两个表中带有 hibernate 的主键

use*_*111 2 hibernate primary-key nhibernate-mapping

我正在尝试学习 Hibernate,并且我有两个彼此相关的课程;人员和地址。Person 组成 Address 对象,并且在数据库 Person 表上有 address_id 列。

基本上:

1) 表 Person 具有列:id、name、age、address_id 2) 表 Address 具有列:id、街道、城市

我观察到,当我插入一条记录时,它使用 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;
}
Run Code Online (Sandbox Code Playgroud)

另一类是:

@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;
    }
Run Code Online (Sandbox Code Playgroud)

我将保存方法称为:

  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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

yas*_*2yj 5

由于你已经使用了默认的Generator策略,所以对于oracle来说,就是Sequence。

在内部,它将在数据库中创建一个序列并从该序列中获取值。

现在您想要获取两个实体的单独序列。您需要指定

@SequenceGenerator()
Run Code Online (Sandbox Code Playgroud)

您必须在代码中进行更改:

对于个人实体

@Entity
public class Person {

    @Id
    GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "GeneratorName")
    @SequenceGenerator(name="GeneratorName", sequenceName = "seq1")
    private int id;    
}
Run Code Online (Sandbox Code Playgroud)

对于地址实体

@Entity
public class Adress {

    @Id
    GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "GeneratorName")
    @SequenceGenerator(name="GeneratorName", sequenceName = "seq2")
    private int id;
}
Run Code Online (Sandbox Code Playgroud)

应用这些更改后,您将获得从 1 开始的 id。