hibernate在插入时忽略列

dm7nw8vv  于 2021-07-22  发布在  Java
关注(0)|答案(1)|浏览(333)

所以,我有一个汽车实体,涉及到一个办公室实体和一个保险实体。当我试图将第一辆车插入数据库时,hibernate忽略了我正在插入office\u id的事实,并说它是空的。
以下是汽车实体的代码:

@Entity
@Table(name = "cars")
public class Car {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "brand")
    private String brand;

    @Column(name = "starting_price")
    private Double starting_price;

    @Column(name = "status")
    private Boolean status;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "insurances_insurance_id", insertable=false, updatable=false)
    @JsonIgnore
    private Insurance insurance;
    @Column(name = "insurances_insurance_id")
    private Long insurances_insurance_id;

    @ManyToOne(targetEntity = Office.class)
    @JoinColumn(name = "offices_office_id", nullable = false, insertable = false, updatable = false)
    private Office office;
    @Column(name = "offices_office_id")
    private Long offices_office_id;

    public Car(){}

    public Car(String brand, Double starting_price, Boolean status, Office office){
        this.brand = brand;
        this.starting_price = starting_price;
        this.status = status;
        this.offices_office_id = office.getId();
    }

办公实体:

@Entity
@Table(name = "offices")
public class Office {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "city")
    private String city;

    @Column(name = "street")
    private String street;

    @Column(name = "email")
    private String email;

    @Column(name = "manager")
    private String mangerLastName;

    public Office(){}

    public Office(String city, String street, String email, String manager){
        this.city = city;
        this.street = street;
        this.email = email;
        this.mangerLastName = manager;
    }

主要内容:

public class Main {
    public static void main(String[] args) throws SQLException, ParseException {
        String date1 = "23/03/2020";
        String date2 = "23/03/2030";
        Date date3 = new SimpleDateFormat("dd/MM/yyyy").parse(date1);
        Date date4 = new SimpleDateFormat("dd/MM/yyyy").parse(date2);
        Office office = new Office("Moscow", "Tverskaya",
                "office1@cars.ru", "Ivan Ivanov");
        Car car = new Car("volkswagen", 1000.0, true, office);
        Insurance insurance = new Insurance(date3, date4, 20000.0);
        car.setInsurance(insurance);
        Session session = HibernateSessionFactoryUtil.getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();
        session.save(car);
        transaction.commit();
        session.close();
    }
}

保险和办公室工作按计划进行,我可以把它们插入数据库。这是我得到的结果:

17:32:07.580 [main] DEBUG org.hibernate.engine.spi.ActionQueue - Executing identity-insert immediately
17:32:07.584 [main] DEBUG org.hibernate.SQL - insert into offices (city, email, manager, street) values (?, ?, ?, ?)
Hibernate: insert into offices (city, email, manager, street) values (?, ?, ?, ?)
17:32:07.593 [main] DEBUG org.hibernate.id.IdentifierGeneratorHelper - Natively generated identity: 4
17:32:07.594 [main] DEBUG org.hibernate.resource.jdbc.internal.ResourceRegistryStandardImpl - HHH000387: ResultSet's statement was not registered
17:32:07.597 [main] DEBUG org.hibernate.engine.spi.ActionQueue - Executing identity-insert immediately
17:32:07.598 [main] DEBUG org.hibernate.SQL - insert into insurances (ins_end, ins_start, price) values (?, ?, ?)
Hibernate: insert into insurances (ins_end, ins_start, price) values (?, ?, ?)
17:32:07.601 [main] DEBUG org.hibernate.id.IdentifierGeneratorHelper - Natively generated identity: 14
17:32:07.601 [main] DEBUG org.hibernate.resource.jdbc.internal.ResourceRegistryStandardImpl - HHH000387: ResultSet's statement was not registered
17:32:07.603 [main] DEBUG org.hibernate.engine.spi.ActionQueue - Executing identity-insert immediately
17:32:07.604 [main] DEBUG org.hibernate.SQL - insert into cars (brand, insurances_insurance_id, offices_office_id, starting_price, status) values (?, ?, ?, ?, ?)
Hibernate: insert into cars (brand, insurances_insurance_id, offices_office_id, starting_price, status) values (?, ?, ?, ?, ?)
17:32:07.620 [main] DEBUG org.hibernate.engine.jdbc.spi.SqlExceptionHelper - could not execute statement [n/a]
org.postgresql.util.PSQLException: ОШИБКА: значение NULL в столбце "offices_office_id" отношения "cars" нарушает ограничение NOT NULL
  Подробности: Ошибочная строка содержит (8, volkswagen, 1000, true      , null, null).
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2553)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2285)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:323)
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:473)
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:393)
    at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:164)
    at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:130)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197)
    at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:43)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3200)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3806)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:84)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:645)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:282)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:263)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:317)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:330)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:287)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:123)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:194)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:179)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:75)
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:93)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:636)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:629)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:624)
    at com.AnnaMarunko.CarRentApp.Main.main(Main.java:30)
17:32:07.620 [main] WARN org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 0, SQLState: 23502
17:32:07.621 [main] ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - ОШИБКА: значение NULL в столбце "offices_office_id" отношения "cars" нарушает ограничение NOT NULL
  Подробности: Ошибочная строка содержит (8, volkswagen, 1000, true      , null, null).

抱歉,有些部分不是英文,但基本上是说offices\u office\u id为空,但我在car实体构造函数中清楚地输入了它:

public Car(String brand, Double starting_price, Boolean status, Office office){
        this.brand = brand;
        this.starting_price = starting_price;
        this.status = status;
        this.offices_office_id = office.getId();
    }

创建对象时:

Office office = new Office("Moscow", "Tverskaya",
                "office1@cars.ru", "Ivan Ivanov");
Car car = new Car("volkswagen", 1000.0, true, office);

这里有什么问题?

wz8daaqr

wz8daaqr1#

正如yousaf所说,应该首先保存office示例,这样office.getid()就不会返回null。

相关问题