Many to one mapping Hibernate - spring-boot

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

Related

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

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

Integrity Constraints violation error when deleting record in Spring boot

I am new into Spring Boot framework, I want to implement an Entity Relationships so to achieve the following cases:
Consider the following example Entities Relationships
#Entity
class Category {
private Long id;
private String name
#OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL)
private List<Product> products = new ArrayList<>();
}
#Entity
class Product {
private Long id;
private String name
#ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.DETACH)
private Category category;
}
I use the below approach to delete objects with Jpa Repository API
Product product = productRepository.getOne(productId);
productRepository.delete(product);
Category category = categoryRepository.getOne(categoryId);
categoryRepository.delete(category);
Based on the above relationships I want to be able to:
When deleting Category record, delete all related Products.
When deleting Product record, detach from the Category's products
I am aware of the cascade types but when deleting Category record I get constraints violation i.e. category x is still referenced into another table i.e. Products.

Must I create a mapping relationship between two entities in hibernate?

For example, if you have an order table in Hibernate and a product table that receives an order, it is mapped as a one to many relationship.Then,Must I write the mapping relationship in code here? In my project, I permanently store order information in a database I have, but in that case, does it need to be a mapping relationship?There's nothing else to do except delete cascade i think.
If you want to use the association in your business code, you also need to model in your domain model. In the described example, I would expect a many-to-many association between the Order and the Product entity. You could model it as a uni- (= only on 1 entity) or bidirectional (= on both entities) association.
Here is a quick example. I provide a very detailed description of all kinds of associations in my guide to association mappings.
public class Order {
#ManyToMany
private Set<Product> products;
...
}
public class Product {
#ManyToMany(mappedBy = "products")
private Set<Order> orders;
...
}

Spring Boot JPA Bidirectional Mapping without Foreign Key

Is it possible to Greate DDL using JPA with bidirectional mapping and without foreign key? If can, is it best practice?
#Entity
class Book{
int id;
String title;
#OneToMany(mappedBy="book")
Set<BookDetail> book_detail;
}
#Entity
class BookDetail{
int id;
String name;
String description;
#ManyToOne
Book book;
}
Yes. It is possible using a join table. It will have foreign keys of course.
#Entity
class Book{
#OneToMany
List<BookDetail> bookDetail;
}
#Entity
class BookDetail{
#ManyToOne(fetch = FetchType.LAZY)
Book book;
}
what is #JoinColumn and how it is used in Hibernate
You can't do it without at least one foreign key, since a DB needs to establish some connection between two entities - BookDetail and Book. It is possible to create two tables for these entities without a real foreign key by using plain integer attribute in BookDetail which will be storing a value of Book's id. But don't do that!
With a foreign key your DBMS generates constraints so it's known about the relationship and it prevents some unsafe deletions and insertions, so each BookDetail's row references existing Books one.
Without real foreign key you c accidentally remove a Book and you BookItem's

Save data to database via Spring Data repository

I am planning to store data from multiple tables which has one to many JPA relationship. I am creating my Repository interface which extends from JPARepository. My question is If I want to save a data on Many sides of relationship (in the below scenario it's Tour) then shall I do with TourRepository or PersonRespository?
On a similar note Is it ideal to create individual repository classes for every JPA entities where data need to be stored? or any better way with limited repository classes the data store to database can be achieved?
#Entity
#Table(name="Person")
public class Person implements Serializable{
...
...
#OneToMany(mappedBy = "person")
private List<Tour> tours;
...
#Entity
#Table(name = "Tour")
public class Tour implements Serializable{
...
...
#ManyToOne
#JoinColumn(name = "PERSON_ID")
private Person person;
...
You have two independent entities. Person can exist without Tour and Tour can exist without Person. So you should have two repositories - for Person and Tour to store their data independently:
Tour tour1 = new Tour("tour1");
tourRepo.save(tour1);
Person person1 = new Person("person1");
person1.addTour(tour1);
personRepo.save(person1);
You chose the bidirectional one-to-many association so you have to use a 'helper' method like addTour to link both entities:
public Person addTour(Tour tour) {
tour.setPerson(this);
this.tours.add(tour);
return this;
}
Additional info: Best Practices for Many-To-One and One-To-Many Association Mappings
Add cascade to tours:
#OneToMany(mappedBy = "person", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private List<Tour> tours;
When you save person object, his tours will be saved automatically.
By the way, in Person class, you should have an addTour(...) utilities method like this:
// Person.java
public void addTour(Tour tour){
this.tours.add(tour);
tour.setPerson(this);
}
I would suggest you to use CascadeType.ALL on #OneToMany mapping in Person entity:
#OneToMany(mappedBy = "person",cascade = {CascadeType.ALL})
private List<Tour> tours;
And then create repository for person to save person object with the list of tours .
CascadeType.ALL means persistence will propagate all EntityManager operations like PERSIST, REMOVE, REFRESH, MERGE, DETACH to the relating entities.

Resources