I am persisting a parent-child object using Hibernate. Here Parent comes with an id which is a primary key from the sender system and always be unique.
For every new incoming object with parent id doesn’t exist then parent object will be inserted in Parent Table with my application database specific primary key ParentPK and child rows will be inserted with corresponding ParentFK .
If parent id already exist in my application database then I have to only update the Parent Table. But How I am supposed to insert ParentFK for the child rows if ParentPK already exists ?
Table Structure:
CREATE TABLE Parent(
ParentPK bigint NOT NULL,
TypeCode int NULL,
Id bigint NULL,
FullName varchar(50) NULL
}
CREATE TABLE Child(
ChildPK bigint NOT NULL,
Code int NULL,
Designation int NULL,
ParentFK bigint NULL
}
ALTER TABLE Child ADD
CONSTRAINT FK_Child_Parent FOREIGN KEY(ParentFK)
REFERENCES Parent (ParentPK)
Entity Classes:
@Entity
@Table(name="Parent")
public class ParentType extends HibernateEntity{
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="KeyGenerator")
@GenericGenerator(name = "KeyGenerator",
strategy = "services.db.hibernate.KeyGenerator")
protected Long parentPK;
protected String id;
protected int typeCode;
protected String fullName;
@OneToMany(mappedBy="parent",targetEntity=ChildType.class,fetch=FetchType.LAZY,cascade = CascadeType.ALL)
protected List<ChildType> child;
}
@Entity
@Table(name="Child")
public class ChildType extends HibernateEntity{
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="KeyGenerator")
@GenericGenerator(name = "KeyGenerator",
strategy = "services.db.hibernate.KeyGenerator")
protected Long childPK;
protected int code;
protected int designation;
@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name="ParentFK")
protected ParentType parent;
}
In Hibernate (and JPA) you don’t work primarily with IDs but with instances of objects. So instead of setting the ID of the parent, you need to load an instance of
ParentTypeand then set it into an instance ofChildType.In JPA (I’m more used to JPA) it would be something like:
In Hibernate it would be something like