我使用Hibernate持久保存两个表,User和DistrictUser.User Table有一个复合PK UserPK。
为什么@PrimaryKeyJoinColumn和@PrimaryKeyJoinColumns的结果表DistrictUser相同?
为什么DistrictUser中的列名称前缀为" user _"当我在" name"中明确提到名字时使用@PrimaryKeyJoinColumn或@PrimaryKeyJoinColumns注释中的属性?
@Entity
@Table(name = "DistrictUser")
public class DistrictUser {
@Id
@Column(name = "ID_KEY")
private Long id;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumns( { @JoinColumn(name = "USERS_KEY", referencedColumnName="USERS_KEY"),
@JoinColumn(name = "BEGIN_DATE", referencedColumnName="START_DATE"),
@JoinColumn(name = "END_DATE", referencedColumnName="END_DATE") })
private User user;
// @PrimaryKeyJoinColumns({
// @PrimaryKeyJoinColumn(name = "START_DATE", referencedColumnName = "START_DATE"),
// @PrimaryKeyJoinColumn(name = "END_DATE", referencedColumnName = "END_DATE"),
// @PrimaryKeyJoinColumn(name = "USERS_KEY", referencedColumnName = "USERS_KEY")})
// @ManyToOne()
// private User user;
//@PrimaryKeyJoinColumn(name = "START_DATE", referencedColumnName = "START_DATE")
// @ManyToOne()
// private User user;
//getters and setters
}
@Entity
@Table(name = "USERS")
@IdClass(UserPK.class)
public class User
{
@Id
@Column(name = "USERS_KEY")
private Long userKey;
@Id
@Column(name = "START_DATE")
@Temporal(javax.persistence.TemporalType.DATE)
private Date startDate;
@Id
@Column(name = "END_DATE")
@Temporal(javax.persistence.TemporalType.DATE)
private Date endDate;
//getters and setters
}
public class UserPK implements Serializable {
private static final long serialVersionUID = -7720874756224520523L;
private Long userKey;
private Date startDate;
private Date endDate;
//getters and setters
}
持久化表格的代码
User user = new User();
user.setStartDate(new Date());
user.setEndDate(new Date());
user.setUserKey(1l);
DistrictUser du = new DistrictUser();
du.setId(10l);
du.setUser(user);
session.save(user);
session.save(du);
session.flush();
session.getTransaction().commit();
session.close();
当使用JoinColumns时,DistrictUser表是
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumns( { @JoinColumn(name = "USERS_KEY", referencedColumnName="USERS_KEY"),
@JoinColumn(name = "BEGIN_DATE", referencedColumnName="START_DATE"),
@JoinColumn(name = "END_DATE", referencedColumnName="END_DATE") })
private User user;
当使用@PrimaryKeyJoinColumn取消注释相对代码区域用户
@PrimaryKeyJoinColumn(name = "START_DATE", referencedColumnName = "START_DATE")
@ManyToOne()
private User user;
通过取消注释DistrictUser中的相对代码来使用@PrimaryKeyJoinColumns
@PrimaryKeyJoinColumns({
@PrimaryKeyJoinColumn(name = "START_DATE", referencedColumnName = "START_DATE"),
@PrimaryKeyJoinColumn(name = "END_DATE", referencedColumnName = "END_DATE"),
@PrimaryKeyJoinColumn(name = "USERS_KEY", referencedColumnName = "USERS_KEY")})
@ManyToOne()
private User user;
有人可以指出三种方法之间的差异