0

表:学生,地址 Student.ADDR_ID 列映射到 Address.ID

我的学生课上的注释如下

public class Student {

String name, surname;
int rollNumber;
Teacher classTeacher;
Address address;

@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="ADDR_ID")
public Address getAddress() {
    return address;
}
:
:

它在创建和更新案例中运行良好。

如果我将 Student 的地址更改为新地址,则它会创建一个新行,但不会删除旧地址的行。如果我将地址设置为 null 仍然不会删除

例如

 Student s1 = session.get(Student.class, 24);
 Address addr = new Address();
 session.save(addr);
 s1.setAddress(addr);
 session.save(s1);

 or

 Student s1 = session.get(Student.class, 24);
 s1.setAddress(null);

我已经设置了级联所有。需要做哪些额外/不同的事情。Inverse 在这里适用吗?

4

2 回答 2

1

orphanremoval = true如果这对你来说足够了,你应该使用

@OneToOne(cascade=CascadeType.ALL, orphanRemoval=true)
@JoinColumn(name="ADDR_ID")
public Address getAddress() {
}
于 2017-05-23T04:13:24.813 回答
0

在我的情况下,由于未使用事务,一对一删除级联不起作用。在这里它工作正常......

@Entity
@Table(name="student")
public class Student {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private Long id;

    @Column(name="student_name",length=60)
    private String studentName;

    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name = "address_id")
    private Address address;

    //Setter Getter
}

@Entity
@Table(name = "address_table")
public class Address {

    @Id
    @Column(name = "address_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long addressId;

    @Column(name = "street_name", length = 50)
    private String street;

    @Column(name = "city_name", length = 50)
    private String city;

    //Setter Getter
}


Student student = session.get(Student.class, 1L);
session.beginTransaction();
session.delete(employee);
session.getTransaction().commit();
于 2019-01-18T19:50:55.277 回答