伙计们!我在保存"子"表的父id时遇到问题。当持久化子对象时,父id为null的列。。
父级(用户类(
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private long userId;
@Column(name = "name")
private String name;
@Column(name = "address")
private String address;
@Column(name = "postcode")
private int postCode;
子级(凭证类(
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name="credential")
public class Credentials {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="id")
private int id;
@Column(name="username")
private String username;
@Column(name="password")
private String password;
@OneToOne(cascade= CascadeType.ALL )
@JoinColumn(name="user_id")
public User user;
应用程序类
User user = new User();
user.setAddress("asdkapoda");
user.setName("xaxaxaxa");
user.setPostCode(3423);
Credentials credit = new Credentials();
credit.setPassword("sadsad");
credit.setUsername("sdadsa");
session.save(credit);
在数据库中,Credential的user_id=NULL。休眠4.3
Hibernate忠实地保存了这样一个事实,即实际上从未将Credentials
对象与User
对象关联。尝试在保存之前添加credit.setUser(user);
。