我正在学习JPA(2.1)和Hibernate(5.0.4)。 在@OneToOne关系映射练习的情况下,我想基于生成的共享键序列创建单向映射。我能够双向进行。
我能够使用[this blog]完成它,但它看起来像 hack (下面的代码) 有没有更好的方法来映射这种情景?
DDL:
DROP TABLE HIBERNATE.T_USER_DETAILS;
DROP TABLE HIBERNATE.T_USERS;
DROP SEQUENCE HIBERNATE.USERS_SEQ;
-- ON HIBERNATE
CREATE TABLE HIBERNATE.T_USERS (
ID NUMBER(15),
NAME VARCHAR2(100 CHAR),
CONSTRAINT USER_PK PRIMARY KEY (ID)
);
CREATE TABLE HIBERNATE.T_USER_DETAILS (
ID NUMBER(15),
DETAILS VARCHAR2(100 CHAR),
CONSTRAINT UDETAILS_PK PRIMARY KEY (ID),
CONSTRAINT UDETAILS_FK FOREIGN KEY (ID) REFERENCES T_USERS(ID)
);
CREATE SEQUENCE HIBERNATE.USERS_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
的usermodel:
@Entity
@Table(name = "T_USERS")
@SequenceGenerator(name = "users-sequence-generator", sequenceName = "USERS_SEQ", initialValue = 0, allocationSize = 1)
public class UserModel {
private Long id;
private String name;
private UserDetailsModel userDetails;
@Id
@Column(name = "id")
@GeneratedValue(generator = "users-sequence-generator", strategy = GenerationType.SEQUENCE)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
if (userDetails != null) {
userDetails.setId(id);
}
}
@Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToOne(fetch = EAGER, cascade = ALL)
@JoinColumn(name = "id", insertable = false, updatable = false)
public UserDetailsModel getUserDetails() {
return userDetails;
}
public void setUserDetails(UserDetailsModel userDetails) {
this.userDetails = userDetails;
}
}
UserDetailsModel:
@Entity
@Table(name = "T_USER_DETAILS")
public class UserDetailsModel {
@Id
@Column(name = "id")
private Long id;
@Column(name = "details")
private String details;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
}