Как я могу использовать двунаправленную связь в спящем режиме для сохранения данных в режиме «один ко многим» с помощью обратного сопоставления? - PullRequest
0 голосов
/ 19 июня 2020

Я новичок в Hibernate и Java, работаю над проектом, связанным со счетами и продуктами. Я работаю над сценарием, в котором в одном счете-фактуре есть еще много продуктов. Я хочу добавить дополнительный столбец для количества.

Во-первых, у меня возникла путаница в отношении отношений, если они верны, чем, пожалуйста, предложите мне, как я могу сохранить данные в InvoiceProduct. java, используя объект Invoice. java?

Если, есть какие-либо проблемы с отношениями, сообщите мне.

Счет-фактура. java

import utils.AbstractTimestampEntity;

import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@Entity
@Table(name = "invoice")
public class Invoice extends AbstractTimestampEntity implements Serializable {

    @Id
    @Column(name = "invoice_number", unique = true, updatable = false, nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Temporal(TemporalType.DATE)
    @Column(name = "invoice_date", nullable = false)
    private Date invoiceDate;

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    private Company company;

    @Column(name = "vehical_number", length = 10)
    private String vehicalNumber;

    @OneToMany(
        mappedBy = "product"
    )
    private List<InvoiceProductModel> products = new ArrayList<>();

    @Temporal(TemporalType.DATE)
    @Column(name = "po_date")
    private Date poDate;

    @Column(name = "po_number", length = 10)
    private String poNumber;

    @Column(name = "payment_status")
    private boolean paymentStatus;

   ... getter and setters.

}

Продукт. java


import utils.AbstractTimestampEntity;

import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.logging.Logger;

@Entity
@Table(name = "Product")
public class Product extends AbstractTimestampEntity implements Serializable {

    private static final Logger LOG = Logger.getLogger(ProductModel.class.getName());

    @Id
    @Column(name = "id", unique = true, nullable = false, insertable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "product_name", nullable = false, unique = true)
    private String description;

    @Column(name = "product_hsn_number", nullable = false, length = 5)
    private int hsn_no;

    @Column(nullable = false)
    private String unit_of_mesaure;

    @Column(nullable = false, length = 3)
    private int tax_rate;

    @OneToMany(
        mappedBy = "product", cascade = CascadeType.ALL,
            orphanRemoval = true, fetch = FetchType.LAZY
    )
    private List<CompanyProductModel> companies = new ArrayList<>();

    @OneToMany(mappedBy = "product")
    private List<InvoiceProductModel> invoices = new ArrayList<>();

   ... getter and setter
 }


InvoiceProductID. java


import javax.persistence.Column;
import javax.persistence.Embeddable;
import java.io.Serializable;
import java.util.Objects;


@Embeddable
public class InvoiceProductID implements Serializable {

    @Column(name = "invoice_id", nullable = false)
    private Long invoiceID;

    @Column(name = "product_id", nullable = false)
    private Long productID;

    public InvoiceProductID(Long invoiceID, Long productID) {
        this.invoiceID = invoiceID;
        this.productID = productID;
    }
    ... getter and setter

InvoiceProduct. java

import utils.AbstractTimestampEntity;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;

@Entity
@Table(name = "invoice_product")
public class InvoiceProduct extends AbstractTimestampEntity implements Serializable {

    @EmbeddedId
    private InvoiceProductID id;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @MapsId("invoice_id")
    @JoinColumn(name = "invoice_id", nullable = false,
        referencedColumnName = "invoice_number")
    private InvoiceModel invoice;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @MapsId("product_id")
    @JoinColumn(name = "product_id", nullable = false,
        referencedColumnName = "id")
    private ProductModel product;

    @Column(name = "product_quantity", nullable = false)
    private int quantity;


    public InvoiceProduct(Invoice invoice, Product product, int quantity) {
        this.id = new InvoiceProductID(invoice.getId(), product.getId());
        this.invoice = invoice;
        this.product = product;
        this.quantity = quantity;
    }
   ...getter and setter
}

Я пытаюсь сохранить данные, используя приведенный ниже код, но получаю ошибка

                Session session = HibernateUtil.getSessionFactory().openSession();
                Transaction tx = session.beginTransaction();
                Invoice invoice = new Invoice();
                invoice.setVehicleNumber("BA01AB1020");
                invoice.setInvoiceDate(new Date(2020, 10, 20));
                invoice.setPoDate(new Date(2020, 10, 05));
                invoice.setPaymentStatus(false);
                invoice.setPoNumber("001");
                invoice.setCompany(
                        new CompanyAbstractEventHandler().alikeByName("Company 1"));

                List<InvoiceProduct> products = new ArrayList<>();

                products.add(new InvoiceProduct(invoice,
                        new ProductAbstractEventHandler()
                                .alikeByName("Product 1"), 200));
                invoice.setProducts(products);

                session.merge(invoice);

                tx.commit();
                session.close();


Hibernate: 
    insert 
    into
        BillingSoftware.invoice_product
        (created_at, updated_at, product_quantity, invoice_id, product_id) 
    values
        (?, ?, ?, ?, ?)
Jun 19, 2020 6:53:46 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 23502, SQLState: 23502
Jun 19, 2020 6:53:46 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: NULL not allowed for column "INVOICE_ID"; SQL statement:
insert into BillingSoftware.invoice_product (created_at, updated_at, product_quantity, invoice_id, product_id) values (?, ?, ?, ?, ?) [23502-200]
Exception in thread "JavaFX Application Thread" javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1364)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:451)
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3210)
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2378)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:447)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101)
    at utils.InvoiceAbstractEventHandler.handle(InvoiceAbstractEventHandler.java:221)
    at utils.InvoiceAbstractEventHandler.handle(InvoiceAbstractEventHandler.java:55)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Node.fireEvent(Node.java:8411)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$353(GlassViewEventHandler.java:432)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:200)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3254)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3779)
    at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:107)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604)
    at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:478)
    at java.util.LinkedHashMap.forEach(LinkedHashMap.java:684)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:475)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:348)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:40)
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102)
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1360)
    ... 54 more
Caused by: org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: NULL not allowed for column "INVOICE_ID"; SQL statement:
insert into BillingSoftware.invoice_product (created_at, updated_at, product_quantity, invoice_id, product_id) values (?, ?, ?, ?, ?) [23502-200]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:459)
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:429)
    at org.h2.message.DbException.get(DbException.java:205)
    at org.h2.message.DbException.get(DbException.java:181)
    at org.h2.table.Column.validateConvertUpdateSequence(Column.java:374)
    at org.h2.table.Table.validateConvertUpdateSequence(Table.java:845)
    at org.h2.command.dml.Insert.insertRows(Insert.java:187)
    at org.h2.command.dml.Insert.update(Insert.java:151)
    at org.h2.command.CommandContainer.update(CommandContainer.java:198)
    at org.h2.command.Command.executeUpdate(Command.java:251)
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:191)
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:152)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197)
    ... 65 more


Спасибо ?.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...