I have a Product entity. One product can be a child of another. The relationship is mapped with OneToMany as follows.
#OneToMany(mappedBy = "parentProd")
private Set<Products> childProd = new HashSet<>();
#ManyToOne
#JsonIgnoreProperties("childProd")
private Products parentProd;
The parent_product_id column generated from this mapping somehow contains invalid parent_ids. Hence I am getting the following error when i try to query all products using JPA criteria query.
javax.persistence.EntityNotFoundException: Unable to find com.test.Products with id 101
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$JpaEntityNotFoundDelegate.handleEntityNotFound(EntityManagerFactoryBuilderImpl.java:162)
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:234)
How to write a criteria query to select all Product entities without considering the parent_child relation?
#Entity
#Table(name = "products")
public class Products implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "productName")
private String productName;
#OneToMany(mappedBy = "parentProd")
private Set<Products> childProd = new HashSet<>();
#ManyToOne
#JsonIgnoreProperties("childProd")
private Products parentProd;
//Getters And Setters
}
Change the oneToMany annotation this way:
#OneToMany(fetch = FetchType.LAZY, mappedBy = "parentProd")
Here fetch = FetchType.Lazy means that data will not be fetched if you don't ask it explicitly.
I have a problem with deleting entity from database. Whatever I do anyway it doesn't delete.
Driver class
#Entity
#Table(name = "drivers")
public class Driver {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#OneToMany(mappedBy = "driver", fetch = FetchType.EAGER)
#JsonSerialize(using = RatingsSerializer.class)
private List<Rating> ratings;
// other fields. Getters and Setters...
}
Rating class
#Entity
#Table(name = "ratings")
#JsonDeserialize(using = RatingDeserializer.class)
public class Rating {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne
#JoinColumn(name = "driver_id")
private Driver driver;
#ManyToOne
#JoinColumn(name = "client_id")
private Client client;
private int mark;
private Date createdAt;
//Getters and Setters ...
}
First one what I do is annotate ratings with #OneToMany(mappedBy = "driver", fetch = FetchType.EAGER, orphanRemoval = true, cascade = CascadeType.REMOVE) and when call driverRepository.delete(driver) it throws:
org.postgresql.util.PSQLException: ERROR: update or delete on table "drivers" violates foreign key constraint "fk3raf3d9ucm571r485t8e7ew83" on table "ratings"
Ok, choose another way. Try to delete each rating object using ratingRepository, but never happens, it just iterate thorough each rating item and throw again error
org.postgresql.util.PSQLException
Next step was to set for each rating item Client and Driver to null. Now driver entity is deleted from database but rating entity remain in database.
What happens?
Spring Data JPA version: 1.5.7
It looks that your Foreign Key error is related to Client table which is linked according to your code line:
#ManyToOne
#JoinColumn(name = "client_id")
private Client client;
So, if you add cascade = CascadeType.REMOVE within the annotation, it may works. But, that' up to you if you want to delete everything on cascade including Client row. If not, then update that column value first to null.
the program under this particular environment:
EJB3.0 + JPA + jersey Web Service
First Entity :
#Entity
#Table(name = "student_by_test_yao")
public class StudentTest implements Serializable {
#Id
#GeneratedValue
private Integer id;
private String name;
#ManyToOne
#JoinColumn(name = "class_id")
private ClassTest classes;
public StudentTest() {}
}
Second Entity:
#Entity
#Table(name = "class_by_test_yao")
public class ClassTest implements Serializable{
#Id
#GeneratedValue
private Integer id;
private String name;
#OneToMany(mappedBy = "classes",cascade = CascadeType.ALL, fetch=FetchType.EAGER)
private List<StudentTest> students;
public ClassTest() {}
}
When I get the ClassTest 's students list.
Exception is:
com.fasterxml.jackson.databind.JsonMappingException:
Infinite recursion (StackOverflowError)
If I change the fetch FetchType.LAZY the Exception is:
org.hibernate.LazyInitializationException:
failed to lazily initialize a collection of role:
cn.gomro.mid.core.biz.goods.test.ClassTest.students,
could not initialize proxy - no Session
How to resolve my problems?
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "userId")
private User user;
it really worked. I just tried that on Bi-Directional #ManyToOne mapping. It fixed
com.fasterxml.jackson.databind.JsonMappingException:
Infinite recursion (StackOverflowError)
Try to add #JsonIgnore annotation to one of fields to avoid looping
For bidirectional relationships you can use these annotations:
#JsonManagedReference for the parent and #JsonBackReference for the child.
Also, this link might help:
Jackson – Bidirectional Relationships
Snippet must help you.
#JsonIgnore
#ManyToOne
#JoinColumn(name = "columnName", referencedColumnName = "id")
private Class class;
I have models like this:
#Table(name="EMPLOYEE")
public class Employee {
#Column(name="firstname")
private String firstname;
// and others
#ManyToOne( targetEntity = Employee.class,
fetch=FetchType.EAGER, cascade=CascadeType.ALL)
#JoinColumn(name="department_id",
insertable=false, updatable=false,
nullable=false)
private Department department;
=============================================================================
#Table(name="DEPARTMENT")
public class Department {
#Column(name="DEPARTMENT_ID")
private Long departmentId;
#OneToMany( targetEntity = Employee.class,
fetch=FetchType.EAGER, cascade=CascadeType.ALL)
#JoinColumn(name="department_id")
#IndexColumn(name="idx")
private List<Employee> employees;
and my DepartmentDaoImpl is
public class DepartmentDaoImpl implements DepartmentDao{
#Autowired
private SessionFactory sessionFactory;
#Transactional
public void addDepartment(Department department) {
sessionFactory.getCurrentSession().save(department);
}
when i run project this exception appear in output
org.hibernate.MappingException: Unknown entity: org.springmvc.form.Department
what is this problem and how solved it?
Department department = new Department();
department.setDepartmentName("Sales");
department.setDepartmentId(90);
Employee emp1 = new Employee("reza", "Mayers", "101",department.getDepartmentId());
// Employee emp2 = new Employee("ali", "Almeida", "2332");
department.setEmployees(new ArrayList<Employee>());
department.getEmployees().add(emp1);
Many problems in this code.
First problem: Unknown entity: org.springmvc.form.Department. This means that Department is not annotated with #Entity and/or is not listed in the entities in the hibernate configuration file.
Second problem:
#ManyToOne( targetEntity = Employee.class)
private Department department;
This doesn't make sense. The target entity is obviously Department, not Employee. targetEntity is useless unless the type of the field is an abstract class or interface, and you need to tell Hibernat what it should use as concrete entity class. Otherwise, Hibernate know the target entity from the type of the field.
Third problem:
#OneToMany( targetEntity = Employee.class,
fetch=FetchType.EAGER, cascade=CascadeType.ALL)
#JoinColumn(name="department_id")
This OneToMany is the inverse side of the bidirectional association that you have already declared and mapped in Employee. So you MUST NOT repeat the mapping here. Instead, you MUST declare it as the inverse side, using the mappedBy attribute:
#OneToMany(mappedBy = "department", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
#IndexColumn(name="idx")
private List<Employee> employees;
Using eager fetching for a toMany association is a really bad idea as well. You really don't want to load the 200 employees of a department every time you load a department. That will kill the performance of your application.
I want to persist my entity with ManyToMany relation. But i have some problem during persisting process.
My entities :
#Entity
#Table(name = "USER")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "ID")
#GeneratedValue(strategy = GenerationType.IDENTITY)
Long userId;
#Column(name = "NAME", unique = true, nullable = false)
String userName;
#Column(name = "FORNAME")
String userForname;
#Column(name = "EMAIL")
String userEmail;
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "USER_USER_ROLES", joinColumns = #JoinColumn(name = "ID_USER"), inverseJoinColumns = #JoinColumn(name = "ID_ROLE"))
List<UserRoles> userRoles = new ArrayList<UserRoles>();
// getter et setter
}
and
#Entity
#Table(name = "USER_ROLES")
public class UserRoles implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "ID")
#GeneratedValue(strategy = GenerationType.IDENTITY)
Long userRolesId;
#Column(unique = true, nullable = false, name = "ROLE_NAME")
String roleName;
// getter et setter
}
Service code :
User user = new User();
UserRoles role;
try {
role = userRolesServices.getUserRoleByName("ROLE_USER"); // find jpql - transaction
} catch (RuntimeException e) {
LOGGER.debug("No Roles found");
role = new UserRoles("ROLE_USER"); // create new
}
user.addUserRole(role);
user.setUserName(urlId);
user.setUserForname(fullName);
user.setUserEmail(email);
userServices.createUser(user); // em.persist(user) - transaction
First time, when I try to persist a User with UserRoles "ROLE_USER", no problem. User and UserRoles and join tables are inserted.
My problem is when I try to persist a second User with the same UserRoles.
I check if the UserRoles exists by finding it (userRolesServices.getUserRoleByName(...)).
If exists -> add this UserRoles to User list (id + role name) else i create a new one (only role name).
By when I try to persist the second User, i obtain the following exception :
"detached entity to persist : .....UserRoles" (maybe because getUserRoleByName is performed in another transaction)
If I do not use getUserRoleByName (only *new UserRoles("ROLE_USER");*), i obtain the following exception :
"...ConstraintViolation : Duplicated entry for 'ROLE_NAME' ..."
So, how to properly persist an entity with #ManyToMany relation ?
For above problem I would say your entity relationship cascade is wrong. Consider this: A user can have multiple roles but there can be fixed number of roles that can exist in the system. So CASCADE ALL from User entity does not make any sense, since life cycle of UserRoles should not depend on User entity life cycle. E.g. when we remove User, UserRoles should not get removed.
detached entity to persist exception will only occur when you are passing object which has primary key already set to persist.
Remove cascade and your problem will be solved now only thing you will need to decide is how you are going to insert User roles. According to me there should be separate functionality to do so.
Also do not use ArrayList, use HashSet. ArrayList allows duplicates.
I will provide my answer if anyone get same type of problem to me and the author.
Basically what I was facing was a situation when I had one table which was some kind of CONSTANT values. And the other would change, but it should map (many to many) to those CONSTANTS.
The exact problem is USERS and it's ROLES.
Roles would be known and added on system startup, thus they should never get removed. Even if no user would have some Role it should still be in the system.
The class implementation, using JPA:
User:
#Entity
#Table(name = "USERS")
public class User{
#Id
private String login;
private String name;
private String password;
#ManyToMany(cascade = {CascadeType.MERGE})
private Set<Role> roles = new HashSet<>();
Role:
#Entity
#Table(name = "ROLE")
public class Role {
#Id
#Enumerated(value = EnumType.STRING)
private RoleEnum name;
#ManyToMany(mappedBy = "roles")
private Set<User> users = new HashSet<>();
Usage
This setup will easily add/remove Role to User. Simply by passing an array, f.e.: user.getRoles().add(new Role("ADMIN")); and merge the user. Removing works with passing an empty list.
If you forget to add the Role before adding it to the user most likely you will get an error like:
javax.persistence.RollbackException: java.lang.IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST: com.storage.entities.Role#246de37e.
What and why
mappedBy attribute is added to the child Entity as described in the JPA Docs
If you choose to map the relationship in both directions, then one
direction must be defined as the owner and the other must use the
mappedBy attribute to define its mapping (...)
cascade = {CascadeType.MERGE} is added for proper cascades JPA Docs
Cascaded the EntityManager.merge() operation. If merge() is called on
the parent, then the child will also be merged. This should normally
be used for dependent relationships. Note that this only affects the
cascading of the merge, the relationship reference itself will always
be merged.
(maybe because getUserRoleByName is performed in another transaction)
That would seem to the the issue, do the query in the same transaction/entity manager. Otherwise re-find it in the current transaction using find().
Duplication Reason: Id is autogenerated, so every time a new role is being created.
Use in this way :
User
#Entity
#Table(name = "user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int user_Id;
#Column(name = "email")
private String email;
#Column(name = "firstname")
private String firstname;
#Column(name = "lastname")
private String lastname;
#Column(name = "password")
private String password;
#Column(name = "active")
private int active;
#ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
#JoinTable(name="user_role",
joinColumns=#JoinColumn(name="user_Id"),
inverseJoinColumns=#JoinColumn(name="role_Id"))
private Set<Role> roles = new HashSet<>();
//Getter and Setter
Role
#Entity
#Table(name="roles")
public class Role {
#Id
#Column(name="role_Id")
private int role_Id;
#Column(name="role_name")
private String role_name;
#ManyToMany(mappedBy = "roles")
private Set<User> users= new HashSet<>();
Controller (Should have added it to Service)
#PutMapping("/addEmp")
public String addEmp(#RequestBody User user) {
String pass=passencoder.encode(user.getPassword());
user.setPassword(pass);
List<Role> roles =rolerepo.findAll();
for(Role role: roles)
System.out.println("Roles"+ role.getRole_name());
//user.setRoles(new HashSet < > (rolerepo.findAll()));
userrepo.save(user);
return "User Created";
}
Output
Roles
User_Role
If you liked the answer please subscribeYoutube Channel Atquil
I have the same issue, but couldn't get through it yet.
My RelationShip is Hotel to DeliveryPartners.
Following are the classes:
#Entity Class
package com.hotelapp.models;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.util.Set;
#Entity
#Getter
#Setter
#NoArgsConstructor
public class Hotel {
#Id
#GeneratedValue(generator = "hotel_id", strategy = GenerationType.AUTO)
#SequenceGenerator(name = "hotel_id", sequenceName = "hotel_id")
private Integer hotelId;
private String hotelName;
#OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "address_id")
private Address address;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "hotel_id")
private Set<Menu> menuList;
#ManyToMany(cascade = {CascadeType.MERGE} ,fetch = FetchType.EAGER)
#JoinTable(name ="hotel_delivery", joinColumns = #JoinColumn(name ="hotel_id"), inverseJoinColumns = #JoinColumn(name="delivery_id"))
private Set<Delivery> delivery;
public Hotel(String hotelName, Address address, Set<Menu> menu, Set<Delivery> delivery) {
this.hotelName = hotelName;
this.address = address;
this.menuList = menu;
this.delivery = delivery;
}
#Override
public String toString() {
return "Hotel{" +
"hotelName='" + hotelName + '\'' +
", address=" + address +
", menu=" + menuList +
", delivery=" + delivery +
'}';
}
}
#Delivery Class
package com.hotelapp.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
#Entity
#Getter
#Setter
#NoArgsConstructor
public class Delivery {
#Id
#GeneratedValue(generator = "del_id", strategy = GenerationType.AUTO)
#SequenceGenerator(name = "del_id", sequenceName = "delivery_id")
private Integer deliveryId;
private String partnersName;
private Double charges;
#ManyToMany(mappedBy = "delivery", cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
#JsonIgnore
private Set<Hotel> hotelList = new HashSet<>();
public Delivery(String partnersName, Double charges) {
this.partnersName = partnersName;
this.charges = charges;
}
#Override
public String toString() {
return "Delivery{" +
"partnersName='" + partnersName + '\'' +
", charges='" + charges + '\'' +
'}';
}
}
#Controller Class
#PostMapping("/hotels")
public ResponseEntity<Hotel> addHotel(#RequestBody Hotel hotel){
Hotel hotel1 =hotelService.addHotel(hotel);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("desc", "oneHotelAdded");
return ResponseEntity.ok().headers(httpHeaders).body(hotel1);
}
When I use merge cascade type, getting following exception:
Hibernate: insert into address (city, state, street_name, zip_code, address_id) values (?, ?, ?, ?, ?)
Hibernate: insert into hotel (address_id, hotel_name, hotel_id) values (?, ?, ?)
Hibernate: insert into menu (hotel_id, menu_name, price, menu_id) values (?, ?, ?, ?)
Hibernate: insert into menu (hotel_id, menu_name, price, menu_id) values (?, ?, ?, ?)
Hibernate: insert into menu (hotel_id, menu_name, price, menu_id) values (?, ?, ?, ?)
Hibernate: insert into hotel_delivery (hotel_id, delivery_id) values (?, ?)
2020-07-12 00:13:37.973 INFO 50692 --- [nio-9098-exec-1] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
2020-07-12 00:13:38.026 ERROR 50692 --- [nio-9098-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientObjectException: object references an unsaved transient instance - **save the transient instance before flushing: com.hotelapp.models.Delivery; nested exception is java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.hotelapp.models.Delivery] with root cause
org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.hotelapp.models.Delivery**
at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:347) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.type.EntityType.getIdentifier(EntityType.java:495) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.type.EntityType.nullSafeSet(EntityType.java:280) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.persister.collection.AbstractCollectionPersister.writeElement(AbstractCollectionPersister.java:930) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1352) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:52) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:478) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at java.util.LinkedHashMap.forEach(LinkedHashMap.java:684) ~[na:1.8.0_221]
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:475) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:348) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:40) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
I realise from the queries part there is no insert query for delivery table so that delivery can be used in hotel_delivery (MTM Table).
Don't know how to proceed now.
I was getting the same error, but after adding the cascade = CascadeType.ALL for both sides of relationship the issue is resolved.
earlier I was cascade = CascadeType.ALL only on the parent side of the relation, after adding child also the code is working fine now.
here is my code.
Reader(parent entity):
#ManyToMany(cascade = CascadeType.PERSIST)
#JoinTable(name="READER_SUBSCRIPTIONS", joinColumns=
{#JoinColumn(referencedColumnName="ID")}
, inverseJoinColumns={#JoinColumn(referencedColumnName="ID")})
private List<Subscription> subscriptions;
Subscription (child entity):
#ManyToMany(mappedBy="subscriptions", cascade = CascadeType.ALL)
private Set<Reader> readers;
Persistence code:
List<Subscription> list = new ArrayList<Subscription>();
list.add(sub1);
list.add(sub2);
Set<Reader> readerSet = new HashSet<Reader>();
readerSet.add(reader1);
readerSet.add(reader2);
reader1.setSubscriptions(list);
reader1.setSubscriptions(list);
sub1.setReaders(readerSet);
sub2.setReaders(readerSet);
reader2.setSubscriptions(list);
reader2.setSubscriptions(list);
readSubscriberRepository.save(reader1);
readSubscriberRepository.save(reader2);