@OneToOne - Cascade全部不保存父ID

时间:2016-08-22 21:18:47

标签: hibernate hibernate-cascade

伙计们!保存孩子"我有问题。 table parent" 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 。 Hibernate 4.3

1 个答案:

答案 0 :(得分:1)

Hibernate忠实地保存了这样一个事实:事实上,你从未将Credentials对象与User对象相关联。尝试在保存之前添加credit.setUser(user);