我有一个小应用程序负责保存数据库中的数据。我正在使用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.
但它对我不起作用。
我正在使用:
答案 0 :(得分:1)
您的地址类应编码如下(假设应使用与生成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);