Spring Data JPA Repository with Hibernate - persist (sql insert) parent entity but only update nested child entities - spring

I'm developing a Spring Boot app with Spring data, JPA, Hibernate combination. Below is the scenario I'm struggling with where the expected behavior is to update only some child entities while the parent entity is being inserted as new.
Entity classes
#Entity
public class A {
#Id
private long id;
#ManyToOne
#JoinColumn (name = "B_ID")
#Cascade ( { CascadeType.ALL } )
private B b;
}
#Entity
#DynamicUpdate
public class B {
#Id
private long id;
#OneToMany (mappedBy = "b")
#Cascade ( { CascadeType.ALL } )
private Set<A> as;
#ManyToOne
#JoinColumn (name = "C_ID")
#Cascade ( { CascadeType.ALL } )
private C c;
}
#Entity
#DynamicUpdate
public class C {
#Id
private long id;
#OneToMany (mappedBy = "c")
#Cascade ( { CascadeType.ALL } )
private Set<B> bs;
#ManyToOne
#JoinColumn (name = "D_ID")
#Cascade ( { CascadeType.ALL } )
private D d;
#ManyToOne
#JoinColumn (name = "E_ID")
#Cascade ( { CascadeType.ALL } )
private E e;
}
#Entity
#DynamicUpdate
public class D {
#Id
private long id;
#OneToMany (mappedBy = "d")
#Cascade ( { CascadeType.ALL } )
private Set<C> cs;
}
#Entity
#DynamicUpdate
public class E {
#Id
private long id;
#OneToMany (mappedBy = "e")
#Cascade ( { CascadeType.ALL } )
private Set<C> cs;
}
Below are the steps I'm performing in the app:
Pull B from repo; if it exists, update some of its field values [Or] create new B with field values.
Create new instance of A and set B into A.
Persist A (by invoking JpaCrudRepository.save(A)).
Success part:
Everything works fine when B doesn't exist in repo already. Which means:
New instances of B (and C,D,E) are created,
This newly created B is set into A,
And A is persisted to repo successfully (a new row is inserted in all corresponding tables in DB/repo).
Failure part:
Now, when B already exists in repo, the existing B is pulled properly,
Some fields of B are updated while C, D, E are left untouched,
And this updated B is set into A.
But when trying to persist A now a Unique constraint violation is thrown on D and E.
All the entities are marked with following:
• ID as auto-generated column (used as PK implicitly),
• Mapping between entities using the ID column,
• CascadeType ALL wherever mappings like OneToMany, ManyToOne are applied,
• Dynamic update annotation.
So far what I could gather from around the web on this subject:
The JPA Repository doesn't have merge() or update() operations available explicitly, and the save() is supposed to cover those. And this save() operation works by calling merge() if the entity instance exists already Or by calling persist() if it is new. And digging further, the entity's ID column is being used to determine its existence in the repo. If this ID is null, entity is determined as new, and as existing if ID is not null.
So in my failure case above, as the existing B entity instance is being pulled from the repo, it already has a non-null ID.
So I'm not currently clear on what exactly I'm missing here.
I tried finding any matching solution online but couldn't arrive at one yet.
Can someone please help me identify what is wrong with my approach?

Found the issue and solution. As A and B were being created as new, subsequently C,D,E were all created as new which caused the violation. So to solve this I had to pull each existing entity of C,D,and E from the DB, and set them respectively/hierarchically inside the newly created B entity, before attempting to persist.
Basically, don't create new instance for an entity if it is nested within a parent entity which is about to be persisted.. and the goal is to update when a similar record already exists.

Related

How to do lazy loading of the non-owning entity in a unidirectional one-to-one mapping?

#Entity
#Table(name = "...")
public class A
{
private Integer id;
...
...
private B b;
#OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "b_id")
getB() {
return b;
}
setB(B b) {
this.b = b;
}
...other methods...
}
#Entity
#Table(name = "...")
public class B
{
private Integer id;
...
...
...methods...
}
When using
Query query = sessionFactory.getCurrentSession().createQuery()
with
query.uniqueResult()
or
query.list()
to fetch an instance of object A from the db,
I am getting the following error message:
org.hibernate.LazyInitializationException: could not initialize proxy [com.project.core.entity.B#261493] - no Session
The above query method is deprecated, however, I am working on an old project that uses Spring (not Spring Boot), and this is the only way I can go about it.
Now, I know that this may be because the hibernate session is already closed, however, I am using join fetch in my hibernate queries above.
I cannot use a shared primary key for the entities because in the future more entities like C, D, etc. will be added which will also have a unidirectional one-to-one mapping with B.
How do I go about fixing this problem? Thank you.

Spring Boot - relationship deleted on save() method

My problem is this: There is a many to many relationship between two tables - Project and Employee. There is an option to update a given employee, but there is a little problem. After updating the employee, hibernate automatically deletes the employee's record from the connected project_employee table.
Hibernate: update employee set email=?, first_name=?, last_name=? where employee_id=?
And this happens right after that
Hibernate: delete from project_employee where employee_id=?
I'm following a course and I've just noticed this error. Source code of the lecturer is here:
https://github.com/imtiazahmad007/spring-framework-course
I've checked your github page:
#ManyToMany(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.PERSIST},
fetch = FetchType.LAZY)
#JoinTable(name="project_employee",
joinColumns=#JoinColumn(name="employee_id"),
inverseJoinColumns= #JoinColumn(name="project_id")
)
#JsonIgnore
private List<Project> projects;
CascadeType.MERGE + CascadeType.PERSIST mean, that if Employee entity is saved, Project entity references must be saved.
In may-to-many cases it means:
DELETE by foreign key
Bulk insert
In case there's no bulk insert, there's an issue with persisntence context (your are saving an entity with empty collection of projects).
Possible solutions:
Remove CascadeType.MERGE + CascadeType.PERSIST if you do not want to change projects every time your save Employee. You can still save the ccollection via Repository
Make sure collection is attached on save action. That will cause Delete+Insert, but the resut will be ok.
Change Many-To-Many to One-To-Many with EmbeddedId
Please, refer to documentation:
When an entity is removed from the #ManyToMany collection, Hibernate simply deletes the joining record in the link table. Unfortunately, this operation requires removing all entries associated with a given parent and recreating the ones that are listed in the current running persistent context.
https://docs.jboss.org/hibernate/orm/5.6/userguide/html_single/Hibernate_User_Guide.html#associations-many-to-many
*** Update from dialog below to make cascade clear.
Say, you have two entities A & B (getters and setters omitted). + repos
#Entity
#Table(name = "a")
public class A {
#Id
private Integer id;
private String name;
#ManyToMany(cascade = {CascadeType.ALL})
#JoinTable(name="a_b",
joinColumns=#JoinColumn(name="a_id"),
inverseJoinColumns= #JoinColumn(name="b_id")
)
private List<B> bs;
}
#Entity
#Table(name = "b")
public class B {
#Id
private Integer id;
private String name;
}
You sample test looks like this:
#Test
public void testSave() {
B b = new B();
b.setId(1);
b.setName("b");
b = bRepository.save(b);
A a = new A();
a.setId(1);
a.setName("a");
a.setBs(Collections.singletonList(b));
aRepository.save(a);
a.setName("new");
service.save(a); //watch sevice implementations below
}
Version1:
#Transactional
public void save(A a) {
aRepository.save(a);
}
Hibernate logs are the following:
Hibernate:
update
a
set
name=?
where
id=?
Hibernate:
delete
from
a_b
where
a_id=?
Hibernate:
insert
into
a_b
(a_id, b_id)
values
(?, ?)
delete+bulk insert present (despite the fact, that B-s where not in fact changed)
Version2:
#Transactional
public void save(A a) {
Optional<A> existing = aRepository.findById(a.getId());
if (existing.isPresent()) {
a.setBs(existing.get().getBs());
}
aRepository.save(a);
}
Logs:
update
a
set
name=?
where
id=?
Here b-collection was forcibly re-attached, so hibernate understands, that it's not needed to be cascaded.

Spring data jpa insert child into parent using rest call

Let's assume we have two entities A and B which have such a relation:
public class A {
#Id
private Integer id;
#OneToMany(mappedBy = "parent")
private Set<B> childs = new HashSet<>();
// getters and setters
}
public class B {
#Id
private Integer id;
#ManyToOne
private A parent;
// getters and setters
}
I'm having 2 repositories, one for each entity (ARepository and BRepository) and i'm using spring data rest starter so i've got generated rest api.
Let assume we have an instance of A, which has as id=12
In order to insert a B entity and link it to A i have to: POST the url http://localhost:8080/appContext/b/ and giving it a request body as follow: {"parent": "a/12"}
It works fine, but it is possible to have the same thing by posting http://localhost:8080/appContext/a/12/childs/ with the same request param except the "parent" JSON attribute ? as it's actually possible to fetch the childs of a parent using this last url.

one-way one-to-many throws Hibernate Cannot add or update a child row: a foreign key constraint fails

I have an application that teaches the user how to play various card games. The data model that gets persisted consists of a TrainingSession with a uni-directional one-to-many relationship with the Hands.
[EDIT] To clarify, a Hand has no existence outside the context of a TrainingSession (i.e they are created/destroyed when the TrainingSession is). Following the principals of Data Driven Design, the TrainingSession is treated as an aggregate root and therefore a single spring-data CrudRepository is used (i.e., no repository is created for Hand)
When I try to save a TrainingSession using a CrudRepository, I get: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (blackjack.hand, CONSTRAINT FKrpuxac6b80xc7rc98vt1euc3n FOREIGN KEY (id) REFERENCES training_session (tsid))
My problem is the 'save(trainingSession)' operation via the CrudRepository instance. What I don't understand is why the error message states that FOREIGN KEY (id) REFERENCES training_session (tsid)). That seems to be the cause of the problem but I cant figure out why this is the case or how to fix it. The relationship is uni-directional and nothing in the Hand class refers to the TrainingSession.
The code, minus all the getters and setters, is:
#Entity
public class TrainingSession {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer tsid;
private String strategy;
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="id")
private List<Hand> hands;
private int userId;
protected TrainingSession() {
}
public TrainingSession(int userId, Strategy strategy, List<Hand> hands) {
this.strategy = strategy.getClass().getSimpleName();
this.hands = hands;
this.userId = userId;
}
while Hand is
#Entity // This tells Hibernate to make a table out of this class
public class Hand {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private int p1;
private String p1s;
private int p2;
private String p2s;
private int d1;
private String d1s;
private int trials;
private int score;
public Hand() {
}
You need to save your TrainingSession and Hand objects first before saving the adding the hand objects to TrainingSession.
TrainingSession ts1 = new TrainingSession();
trainingSessionManager.save(ts1);
Hand hand1 = new Hand();
handManager.save(hand1);
Hand hand2 = new Hand();
handManager.save(hand2);
ts1.gethands().add(hand1);
ts1.gethands().add(hand2)
trainingSessionManager.save(ts1);
If you check your database you will find 3 tables TrainingSession, Hand and TrainingSession_Hand, The TrainingSession_Hand table references to both TrainingSession and Hand both. Therefore you need to save TrainingSession and hand before saving the relationship.
Found the problem. I was assuming that when spring-data set up the DB tables, it was able to figure out and set up the uni-directional 1-to-many relationship. Apparently that isn't the case. When I configure the relationship as bi-directional everything seems to work.
To fix things I:
removed from TrainingSession the #joincolumn annotation for hands
in Hands I added a TrainingSession field with a #ManyToOne annotation:
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "tsid", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
private TrainingSession tsession;
I also added in the Hand class the getter/setter for tsession
I can now do a save of the entire aggregate construct using only a TrainingSessionRepository.

Spring JPA OneToOne out of a OneToMany with only the fist entry

my problem can be broken down to this little example:
I have a entity class A and a entity class B. A has a List of B objects. Now there is always only one B relevant. So I do not want to load all B's of an A, only to access this one B (last inserted B inside a A).
The question: Can I manipulate an entity without an service, so that there is a #Transient variable, that is always the newest B? And also without saving the newest B separately in A. Is there a way to achieve this?
class B{
#Id
#GeneratedValue
private Long id;
#Column(nullable=false)
private String name;
#Column(nullable=false)
private Date created = new Date();
}
class A{
#Id
#GeneratedValue
private Long id;
#OneToMany
#OrderBy("created ASC")
private List<B> b;
#Transient
private B newestB; // Here should be only the newest B
}
Yes. Forget storing the newest B as a variable and instead simply add a getter for it:
#Transient
public B getNewestB() {
return b.get(b.size() -1);
}
This will solve your problem under the assumption that b is set to FetchType.EAGER. Fetching using b's getter and FetchType.LAZY may not be so straight forward as Spring may rely on an AOP proxy call to trigger the lazy load (you'd need to experiment).
However, I'd discourage both these approaches. You're effectively trying to fit business logic into your Entity. Why not keep your entity clean and perform this query using B's repository?
E.g.
public interface BRepository extends CrudRepository<B, Long> {
#Query(...) //query to get newest B for specified A
B getNewest(A a)
}

Resources