开发者

hibernate and DB triggers

开发者 https://www.devze.com 2023-03-02 21:23 出处:网络
I am using hibernate and pre-insert triggers in database. Let me explain the scenario. I have two tables say A and B. In both the tables Primary keys are inserted through pre-insert triggers. Primary

I am using hibernate and pre-insert triggers in database. Let me explain the scenario. I have two tables say A and B. In both the tables Primary keys are inserted through pre-insert triggers. Primary key from A is foreign key i开发者_如何学Gon B. So when I insert into these tables the foreign key column in B should get populated with triggered value of A (the primary key value). But its not happening as I am expecting. Primary keys in both tables are inserted properly but the foreign key column keeps getting value 0 instead of the triggered value which it should actually get. Table have one-to-many relationship.

The two tables are like -

class Employee {
   private int RECORDID;
   @OneToMany(cascade=cascadeType.ALL)
   @JoinColumn(name="MASTERRECORDID" , referencedColumnName="RECORDID")
   private Collection<EmployeeDetails> employeeDetails = new ArrayList<EmployeeDetails>();
}

class EmployeeDetails{
   private int RECORDID;
   private int MASTERRECORDID;
}

Thanks


Hibernate doesn't support primary keys generated by triggers out of the box.

You can use a custom identity generator described in Before Insert Trigger and ID generator:

class Employee {
    @Id @GeneratedValue(generator = "trigger_gen")
    @GenericGenerator(name = "trigger_gen", 
        value = "jpl.hibernate.util.TriggerAssignedIdentityGenerator")
    private int RECORDID; 
    ...
}

Alternatively, if your entities have non-PK unique field, you can use built-in select generator.

See also:

  • 5.1.2.2. Identifier generator
0

精彩评论

暂无评论...
验证码 换一张
取 消