休眠。 OneToOne映射问题

时间:2016-04-25 17:18:43

标签: hibernate one-to-one

@Entity
@Table(name="Customer")
public class Customer implements Serializable{

/**
 * This is my Customer entity object
 */
private static final long serialVersionUID = 9037154862690840147L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="Cust_Id")
private int customerId;

@Column(name="First_Name")
private String firstName;

@Column(name="Last_Name")
private String lastName;

@Column(name="Gender")
private String gender;

@Column(name="Email")
private String email;

@Column(name="Password")
private String password;

@Column(name="City")
private String city;

@Column(name="State")
private String state;

@Column(name="Country")
private String country;

@Column(name="Phone_No")
private String phoneNumber;

@Column (name="Zip_Code")
private int zipCode;

@Column(name="LAST_UPDATED_NM")
private String lastUpdatedName;

@Column(name="LAST_UPDATED_DTM")
private Date lastUpdatedTime;


@OneToOne(mappedBy = "customer", cascade = CascadeType.ALL)
private RoleOfUser roleOfUser;





This is my Role of user entity object
@Entity
@Table(name = "role_of_user")
public class RoleOfUser implements Serializable{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "Role_Id")
private Integer roleId;

@Column(name = "Role_Name")
private String roleName;

@Column(name = "First_Name")
private String firstName;

@Column(name="Last_Name")
private String lastName;

@Column(name = "Created_NM")
private String createdName;

@Column(name = "Created_DTM")
private Date createdDate;

@Column(name = "Last_Update_NM")
private String lastUpdatedName;

@Column(name = "Last_Update_DTM")
private Date lastUpdatedDate;

@Column (name = "Status")
private String status;

@OneToOne(cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn
private Customer customer;



@Column(name = "Customer_Cust_Id")
@GeneratedValue(generator="gen")
@GenericGenerator(name="gen", strategy="foreign",  parameters =       @Parameter(name = "property", value = "customer"))
private Integer customerId;

来自客户实体表的customerId需要是RoleOfUser表中Customer_cust_id的外键。 我运行上面的代码,它说Customer_cust_id不能为空。 我如何映射外键? Role_id已经是主键。

1 个答案:

答案 0 :(得分:1)

在我的持久性类中使用原语一直是我的一个小问题因为它可能导致一些误导性的错误,所以我首先要将int customerId更改为Integer customerId

接下来,听起来Customer应该是您的父表,而RoleOfUser应该是孩子。这里的问题是你说你的表是一对一的,但你没有加入@Id的{​​{1}}列。

考虑做这样的事情:

RoleOfUser

但是,最后,如果这些表真的是一对一的,那么为什么不只是让它们成为一个包含更多列的更宽的表?或者,如果允许用户拥有多个角色,那么您需要将@Table(name = "CUSTOMER") public class Customer { @Id @Column(name = "CUST_ID") private Integer customerId; } @Entity @Table(name = "ROLE_OF_USER") public class RoleOfUser { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ROLE_ID") private Integer roleId; @OneToOne @JoinColumn(name = "CUSTOMER_CUST_ID", referencedColumnName = "CUST_ID") private Customer customer } 更改为@OneToOne