我正在尝试学习 Hibernate,我有两个相互关联的类(class);人和地址。 Person 组成 Address 对象,在 db Person 表上有 address_id 列。
基本上:
1) Person 表有列:id, name, age, address_id 2) Table Address 有列:id, street, city
我观察到当我插入一条记录时,它使用 id=1 用于 Person 表,id=2 用于 Address 表。所以它看起来像是从相同的序列生成 PK。实际上一切正常,但为什么会这样,为什么它不在地址表中使用 id=1?
代码如下所示:
@Entity
public class Person {
public Person(){
}
public Person(String name, int age, Adress adress){
this.name = name;
this.age = age;
this.adress = adress;
}
@Id
@GeneratedValue
private int id;
@Column(name = "NAME")
private String name;
@Column(name = "AGE")
private int age;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name="address_id")
private Adress adress;
}
另一个类是:
@Entity
public class Adress {
@GeneratedValue
@Id
private int id;
@Column(name = "STREET")
private String street;
@Column(name = "CITY")
private String city;
public Adress(){
}
public Adress(String street, String city){
this.street = street;
this.city = city;
}
我将保存方法调用为:
private static void addPerson(SessionFactory sessionFactory){
Adress adress = new Adress("Wroclawska", "Krakow");
Person person = new Person("Cemal Inanc", 31, adress);
Transaction tx = null;
Session session = null;
try {
session= sessionFactory.openSession();
tx = session.beginTransaction();
session.save(person);
tx.commit();
}
catch (Exception e){
tx.rollback();
System.out.println("Exeception occured");
}
finally {
session.close();
}
}
最佳答案
由于你使用了默认的Generator策略,所以对于oracle来说,就是Sequence。
在内部,它将在数据库中创建一个序列并从该序列中获取值。
现在您想要为您的两个实体获取单独的序列。你需要指定
@SequenceGenerator()
您必须在代码中进行的更改:
对于个人实体
@Entity
public class Person {
@Id
GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "GeneratorName")
@SequenceGenerator(name="GeneratorName", sequenceName = "seq1")
private int id;
}
对于地址实体
@Entity
public class Adress {
@Id
GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "GeneratorName")
@SequenceGenerator(name="GeneratorName", sequenceName = "seq2")
private int id;
}
应用这些更改后,您将获得从 1 开始的两个 id。
关于hibernate - 两个表中 hibernate 的主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57988344/