MIssing parent reference in a bidirectional hibernate mapping - spring

I have a spring rest backend with two entities with a bidirectional relationshop (one-to-many, many to one). To overcome nested fetching issues, #JsonManagedReference/#JsonBackReference has been used for a perent/child relationship between entities.
The entites look as this:
#Entity
#Table(name = "Parent")
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Parent implements java.io.Serializable {
private Integer id;
private List<Child> childList;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "ID", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
#JsonManagedReference
public List<Child> getChildList() {
return childList;
}
public void setChildListe(List<Child> childListe) {
this.childList = childList;
}
}
#Entity
#Table(name = "Child")
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Child implements java.io.Serializable {
private Integer id;
private Parent parent;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "ID", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "ParentID")
#JsonBackReference
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
}
This works fine when fetching the Parent element, the childset is then fetched alongside and displayed as an json-array.
However, there is no reference to parent in the child element due to the usage of jsonbackreferance.
How can solve this issue ? I need parent reference when fetching child

That would lead to an infinite loop when serializing to JSON. That's the whole reason we don't do bi-direction JSON relationships.
What I would do is add an additional column to the child entity if you need the ID alone.
private Integer parentId;
#Column(name = "ParentID", insertable=false, updateable=false)
public Integer getParentId() {
return parentId;
}

Related

ManyToOne with jsonb Colum

There are my classes:
Parent
#Entity
#NoArgsConstructor
#Data
#AllArgsConstructor
public class Parent {
#Id
private String id;
private String name;
private String ssn;
#Valid
#Type(type = "json")
#Column(columnDefinition = "jsonb")
#OneToMany(mappedBy="parent ", cascade = CascadeType.ALL)
private List<Child> children;
}
Child
#Entity
#NoArgsConstructor
#Data
#AllArgsConstructor
public class Child implements Serializable {
#Id
private String name;
private String parentId;
#Valid
#Type(type = "json")
#Column(columnDefinition = "jsonb")
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "parentId", referencedColumnName = "id", insertable = false, updatable = false)
private Parent parent;
}
Parent Mapper
#Mapper
public interface ParentMapper {
#Mapping(target = "id", expression = "java(setId(parent.getName(), parent.getSsn()))")
ParentEntity toParentEntity(CreateParent parent);
Parent toParent(ParentEntity parentEntity);
default String setId(String name, String ssn) {
if (StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(ssn)) {
return String.format("%s+%s", name, ssn);
} else {
return null;
}
}
}
child mapper
#Mapper
public interface ChildMapper {
ChildEntity toChildEntity(CreateChild child, String parentId, String chaildName);
Child toChild(ChildEntity childEntity);
}
so there is an issue, creating and saving child object doesn't persist parent property of child object
Parent p = new Parent("somename","123456");
parentRepository.save(p);
Child c = new Child("somename");
c.setParentId(p.getId());
ChildEntity saved = childRepository.save(c);
saved.getParent() => returns null
ParentEntity savedParent = parentRepository.findById(p.getId());
savedParent.getChildren() => return null
Not sure what i done wrong ...

can i retrieve child entity containing parent entity id by using Spring Data Jpa one-to-many unidirectional relationship

Here is my parent entity:
#Entity
public class Parent {
#Id
int parentId;
String name;
#OneToMany()
#JoinColumn(name="parent_id")
List<Child> childList;
}
public class Child {
int childId;
//if i am taking this property as non-transient application won't run. but i need parent Id without changing the class structure..
#Transient
int parentId;
// ... some other properties
}
Insertion is successful as two tables are created : parent(id,name),
child(id,name,parent_id).
But when I retrieve the Parent record then in the Child object, the
parentId property remains 0.
i found a way to retrieve the parentid from the child entity by doing a bidirectional mapping of the Parent-child relationship. You can get the ParentId by using a getter method from the child entity that returns the parentId.
Parent Entity
#Entity
#Table(name = "Parent")
public class Parent implements Serializable {
#Column(name = "ID", nullable = false, length = 10)
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int Id;
#Column(name = "Name")
public String name;
#OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
private Set<Child> children = new HashSet<>();
public Parent() {
}
//getters and setters omitted for brevity
}
//Child Entity
#Entity
#Table(name = "Child")
public class Child implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int Id;
#Column(name = "Name")
private String name;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "parentId", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
private Parent parent;
public Child() {
}
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#JsonIgnore
public Parent getParent() {
return parent;
}
//getter method to retrieve the parent id in the child entity
public int getParent_Id(){
return parent.getId();
}
public void setParent(Parent parent) {
this.parent = parent;
}
}
Notice the method getParent_Id() which returns the parent Id, since getter methods are used to return object, the parentId would be returned as part of the child entity anytime it is fetched.
Also note the use of #JsonIgnore on the getParent() method, this to avoid an infinite recursion going on during serialization since Parent refers to Child and Child refer to Parent.

Spring JPA EntityGraph fetches all lazy loaded properties

I've worked with Spring and Hibernate. Now having a look at Spring Data JPA (2.0.3) with JPA 2.2
AgencyTicketType
#Entity
#Table(name = "agency_ticket_type", catalog = "test")
public class AgencyTicketType implements java.io.Serializable {
private Long id;
private String name;
private Agency agency;
private Set<AgencyTicketCategory> agencyTicketCategories = new HashSet<AgencyTicketCategory>(0);
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "name", nullable = false, length = 100)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "agency_id", nullable = false)
public Agency getAgency() {
return this.agency;
}
public void setAgency(Agency agency) {
this.agency = agency;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "agencyTicketType")
public Set<AgencyTicketCategory> getAgencyTicketCategories() {
return this.agencyTicketCategories;
}
public void setAgencyTicketCategories(Set<AgencyTicketCategory> agencyTicketCategories) {
this.agencyTicketCategories = agencyTicketCategories;
}
}
AgencyTicketCategory
#Entity
#Table(name = "agency_ticket_category", catalog = "waytest")
public class AgencyTicketCategory implements java.io.Serializable {
private Long id;
private AgencyTicketType agencyTicketType;
private String name;
private BigDecimal price;
private Set<TripTicket> tripTickets = new HashSet<TripTicket>(0);
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "agency_ticket_type_id", nullable = false)
public AgencyTicketType getAgencyTicketType() {
return this.agencyTicketType;
}
public void setAgencyTicketType(AgencyTicketType agencyTicketType) {
this.agencyTicketType = agencyTicketType;
}
#Column(name = "name", nullable = false, length = 100)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "price", nullable = false, precision = 8)
public BigDecimal getPrice() {
return this.price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "agencyTicketCategory")
public Set<TripTicket> getTripTickets() {
return this.tripTickets;
}
public void setTripTickets(Set<TripTicket> tripTickets) {
this.tripTickets = tripTickets;
}
}
Repository
public interface TicketTypeRepository extends JpaRepository<AgencyTicketType, Long> {
#EntityGraph(attributePaths={ "agencyTicketCategories" }, type=EntityGraphType.LOAD)
#Query("select type from AgencyTicketType type where type.agency.code=?1")
List<AgencyTicketType> findByAgency(String agencyCode);
}
Service
#Service
public class TicketServiceImpl implements TicketService {
#Autowired private TicketTypeRepository ticketType;
#Transactional(readOnly=true)
#Override
public List<AgencyTicketType> findByName(String code) {
return ticketType.findByAgency(code);
}
}
When debugged on Service, it seems, the query eagerly fetches all the lazy loaded properties - agency, agencyTicketCategories - and all their inner lazy loaded properties, which leads to JSON serilization error.
Need to fetch only these
AgencyTicketTypes [
{
id, name,
agencyTicketCategories [
{id,name,price},....
]
},.....
]
Can I do this with #EntityGraph? What I am missing?
Specifying lazy loading is only a hint for the JPA provider. Depending on the provider you use (Hibernate, EclipseLink etc.) it may be completely ignored and the dependencies may be eagerly fetched.
What you need to do is configure how your classes are mapped to json. Assuming you are using Jackson you may need to use annotations like #JsonIgnore or #JsonView. You may also map your class that only has the fields you need.
You can use Jackson annotations #JsonBackReference/#JsonManagedReference. They address problem of infinite recursion with bidirectional links in object model. As far as I understand it is your case.
See http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion for more information.
One thing to point is that debugging while the transaction is open (touching the collection) will cause it to be loaded even if at real time it doesn't .. the other thing is that as #Apokralipsa mentioned , LAZY loading is just a hint that can be totally ignored and should never be relied upon whatever technique you are using

Spring Data JPA - ManyToOne unable to delete child without modifying parent list

I struggle for a week with the following problem:
How is it possible to delete a child entity through a repository without modifying the List on the owning (parent) side of the relation?
Thanks in advance.
I am hoping for some answers!
The child class:
#Entity
#Table(name = "child")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Child implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#ManyToOne
private Parent parent;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
}
And the parent class:
#Entity
#Table(name = "parent")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Parent implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true)
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Child> children = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Set<Child> getChildren() {
return children;
}
public void setChildren(Set<Child> children) {
this.children = children;
}
public Parent addChild(Child child) {
this.children.add(child);
child.setParent(this);
return this;
}
public Parent removeChild(Child child) {
this.children.remove(child);
child.setParent(null);
return this;
}
}
And here the test:
#Test
#Transactional
public void testParentToChildRelationShip() {
Parent parent = new Parent();
Child child = new Child();
parent.addChild(child);
parent.addChild(new Child());
parent.addChild(new Child());
parent.addChild(new Child());
parentRepository.save(parent);
Assertions.assertThat(parentRepository.count()).isEqualTo(1L);
Assertions.assertThat(childRepository.count()).isEqualTo(4L);
childRepository.delete(child);
Assertions.assertThat(parentRepository.count()).isEqualTo(1L);
// fails
Assertions.assertThat(childRepository.count()).isEqualTo(3L);
parentRepository.delete(parent.getId());
Assertions.assertThat(parentRepository.count()).isEqualTo(0L);
Assertions.assertThat(childRepository.count()).isEqualTo(0L);
}
The test would work if I insert before deleting the child,
child.getParent().removeChild(child);
but I want to avoid calling this.
Is there a way to make it work with just calling the Child-JPA-Repository.delete method? Or other annotations that I missed?
Since child has association with parent you are facing this issue, you need to remove the link between child and parent either using
parent.removeChild(child);
or
child.getParent().removeChild(child);
Remove these lines from your parent class and also setter and getter of children
#OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true)
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Child> children = new HashSet<>();
I think you can remove child mapping from your parent class so you can easily delete the child row using ChildRepository delete() method but problem is that you have to save your child manually using ChildRepository save(). You can not save child object with parent object using ParentRepository. Change your Test code like below for saving child and parent
Parent parent = new Parent();
Parent parent = parentRepository.save(parent);
Child child = new Child();
child.setParent(parent);
childRepository.save(child);

how to rectify this mapping exception( Use of #OneToMany or #ManyToMany targeting an unmapped class)

Hi I am getting some mapping exception please follow the below error
org.hibernate.AnnotationException: Use of #OneToMany or #ManyToMany targeting an unmapped class: com.cmr.daos.child.domain.Child.medications[com.cmr.daos.child.domain.Medications]
at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1185)
at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:710)
at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:645)
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:65)
at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1716)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1423)
at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1375)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:720)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:188)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1571)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1509)
... 62 more
My domain class:
public class Child extends AuditProperties implements java.io.Serializable {
#Expose private Long childId;
#Expose private String firstName;
#Expose private String lastName;
private Set<Allergies> allergies = new HashSet<Allergies>();
private Set<Medications> medications = new HashSet<Medications>();
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "child")
#JsonManagedReference
public Set<Medications> getMedications() {
return this.medications;
}
public void setMedications(Set<Medications> medications) {
this.medications = medications;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "child")
#JsonManagedReference
public Set<Allergies> getAllergies() {
return this.allergies;
}
public void setAllergies(Set<Allergies> allergies) {
this.allergies = allergies;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "CHILD_ID", unique = true, nullable = false)
public Long getChildId() {
return this.childId;
}
public void setChildId(Long childId) {
this.childId = childId;
}
#Column(name = "FIRST_NAME", nullable = false, length = 64)
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "LAST_NAME", nullable = false, length = 64)
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Here my mapped classs:
public class Medications extends AuditProperties implements java.io.Serializable{
#Expose private Long medicationId;
#Expose private String hasMedication;
#Expose private String medicationType;
#Expose private transient Child child;
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "CHILD_ID")
#JsonBackReference
public Child getChild() {
return child;
}
public void setChild(Child child) {
this.child = child;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "MEDICATION_ID", unique = true, nullable = false)
public Long getMedicationId() {
return medicationId;
}
public void setMedicationId(Long medicationId) {
this.medicationId = medicationId;
}
#Column(name = "HAS_MEDICATION", nullable = false, length = 3)
public String getHasMedication() {
return hasMedication;
}
public void setHasMedication(String hasMedication) {
this.hasMedication = hasMedication;
}
#Column(name = "MEDICATION_TYPE", length = 64)
public String getMedicationType() {
return medicationType;
}
public void setMedicationType(String medicationType) {
this.medicationType = medicationType;
}
}
Here another mapped class:
#Entity
#Table(name = "ALLERGIES")
public class Allergies extends AuditProperties implements java.io.Serializable {
#Expose private Long allergyId;
#Expose private String hasAllergies;
#Expose private String allerigyType;
#Expose private transient Child child;
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "CHILD_ID")
#JsonBackReference
public Child getChild() {
return child;
}
public void setChild(Child child) {
this.child = child;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "ALLERGY_ID", unique = true, nullable = false)
public Long getAllergyId() {
return allergyId;
}
public void setAllergyId(Long allergyId) {
this.allergyId = allergyId;
}
#Column(name = "HAS_ALLERGIES", length = 3)
public String getHasAllergies() {
return hasAllergies;
}
public void setHasAllergies(String hasAllergies) {
this.hasAllergies = hasAllergies;
}
#Column(name = "ALLERIGY_TYPE", length = 20)
public String getAllerigyType() {
return allerigyType;
}
public void setAllerigyType(String allerigyType) {
this.allerigyType = allerigyType;
}
}
Here i mentioned one child class, allergy class and medication class.Here i mapped child object to both the classes(allergy,medications) then i will get this exception.please help me abot this exception
As the exception says:
Use of #OneToMany or #ManyToMany targeting an unmapped class:
com.cmr.daos.child.domain.Child.medications[com.cmr.daos.child.domain.Medications]
Hibernate is trying to find the entity Medications that represents the property medications in your Child class.
Looking at the etities everything looks good, so I assume you missed to place #Entity for Medications class or you missed to mention about this entity in hibernate.cfg.xml file.

Resources