gpt4 book ai didi

java - 执行一对一映射时,Hibernate 不会填充第二个表

转载 作者:行者123 更新时间:2023-11-30 10:33:35 25 4
gpt4 key购买 nike

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

用户类

@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

地址类

@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() 方法时,该方法负责在这两个表中保存数据,只有用户表被填满。

我找到了这个解决方案 Hibernate @OneToOne with Shared Primary Key(bidirectional). Dependent entity not persisted in DB.

但这对我不起作用。

我正在使用:

  • hibernate 4.3.6.Final
  • Spring 4.3.6.RELEASE

最佳答案

您的 Address 类应编码如下(假设应使用与生成 id 的用户相同的 Id 创建 Address):

@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);

关于java - 执行一对一映射时,Hibernate 不会填充第二个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42141198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com