Spring/Hibernate/JPA: Prevent reassigning child to another parent - spring

I am working in a SpringBoot application with Hibernate that exposes a REST interface.
The Problem
Users are able to create objects, let's name them parent. Users can associate the parent object with several child items. These items are also composed of other objects, but lets keep it simple for now. I want to prevent the case that a client can do the following:
create parent1 and create child1, child2
create parent2 and create child3
update parent1 with child3 in payload
This behaviour should not be possible as the child items should not be updatable when they belong to another parent.
My goal is to make it impossible to update parent and update any child that belongs to a different parent.
The model
#Entity(name = "Parent")
#Table(name = "t_parent")
data class Parent(
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Int = 0,
#JoinColumn(name = "fk_parent")
#OneToMany(orphanRemoval = true, cascade = [CascadeType.ALL])
val children: MutableList<Child> = mutableListOf()
)
#Table(name = "t_child")
#Entity(name = "Child")
data class Child(
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Int = 0,
)
I am using Spring's JpaRepository for persistence.
Solutions?
The 'dumbest' way of doing this would be to fetch parent1 from the database and remove all child items from the client's request that are not contained in dbParent1. This is quite tedious and not really smart I guess.
Thanks for your advice.

What about transactions? In a transactional method you can check if a child belongs to another parent. If you find any obstacle for update/insert or whatever, then rollback the transaction (for example, just throw an exception). This methodology will require additional service layer in your archtecture since the code of repos is autogenerated from interface declarations.
This approach is described here: How to override save method of CrudRepository REST wise

I would do this in the following way for the update operation:
1) Fetch the parent with childId
2a) If there are no parents, then just add the child to the parent (new child)
2b) Otherwise, check if the child belongs to the parent (you can use parentId probably set in the #PathVariable
2b1) If not, throw a new IllegalArgumentException("wrong parent")
2b2) Otherwise, update parent

Related

Save either a new or detached child object using Spring JPA and Hibernate

I have a class like this:
#Entity
#Table(name = "parent")
class Parent{
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "child")
private Child child;
}
The child class and therefore the child table has no references to Parent. Now the problem is that I have code like:
//Brand new transient parent created
Parent parent = new Parent();
//Either find child in the DB using the attributes or create a brand new one
Child child = createOrFindChild(childAttributes)
//Set child in parent
parent.setChild();
parentRepository.save(parent)
The problem here is that if I don't find the child and try to save I get the error:
"object references an unsaved transient instance - save the transient instance before flushing"
If I set CascadeType.PERSIST then it works when a brand new child but when I find the child in the DB and it is detached then I get the error:
"detached entity passed to persist".
Anyway to make it work without explicitly saving child first?
You can use CascadeType.MERGE and use EntityManager#merge in your repository.

Transaction getting rolled back on persisting the entity from Many to one side

I have this association in the DB -
I want the data to be persisted in the tables like this -
The corresponding JPA entities have been modeled this way (omitted getters/setters for simplicity) -
STUDENT Entity -
#Entity
#Table(name = "student")
public class Student {
#Id
#SequenceGenerator(name = "student_pk_generator", sequenceName =
"student_pk_sequence", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator =
"student_pk_generator")
#Column(name = "student_id", nullable = false)
private Long studentId;
#Column(name = "name", nullable = false)
private String studentName;
#OneToMany(mappedBy = "student", cascade = CascadeType.ALL)
private Set<StudentSubscription> studentSubscription;
}
STUDENT_SUBSCRIPTION Entity -
#Entity
#Table(name = "student_subscription")
#Inheritance(strategy = InheritanceType.JOINED)
public abstract class StudentSubscription {
#Id
private Long studentId;
#ManyToOne(optional = false)
#JoinColumn(name = "student_id", referencedColumnName = "student_id")
#MapsId
private Student student;
#Column(name = "valid_from")
private Date validFrom;
#Column(name = "valid_to")
private Date validTo;
}
LIBRARY_SUBSCRIPTION Entity -
#Entity
#Table(name = "library_subscription",
uniqueConstraints = {#UniqueConstraint(columnNames = {"library_code"})})
#PrimaryKeyJoinColumn(name = "student_id")
public class LibrarySubscription extends StudentSubscription {
#Column(name = "library_code", nullable = false)
private String libraryCode;
#PrePersist
private void generateLibraryCode() {
this.libraryCode = // some logic to generate unique libraryCode
}
}
COURSE_SUBSCRIPTION Entity -
#Entity
#Table(name = "course_subscription",
uniqueConstraints = {#UniqueConstraint(columnNames = {"course_code"})})
#PrimaryKeyJoinColumn(name = "student_id")
public class CourseSubscription extends StudentSubscription {
#Column(name = "course_code", nullable = false)
private String courseCode;
#PrePersist
private void generateCourseCode() {
this.courseCode = // some logic to generate unique courseCode
}
}
Now, there is a Student entity already persisted with the id let's say - 100.
Now I want to persist this student's library subscription. For this I have created a simple test using Spring DATA JPA repositories -
#Test
public void testLibrarySubscriptionPersist() {
Student student = studentRepository.findById(100L).get();
StudentSubscription librarySubscription = new LibrarySubscription();
librarySubscription.setValidFrom(//some date);
librarySubscription.setValidTo(//some date);
librarySubscription.setStudent(student);
studentSubscriptionRepository.save(librarySubscription);
}
On running this test I am getting the exception -
org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: com.springboot.data.jpa.entity.Student; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.springboot.data.jpa.entity.Student
To fix this I attach a #Transactional to the test. This fixed the above exception for detached entity, but the entity StudentSubscription and LibrarySubscription are not getting persisted to the DB. In fact the transaction is getting rolled back.
Getting this exception in the logs -
INFO 3515 --- [ main] o.s.t.c.transaction.TransactionContext : Rolled back transaction for test: [DefaultTestContext#35390ee3 testClass = SpringDataJpaApplicationTests, testInstance = com.springboot.data.jpa.SpringDataJpaApplicationTests#48a12036, testMethod = testLibrarySubscriptionPersist#SpringDataJpaApplicationTests, testException = [null], mergedContextConfiguration = [MergedContextConfiguration#5e01a982 testClass = SpringDataJpaApplicationTests, locations = '{}', classes = '{class com.springboot.data.jpa.SpringDataJpaApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#18ece7f4, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer#264f218, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer#2462cb01, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer#928763c, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#7c3fdb62, org.springframework.boot.test.context.SpringBootTestArgs#1, org.springframework.boot.test.context.SpringBootTestWebEnvironment#1ad282e0], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]
Now I have couple of questions -
Why am I getting detached entity exception. When we fetch an entity from the DB, Spring Data JPA must be using entityManager to fetch the entity. The fetched entity gets automatically attached to the persistence context right ?
On attaching #Transactional on the test, why the transaction is getting rolledback, and no entity is getting persisted. I was expecting the two entities - StudentSubscription and LibrarySubscription should've been persisted using the joined table inheritance approach.
I tried many things but no luck. Seeking help from, JPA and Spring DATA experts :-)
Thanks in advance.
Let me add a few details that outline a couple of design problems with your code that significantly complicate the picture. In general, when working with Spring Data, you cannot simply look at your tables, create cookie-cutter entities and repositories for those and expect things to simply work. You need to at least spend a bit of time to understand the Domain-Driven Design building blocks entity, aggregate and repository.
Repositories manage aggregates
In your case, Student treats StudentSubscriptions like an entity (full object reference, cascading persistence operations) but at the same time a repository to persist the …Subscriptions exists. This fundamentally breaks the responsibility of keeping consistency of the Student aggregate, as you can simply remove a …Subscription from the store via the repository without the aggregate having a chance to intervene. Assuming the …Subscriptions are aggregates themselves, and you'd like to keep the dependency in that direction, those must only be referred to via identifiers, not via full object representations.
The arrangement also adds cognitive load, as there are now two ways to add a subscription:
Create a …Subscription instance, assign the Student, persist the subscription via the repository.
Load a Student, create a …Subscription, add that to the student, persist the Student via it's repository.
While that's already a smell, the bidirectional relationship between the …Subscription and Student imposes the need to manually manage those in code. Also, the relationships establish a dependency cycle between the concepts, which makes the entire arrangement hard to change. You already see that you have accumulated a lot of (mapping) complexity for a rather simple example.
What would better alternatives look like?
Option 1 (less likely): Students and …Subscriptions are "one"
If you'd like to keep the concepts close together and there's no need to query the subscriptions on their own, you could just avoid those being aggregates and remove the repository for them. That would allow you to remove the back-reference from …Subscription to Student and leave you with only one way of adding subscriptions: load the Student, add a …Subscription instance, save the Student, done. This also gives the Student aggregate its core responsibility back: enforcing invariants on its state (the set of …Subscription having to follow some rules, e.g. at least one selected etc.)
Option 2 (more likely): Students and …Subscriptions are separate aggregates (potentially from separate logical modules)
In this case, I'd remove the …Subscriptions from the Student entirely. If you need to find a Students …Subscriptions, you can add a query to the …SubscriptionRepository (e.g. List<…Subscription> findByStudentId(…)). As a side effect of this you remove the cycle and Student does not (have to) know anything about …Subscriptions anymore, which simplifies the mapping. No wrestling with eager/lazy loading etc. In case any cross-aggregate rules apply, those would be applied in an application service fronting the SubscriptionRepository.
Heuristics summarized
Clear distinction between what's an aggregate and what not (the former get a corresponding repository, the later don't)
Only refer to aggregates via their identifiers.
Avoid bidirectional relationships. Usually, one side of the relationship can be replaced with a query method on a repository.
Try to model dependencies from higher-level concepts to lower level ones (Students with Subscriptionss probably make sense, a …Subscription without a Student most likely doesn't. Thus, the latter is the better relationship to model and solely work with.)
The transaction is getting rolled back because the test is doing DB updates in the test method.
#Transactional does auto rollback if the transaction includes any update DB. Also here is the compulsion to use transaction because EntityManager gets closed as soon as the Student entity gets retrieved, so to keep that open the test has to be within the transactional context.
Probably if I had used a testDB for my testcases then probably spring wouldn't haveve been rolling back this update.
Will setup an H2 testDb and perform the same operation there and will post the outcome.
Thanks for the quick help guys. :-)
Why am I getting detached entity exception. When we fetch an entity from the DB, Spring Data JPA must be using entityManager to fetch the entity. The fetched entity gets automatically attached to the persistent context right ?
Right, but only for as long as the entityManager stays open. Without the transactional, as soon as you return from studentRepository.findById(100L).get();, the entityManager gets closed and the object becomes detached.
When you call the save, a new entityManager gets created that doesn't contain a reference to the previous object. And so you have the error.
The #Trannsaction makes the entity manager stay open for the duration of the method.
At least, that's what I think it's happening.
On attaching #Transactional on the test, why the transaction is getting rolledback,
With bi-directional associations, you need to make sure that the association is updated on both sides. The code should look like:
#Test
#Transactional
public void testLibrarySubscriptionPersist() {
Student student = studentRepository.findById(100L).get();
StudentSubscription librarySubscription = new LibrarySubscription();
librarySubscription.setValidFrom(//some date);
librarySubscription.setValidTo(//some date);
// Update both sides:
librarySubscription.setStudent(student);
student.getStudentSubscription().add(librarySubscription);
// Because of the cascade, saving student should also save librarySubscription.
// Maybe it's not necessary because student is managed
// and the db will be updated anyway at the end
// of the transaction.
studentSubscriptionRepository.save(student);
}
In this case, you could also use EntityManager#getReference:
#Test
#Transactional
public void testLibrarySubscriptionPersist() {
EntityManager em = ...
StudentSubscription librarySubscription = new LibrarySubscription();
librarySubscription.setValidFrom(//some date);
librarySubscription.setValidTo(//some date);
// Doesn't actually load the student
Student student = em.getReference(Student.class, 100L);
librarySubscription.setStudent(student);
studentSubscriptionRepository.save(librarySubscription);
}
I think any of these solutions should fix the issue. Hard to say without the whole stacktrace.

JPA - How to efficiently get all children of a parent by JPA?

Having a parent and child class as below
#Entity
class Parent {
#Id
Long id;
#OneToMany(orphanRemoval = true, cascade = CascadeType.ALL)
List<Child> children;
}
#Embeddable
class Child{
#Id
Long id;
// child does not have parent id
}
I am using ObjectDB and JPA. My db got bigger and some parents has 500K children.
Normally, to get all children of a parent, I was loading parent and accessing children as parent.getChildren() via lazy loading.
However, since the list too big, it requires a lot of memory.
How can I get all children of a specific parent as a lightweight DTO object list in a performant way?
Bonus question: how can I delete all children of a parent efficiently?
Setting Child as embeddable is a possible solution. Note that in that case no need for an id field, which is unused and just consumes space. You can delete the embeddable children by clearing the collection.
To improve performance you may need a different design in which not all the 500K are loaded each time together.

Spring data JPA self join on an entity. How do I specify the depth of recursion?

Using Spring Boot JPA, I am doing a self join on a table of "Person" with attributes id, name and parent_id. parent_id is a foreign key referencing Person.id. So, a Person will have zero or one parent. A sample of my domain class is below.
#Entity(name="person")
public class Person {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
#Column(name="id")
private Integer id;
#Column(name="name")
private String name;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="parent_person_id")
private Person parent;
// constructors, getters, setters, etc
}
This actually works just fine; when I query with CrudRepository.findById() for example, I get a Person object with an embedded Person object (parent), which may have another embedded Person object (grandparent), etc until I get to a Person without a parent.
My question is, how may I retrieve only a Person and their immediate parent without recursing any further (no grandparents, great-grandparents, etc)?
I imagine I could simply avoid the join, and make parent_id a plain #Column, then in the service layer do an additional query to find the parent, but I'm wondering if there is some Jpa magic that could make it easier than that.
Actually, this was not as hard as it seemed. Converting my Person entity to a dto provided me with the opportunity to simply STOP at the parent, and not recurse through the whole tree!

Collection not updating upon saving opposite entity using Spring Data Jpa

I have two entities that are in a one-to-many relationship:
Parent entity:
#OneToMany(mappedBy = "parent")
public List<Child> getChildren()
Child entity:
#ManyToOne
#JoinColumn(name = "PARENT_ID")
public Parent getParent()
Consider the following code (inside transaction):
Child child = childRepository.findById(id).get();
Parent parent = child.getParent();
child.setParent(null);
childRepository.saveAndFlush(child);
List<Child> children = parent.getChildren();
In this case the 'children' list will still contain the child entity although it is already removed. I tried flushing the repositories, saving the parent entity or even getting a new one from the parentRepository, none of these worked.
Why is the children list not updated upon save and how can I make sure the collection is up-to-date without explicitly removing the entity (I want to make further operations on the entities in the collection)?

Resources