简体   繁体   中英

Hibernate: Is it possible to persist only a child which will cause persisting a parent as well

Let's say I have a parent table A and a child table B, they have a foreign key linking A.id and B.id, the problem is this parent table and the FK have been created recently and there are too many places which persisting a child table, so I'm waiting for a simple way to persist the parent table and link it to the child table. Is it possible to handle this task by using Hibernate instruments? I was trying to use cascades but no success, looks they only work if we persist a parent entity.

So the structure is the following:

@Entity
class A {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "a_id")
    long id;
}



@Entity
class B {
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   @Column(name = "b_id")
   long id; // FK to a_id
}

class BDao {
    void store(B b) {
       session.save(b); // to many places
}
}

Will appriciate any help, thanks!

Yeah! I've fixed it, just in case somebody wants to know the answer I'm leaving my solution here. Perhaps you guys will spent less time than me solving the same problem. So first you need to use @Inheritance(strategy= InheritanceType.JOINED) annotation to describe the parent entity:

@Entity
@Inheritance(strategy= InheritanceType.JOINED)
@PrimaryKeyJoinColumn(name = "a_id")
public class A {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "a_id")
    protected Integer id;
}

Then describe the child entity like

@Entity
@AssociationOverride(name="a_id", joinColumns = @JoinColumn(name="b_id"))
@PrimaryKeyJoinColumn(name = "b_id")
public class B extends A {
    ...
}

I've left here @AssociationOverride because in my case I have different primary key name so perhaps it helps somebody as well.

That's it! Now when you persist a child entity it will create two rows - one for a parent and one for a child tables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM