表格:学生,地址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 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);
我已经设置了级联所有。需要做什么额外/不同的事情。逆在这里适用吗?
如果适合
您,您应该使用orphanremoval = true
@OneToOne(cascade=CascadeType.ALL, orphanRemoval=true)
@JoinColumn(name="ADDR_ID")
public Address getAddress() {
}
在我的情况下,一对一删除级联不起作用,因为未使用事务。这里工作正常...
@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();