0

伙计们 !我在保存“子”表父的 id 时遇到问题当持久化子对象时,具有父 id 的列为空..

父级(用户类)

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

4

1 回答 1

1

Hibernate 忠实地保存了您实际上从未将Credentials对象与User对象关联的事实。尝试credit.setUser(user);在保存前添加。

于 2016-08-22T21:23:45.090 回答