What value to apply on one-to-one relationship with a reference data? - spring-boot

I need to persist an Entity named RevenueParty that has OneToMany relationship with another Entity RevenueAccount that further has OneToOne unidirectional relationship with another "reference" data Entity named RevenueCategory
At moment, I have defined the above relationships as follows:
In RevenueParty Entity
#OneToMany(mappedBy = "revenueParty", cascade = CascadeType.ALL, orphanRemoval = true)
private List<RevenueAccount> revenueAccounts= new ArrayList<>();
And in RevenueAccount, I have defined the following relationship:
#OneToOne
#JoinColumn(name="REVENUE_CATEGORY_ID")
private RevenueCategory revenueCategory;
My dilemma is as follows:
When I create a RevenueParty,the record in the corresponding table get created as expected, but nothing gets persisted in the table denoting the RevenueAccount Entity.
What can I do to make the records appear/persist for RevenueAccount Entity?
Thanks

Related

Join query in Spring Data JPA

I have two tables:
Car_company which has the attributes of:
C_id (primary key),
C_name
Car_model which has the attributes of:
Com_id (referenced to C_id of Car_company),
Model_year
Warranty
I wish to access both of these tables individually and also I would like to perform a join operation on them and display all of the car_models along with their car_company name. I tried using both JPQL and native query but nothing worked. I also made sure to use the OneToMany and ManyToOne associations but I ended up getting infinite nesting,i.e, the models have car_company as field, this inturn has car_models as a list, and this keeps going. Please help me with entity classes and DAOs.
You can get a List of CarModel for each car company in the CarCompany entity through the oneToMany annotation like this:
#OneToMany(mappedBy = "carCompany", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<CarModel> carModels;
or get all car models with their company field in the CarModel entity like this:
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "Com_id", referencedColumnName = "C_id", nullable = false)
private CarCompany carCompany;
Just try to define your relationships as LAZY for performance purpose and to prevent circular nesting when you map your responses to a Data Transfer Object (DTO).

Many to one mapping Hibernate

I am doing many to one mapping in hibernate. I am using the existing tables which I created earlier for one to many mapping (customer and order) but when I am trying to map and update those table I couldn't able to I don't know how should I processed? and I would like to insert the data meaning I would like to create some more orders using command line runner for that customer.
Could you please help me with this
Appreciate your help.
Mapping one-to-many and many-to-one association
Both associations are the same association seen from the perspective of the owing and subordinate entities and respectively.
Student one-to-many Address
Address many-to-one Student
#OneToMany annotation can be applied to a field or property value of "one" end entity class for a collection or an array representing the mapped "many" end of the association.
#ManyToONe relationship between two entities is by managing the FK(Foreign key) of the "one" end entity, as a column in the "many" entity table.
> **Bidirectional one-to-many using ```#JoinColumn```**
#Entity
public class Student{
#OneToMany(cascade = CasecadeType.ALL)
#JoinTable(name="Student_FK")
public set<Address> getAddress(){
return address;
}
}
One-to-Many side as the owing side, You have to remove the mappedBy element and set the #ManyToOne #JoinColumn as insertable and updatable to false. This Solution is not optimized and will produce some additional UPDATE Statement.
#Entity
public class Address{
#ManyToOne(cascade = CasecadeType.ALL)
#JoinColumn(name="STUDENT_FK", insertable = false, updatable = false)
public Student student;
}
For more details look at this link Link

AuditorAware is not working for Many-Many relationship

I use Spring data AuditorAware feature to audit CreatedBy,LastModifiedBy,CreatedDate and LastModifiedDate. It perfectly works for all the entities even when an entity is in one-many relationship. But It doesn't work for many-many relation ship.
For Ex,
I have entities user and user_group with many-many relationship. So it has another table user_group_association with user_id and user_group_id
Whenever there is an create or update in usergroup then audit columns get updated in usergroup table. But within the same transaction if any create/update to user_group_association there is no changes for these columns.
As I define many-many relation ship as below, I wouldn't have an entity class for user_group_association
// bi-directional many-to-many association to Users through
// user_group_association
#ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE })
#JoinTable(name = "user_group_association", joinColumns = #JoinColumn(name = "user_group_id"), inverseJoinColumns = #JoinColumn(name = "user_id"))
private Set<User> users;
How can I force Spring Data to make entires in user_group_association table as well ?

Hibernate: What is the correct way to update collection of an entity?

I am trying to optimize our hibernate application. In many places, while add/updating a collection of an entity, we are clearing it first, and then add all of them again from the input. I feel somehow, there should be a better way but could not found yet.
How do you do in your applications.?
I guess with collection, you mean the "many" side of an #OneToMany relationship.
In this case, you can specify the value orphanRemoval in the #OneToMany annotation to the foreign reference in the owning class:
public class Parent {
// ...
#OneToMany(mappedBy = "whatever", orphanRemoval = true, cascade = CascadeType.ALL)
private List<Child> children;
}
orphanRemoval will instruct Hibernate to delete all existing child entities that have been removed from the collection when the parent entity is persisted.

Retrieve data over a many-to-many relationship in a Spring/Hibernate project

I am new to development using Spring framework and Hibernate. And I need to know what is the best practice to retrieve data from multiple tables. Here is a simple scenario:
Assuming a many-to-many relationship with these tables: Students(sid, name), Courses(cid, title), Students-Courses(sid,cid)
I don't have a Model/Entity class for Students-Courses. Here is how I handled the relationship in the "Student" Model/Entity class:
#JsonIgnore
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(
name = "students-courses",
joinColumns = {#JoinColumn(name = "sid", referencedColumnName = "sid")},
inverseJoinColumns = {#JoinColumn(name = "cid", referencedColumnName = "cid")})
So, this class creates both "Students" and "Students-Courses" tables in the database via Hibernate. I also have a separate Model/Entity class for Course.
How can I get the list of all the students including their courses (titles)? I mean multiple records for the students with more than one course
I can create an attribute in the "Student" class like this:
private Set<Course> courses = new HashSet<>();
But it won't be returned back if I use a JpaRepository interface/class like
return studentRepository.findAll();
since it's not a #Column.
Should I write native-SQL code in my class?
Should I create an Immutable Entity class so Hibernate create sort of a database-view object in the data layer?
What is the best practice and how should I do that?

Resources