执行一对一映射时,Hibernate 不填充秒 table

Hibernate doesn't fill second table when one-to-one mapping is performed

我有一个小应用程序负责在数据库中保存数据。为此,我正在使用 Hibernate。下面是我的代码:

用户class

@Entity
@Table(name = "USERS")
@Transactional
public class User implements Serializable{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "USER_ID")
private int userId;

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

@Column(name = "SURNAME")
private String surname;

@Column(name = "AGE")
private int age;

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

@OneToOne(fetch = FetchType.LAZY, mappedBy = "user", cascade = CascadeType.ALL)
private Address address;

public User() {

}

public User(String firstName, String secondName, int age, String email) {
    this.firstName = firstName;
    this.surname = secondName;
    this.age = age;
    this.email = email;
}

// GETTERS/SETTERS

地址class

@Entity
@Table(name = "ADDRESS")
@Transactional
public class Address implements Serializable{

/**
 * 
 */
private static final long serialVersionUID = 1L;

@GenericGenerator(name = "generator", strategy = "foreign", parameters = @Parameter(name = "property", value = "user"))
@Id
@GeneratedValue(generator = "generator")
@Column(name = "USER_ID", unique = true, nullable = false)
private int addressId;

@Column(name = "STREET")
private String street;

@Column(name = "STREET_NUMBER")
private String streetNumber;

@Column(name = "FLAT_NUMBER")
private String flatNumber;

@Column(name = "POSTAL_CODE")
private String postalCode;

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

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

@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn(name = "USER_ID")
private User user;


public Address() {

}

public Address(String street, String streetNumber, String flatNumber, String postalCode, String city, String country) {
    this.street = street;
    this.streetNumber = streetNumber;
    this.flatNumber = flatNumber;
    this.postalCode = postalCode;
    this.city = city;
    this.country = country;
}

//GETTERS/SETTERS

并且当我执行 save() 方法时,该方法负责在这两个 table 中保存数据,只有用户 table 被填满。

我找到了这个解决方案

但这对我不起作用。

我正在使用:

您的地址 class 应编码如下(假设应使用与生成 ID 的用户相同的 ID 创建地址):

@Id
@Column(name = "USER_ID", unique = true, nullable = false)
private int addressId;


@MapsId
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "USER_ID", referencedColumnName = "USER_ID")
private User user;

坚持期间

User u = new User();
// populate u fields

Address a = new Address();
a.setUser(u);
// populate a fields

session.persist(a);