为什么Hibernate需要@GeneratedValue进行级联?

时间:2018-03-19 09:41:47

标签: java hibernate spring-data-jpa

我想要坚持一个实体,它既没有标识符的生成值,也有级联持久存储另一个实体。然而,这种组合似乎不可能。我正在使用Spring Data JPA来保存实体。

假设您有两个实体,例如学生和地址。对于想要保留注册日期的学生(让我们假设它始终是唯一的),姓名和地址。从您想要的地址出发,为了简单起见,只保存街道。保存Student实体时,要级联保留Address实体。所以你创建了以下实体。

@Entity
public class Student {

    @Id
    private LocalDateTime registrationDateTime;

    @Column(nullable = false)
    private String name;

    @ManyToOne(targetEntity = Address.class, cascade=CascadeType.PERSIST)
    private Address address;

    public Student(LocalDateTime registrationDateTime, String name, Address address) {
        setRegistrationDateTime(registrationDateTime);
        setName(name);
        setAddress(address);
    }

    public Student() {
    }

    // ...getters and setters omitted...

}

@Entity
public class Address {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column
    private String street;

    public Address(String street) {
        setStreet(street);
    }

    public Address() {
    }

    // ...getters and setters omitted...

}

执行以下代码时,两个实体都是持久的,但street为NULL。

Student student = new Student(LocalDateTime.now(), "John Doe");
student.setAddress(new Address("Mainstreet"));
studentRepository.save(student);

当我从LocalDateTime属性中删除@Id注释并添加以下代码时,地址将被正确保存。

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

这些是Hibernate执行的查询(由于该实体需要地址的id,所以它首先插入学生的方式似乎很奇怪。)

Hibernate: 

    alter table Student 
       drop constraint FKf12myy73nsf6soln9xli8th80
Hibernate: 

    drop table Address
Hibernate: 

    drop table Student
Hibernate: 

    drop sequence hibernate_sequence restrict
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
Hibernate: 

    create table Address (
       id integer not null,
        street varchar(255),
        primary key (id)
    )
Hibernate: 

    create table Student (
       dateTime timestamp not null,
        name varchar(255) not null,
        address_id integer,
        primary key (dateTime)
    )
Hibernate: 

    alter table Student 
       add constraint FKf12myy73nsf6soln9xli8th80 
       foreign key (address_id) 
       references Address
Hibernate: 
    select
        student0_.dateTime as dateTime1_3_0_,
        student0_.address_id as address_3_3_0_,
        student0_.name as name2_3_0_ 
    from
        Student student0_ 
    where
        student0_.dateTime=?
Hibernate: 

values
    next value for hibernate_sequence
Hibernate: 
    insert 
    into
        Student
        (address_id, name, dateTime) 
    values
        (?, ?, ?)
Hibernate: 
    insert 
    into
        Address
        (street, id) 
    values
        (?, ?)
Hibernate: 
    update
        Student 
    set
        address_id=?,
        name=? 
    where
        dateTime=?

0 个答案:

没有答案