Hibernate OneToMany generated foreign key - java

I have the following table structure:
parent(parentId)
child(childId, parentId fk)
Then, I have the following objects:
#Entity
#Table(name = "parent")
public class Parent {
#Id
#GeneratedValue(...)
private String id;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinColumn(name = "parentId")
Set<Child> children
}
#Entity
#Table(name = "child")
public class Child {
#Id
#GeneratedValue(...)
private String id;
#Column(...)
private String parentId;
}
Now, I create a transient parent and child, and I add the child to the parent, then save the parent:
Parent parent = new Parent();
parent.children.add(new Child());
parentDao.save(parent);
I get the exception:
org.hibernate.PropertyValueException: not-null property references a null or transient value
My question: How can I get the parentId in the child class to automatically be set to the value generated by the insertion of the parent?

I would re-arange your class structure as follows:
#Entity
#Table(name = "parent")
public class Parent {
#Id
#GeneratedValue(...)
private String id;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinColumn(name = "parentId")
Set<Child> children
}
#Entity
#Table(name = "child")
public class Child {
#Id
#GeneratedValue(...)
private String id;
#Column(...)
private Parent parent;
}
Then when hibernate fetches the parent class, and initializes the set of children, the child class will have a reference to the parent class. Then to get the parentId, you would call:
Child c = new Child()....
c.parent.id;

Your child shouldn't have a private String parentId, but a private Parent parent, and when you parent.children.add(child), you must also child.setParent(parent). See the prototypical parent-child relationship example in the Hibernate reference and the bidi one-to-many section of the annotation reference.

Related

Change the way hibernate looks up related data?

Let's say I have the following "parent" pojo...
#Entity
#Table(name = "parent")
public class Parent{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#OneToMany(fetch=FetchType.LAZY, mappedBy = "parent", cascade = {CascadeType.ALL})
#JsonIgnoreProperties("parent")
List<Child> children;
}
and I have the following child POJO :
#Entity
#Table(name = "child")
public class Child{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne
#JoinColumn(name="parent_id")
private Parent parent;
}
The result of this will be that I have two tables, and my jpa repository will perform queries using the parent_id field within the child table.
However, What if I want it be like a lookup, where by there is a third table for the relationship, where I have the child id and the parent id as a row, and that would be the relationship? can I modify my spring - jpa / hibernate setup for that? If so, some help would be appreciated!

Retrieving related objects in spring boot using hibernate?

I have this "Parent" class :
#Entity
#Table(name = "parent_table")
public class Parent {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
#OneToMany(fetch=FetchType.LAZY, mappedBy = "parent", cascade = {CascadeType.ALL})
List<Child> children;
}
And, I have the following child class :
#Entity
#Table(name = "children")
public class Child {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long childId;
#ManyToOne
#JoinColumn(name="parent_id")
private Parent parent;
private String name;
}
I am also sending this as my request body :
{
"firstName": "Test",
"lastName": "Parent",
"children":[{
"name":"jack"
},
{
"name":"jill"
}
]
}
The good news is that is that I can write these children to the database directly from the parent repository, however... when I do my GET, to get a parent, it comes back without the child entities (even though they are in the database, in their table)
SEMI-USEFUL UPDATE (MAYBE?) : I have noticed that the parent_id field in the database for the child records doesn't seem to be getting populated! No idea why!
You are creating the relationship with the wrong column names.
Your parent class has id column defined as:
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
That will generate a column id in your parent table.
Your child class has foreign key defined as:
#ManyToOne
#JoinColumn(name="parent_id")
private Parent parent;
You indicate to look for parent_id column within parent table to make a relationship. Such column does not exist.
If you wish to indicate foreign key column name must be parent_id you have to define it as:
#ManyToOne
#Column(name = "parent_id") // Your child field
#JoinColumn(name="id") // Your parent id field
private Parent parent;

Spring-boot JPA entity OneToOne adding new child with relation to parent

I cannot figure out how to simply relate a child entity to and existing parent.
#Entity
#Table(name = "parent")
#Document(indexName = "parent")
public class Parent implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#Column(name = "name")
private String name;
#OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinColumn(unique = true)
private Child child;
//getters, setters
}
Child
#Entity
#Table(name = "child")
#Document(indexName = "child")
public class Child implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#Column(name = "name")
private String name;
#OneToOne(mappedBy = "child")
private Parent parent;
//getters, setters
}
These are the two basic models.
The parent already exists within the database, and I want to add a new child in relation.
Child childEntity = childRepository.save(child);
The child is populated as follows:
child.json
{
"name": "smallChild",
"parent": { "id" : "1" }
}
I want to be able to save the child, and have it automatically have a relation to the parent.
I did some really nasty code...
Save the Child without a parent for the ID
Query the database for the parent by ID
Set the child to the parent entity
Save the Parent with the new child
Set the Parent entity TO the child entity
Resave the child with the parent.
This ended up being 6-ish database queries.
I tried watching a few course videos from lynda.com, but it didn't help.
Thanks!
Either the Parent Primary Key or the complete entity is required.
If the parent's ID available, then the extra query for fetching parent object is not required if the goal is to just save.
If you have the parent's Id available with you then you can save the child entity as:
Child child = new Child();
//...
//Setters for child
//...
//Now just create a parent object and set the id to it
Parent p = new Parent();
p.SetId(parentId); // as the parentId is already vailable
child.setParent(p);
Child childEntity = childRepository.save(child);

Child table not having parent's id as foreign key - JPA/Hibernate

Maybe a very obvious answer exists but I cant see it.
I have a parent table Parent and a child Table Child.
#Entity
#Table(name="PARENT")
public class Parent implements Serializable {
#Id #GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="PARENT_ID")
private int parentId;
#JsonBackReference
#OneToMany(mappedBy="parent", cascade = CascadeType.ALL)
private List<Child> childs;
....
}
And the child entity.
#Entity
#Table(name="CHILD")
public class Child implements Serializable {
#EmbeddedId
private ChildPK id;
#ManyToOne
#JsonManagedReference
#JoinColumn(name="PARENT_ID",insertable = false, updatable = false, referencedColumnName = "PARENT_ID")
private Parent parent;
....
}
The composite primary key being:
#Embeddable
public class ChildPK implements Serializable {
#Column(name="CTGRY_ID", insertable=false, updatable=false)
private int ctgryId;
#Column(name="PARENT_ID", insertable=false, updatable=false)
private int parentId;
....
}
Now in my service method, i set the relation both ways
childItem.setParent(parent);
parent.setChilds(childItemList);
and call save on the entity:
parentDao.save(parent);
This creates a new entry for the PARENT table as expected with a pk generated by the table identity. Creates a new insert in the CHILD table as expected with a pk generated by the table identity.
However, the fk of the child entry should have been the parentId, but it comes as 0!
Am i missing something?
Although this problem is not unique, when I tried looking for similar issues online, few of the suggestions didn't appear to be relevant.
Please let me know in case you need more details.
Thanks!
You are making both id's entries not insertable (one must be insertable, or the JPA implementation wont know from where take the id):
#ManyToOne
#JsonManagedReference
#JoinColumn(name="PARENT_ID", insertable = false, updatable = false, referencedColumnName = "PARENT_ID")
private Parent parent;
And
#Column(name="PARENT_ID", insertable=false, updatable=false)
private int parentId;
You should remove the insertable = false from parent object (first example).
Other option is removing the insertable false from the second one and making it "by hand" in the #prepersist:
#PrePersist
protected setIdsBeforeSave() {
this.id = new ChildPK(parent.Id, categoryId);
}
Edit
Option 1
#Entity
#Table(name="CHILD")
public class Child implements Serializable {
#EmbeddedId
private ChildPK id;
#ManyToOne
#JsonManagedReference
#JoinColumn(name="PARENT_ID", referencedColumnName = "PARENT_ID")
private Parent parent;
....
}
And the other classes remain the same
Option 2
#Entity
#Table(name="CHILD")
public class Child implements Serializable {
#EmbeddedId
private ChildPK id;
....
#PrePersist
protected void setIdsBeforeSave() {
//You set the parent ID, so wont be null, idk what category means, that why i just put the 0
this.id = new ChildPK(parent.Id, 0);
}
}

Why does setting ManyToOne parent early causes flush to fail?

I am creating a JPA entity with a ManyToOne relationship. Why does having child.setParent(parent); cause the following fail during flush():
org.apache.openjpa.persistence.ArgumentException: Missing field for property "parent_id" in type "class test.ChildPrimaryKey".
The test code that fails:
Parent parent = new Parent();
Child child = new Child();
ChildPrimaryKey childPrimaryKey = new ChildPrimaryKey();
childPrimaryKey.setLookupId(1);
child.setId(childPrimaryKey);
child.setParent(parent); // <-- FAIL because of this
// Begin transaction
entityManager.clear();
entityManager.getTransaction().begin();
LOGGER.info("Persisting parent without child.");
entityManager.persist(parent);
LOGGER.info("Updating parent with child.");
childPrimaryKey.setParentId(parent.getId());
parent.getChildren().add(child);
entityManager.merge(parent);
// Fail happens at flush
entityManager.flush();
Entities:
#Embeddable
public class ChildPrimaryKey {
#Column(name = "lookup_id")
private int lookupId;
#Column(name = "parent_id")
private long parentId;
}
#Entity
#Table(name = "child")
public class Child {
#EmbeddedId
private ChildPrimaryKey id;
#MapsId("parent_id")
#ManyToOne
private Parent parent;
}
#Entity
#Table(name = "parent")
public class Parent {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private long id;
#OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Child> children;
}
If I remove child.setParent(parent); statement, then my code passes. Using OpenJPA 2.2.2
I beleive your MapsId should be #MapsId("parentId") based on the class structure you've presented. The value of MapsId is an attribute, not a column name.

Categories