Hibernate join two entities - spring

i really don't know what actually my problem is.
I have two models in my Project.
model-package
Ansprechpartner
Lieferant
Ansprechpartner.java
#Entity
#Table(name = "ANSPRECHPARTNER")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = {"anlageAm", "updatedAt"}, allowGetters = true)
public class Ansprechpartner {
...
#NotNull
#ManyToOne
#JoinColumn(name = "lief_code", foreignKey=#ForeignKey(name = "APART_LIEF_FK"))
private Lieferanten liefCode;
public Lieferanten getLiefCode() {
return liefCode;
}
public void setLiefCode(Lieferanten liefCode) {
this.liefCode = liefCode;
}
...
}
Lieferant.java
#Entity
#Table(name = "LIEFERANTEN")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = {"anlageAm"}, allowGetters = true)
public class Lieferanten {
...
#Id
private String code;
#OneToMany(mappedBy = "liefCode")
private Set<Ansprechpartner> apart;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Set<Ansprechpartner> getApart() {
return apart;
}
public void setApart(Set<Ansprechpartner> apart) {
this.apart = apart;
}
...
}
My Controller:
#RestController
#RequestMapping("/apart")
public class AnsprechpartnerController {
...
#GetMapping("/all/{id}")
public Ansprechpartner getApartWithId(#PathVariable("id") long id) {
Ansprechpartner apart = apartRepository.findOne(id);
return apartRepository.findOne(id);
}
}
When i try to get the json data i get the following problem. Ansprechpartner gets data from Lieferant (because of that join). But then Lieferant again shows data from Ansprechpartner and so on.
Maybe better described with the following picture:
Image with explanation
EDIT:
I finally solved it with the #JsonIgnoreProperties annotation:
In my Ansprechpartner.java i did it this way:
#NotNull
#JsonIgnoreProperties("apart")
// #JsonManagedReference
#ManyToOne
#JoinColumn(
name = "lief_code",
foreignKey=#ForeignKey(name = "APART_LIEF_FK")
)
private Lieferanten liefCode;
And in my Lieferanten.java i did it this way:
// #JsonBackReference
#JsonIgnoreProperties("liefCode")
#OneToMany(mappedBy = "liefCode", fetch = FetchType.LAZY)
private Set<Ansprechpartner> apart;

To avoid infinite recursions you can use #JsonManagedReference & #JsonBackReference
Json Infinite Recursion is one of the most common problems when we serialize Java objects which having Bidirectional-Relationships.
#JsonManagedReference: a part with the annotation will be serialized normally.
#JsonBackReference: a part with the annotation will be omitted from serialization.
like:
#JsonBackReference
private Set<Ansprechpartner> apart;
You can check details in solution-2

Strange behaviour. Possibly you could try:
1) Make sure in the Lieferanten entity, in the equals / hashCode you do not use the Set<Ansprechpartner> apart.
2) You can explicitly detach the entities from the persistence context:
#NotNull
#ManyToOne
#JoinColumn(name = "lief_code"
, foreignKey=#ForeignKey(name = "APART_LIEF_FK")
, cascade={CascadeType.DETACH})
private Lieferanten liefCode;
and then in the controller:
#GetMapping("/all/{id}")
public Ansprechpartner getApartWithId(#PathVariable("id") long id) {
Ansprechpartner apart = apartRepository.findOne(id);
apartRepository.detach(apart);
return apart;
}
you would need to implement a bit -> link, in repository in order to have that available.
3) explicitly add lazy loading: #OneToMany(mappedBy = "liefCode", fetch = FetchType.LAZY).

The root cause is jackson trying to serialize object when object has Bidirectional-Relationships.
You can fixed it by this way
Short way
Better way :
Returning entities directly to view layer is not a good practice.
You should convert entities to DTOs (Data Transfer Object) and pass the DTOs to view

Related

Duplicated entities in Bidirection OneToMany relationship when fetching with Spring Data JPA

I have two entities defined. Both of them are connected through a bidirectional #OneToMany.
Here are my two entities
#Entity(name = "Post")
#Table(name = "post")
public class Post {
#Id
#GeneratedValue
private Long id;
private String title;
#OneToMany(
mappedBy = "post",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<PostComment> comments = new ArrayList<>();
//Constructors, getters and setters removed for brevity
public void addComment(PostComment comment) {
comments.add(comment);
comment.setPost(this);
}
public void removeComment(PostComment comment) {
comments.remove(comment);
comment.setPost(null);
}
}
#Entity(name = "PostComment")
#Table(name = "post_comment")
public class PostComment {
#Id
#GeneratedValue
private Long id;
private String review;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "post_id")
private Post post;
//Constructors, getters and setters removed for brevity
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof PostComment )) return false;
return id != null && id.equals(((PostComment) o).getId());
}
#Override
public int hashCode() {
return Objects.hash(id);
}
}
I am using Spring Data JPA to fetch / save entities.
Saving works fine and for example if I save 1 post and 4 post comments I can see the entries in the database. The database I am using is PostgreSQL.
When I am fetching all the posts through my repository using the findAll method, then I receive the post with the 4 comments.
The issue is when I am fetching only one post through the getOne method, the post is found, but for some reason the entity contains 7 post comments. The first entry is duplicated 3 times and the second one is duplicated two times.
I don't understand why this is happening and how can I fix this.
Any help is appreciated.
Thanks
You need to change List to Set.
#OneToMany(mappedBy = "post",cascade = CascadeType.ALL,orphanRemoval = true)
private Set<PostComment> comments = new HashSet<>();

spring boot ignore field dynamically jpa

I am using Spring Boot REST Web Services and Angular 5 as a frontend, well I have a model class for hibernating like this :
#Entity
public class Title {
private Integer id;
private String name;
private Date releaseDate;
private Time runtime;
private String storyline;
private String picture;
private String rated;
private String type;
private Double rating;
private Integer numberOfVotes;
private Timestamp inserted;
private Set<Genre> genres = new HashSet<>();
private List<TitleCelebrity> titleCelebrities;
private List<TitleMedia> titleMedia;
// Basic getters and setter
#ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
#JoinTable(name = "title_genre", joinColumns = { #JoinColumn(name = "title_id") }, inverseJoinColumns = { #JoinColumn(name = "genre_id") })
public Set<Genre> getGenres() {
return genres;
}
public void setGenres(Set<Genre> genres) {
this.genres = genres;
}
#OneToMany(mappedBy = "title", cascade = CascadeType.ALL)
public List<TitleCelebrity> getTitleCelebrities() {
return titleCelebrities;
}
public void setTitleCelebrities(List<TitleCelebrity> titleCelebrities) {
this.titleCelebrities = titleCelebrities;
}
#OneToMany(mappedBy = "title", cascade = CascadeType.ALL)
public List<TitleMedia> getTitleMedia() {
return titleMedia;
}
public void setTitleMedia(List<TitleMedia> titleMedia) {
this.titleMedia = titleMedia;
}
}
And here's my REST controller
#RestController
#RequestMapping("titles")
#CrossOrigin(origins = {"http://localhost:4200"})
public class TitleController {
private TitleService titleService;
#Autowired
public void setTitleService(TitleService titleService) {
this.titleService = titleService;
}
// Api to get all the movies ordered by release date
#GetMapping("movies")
public List<Title> getAllMoviesOrderByReleaseDateDesc() {
return this.titleService.findByTypeOrderByReleaseDateDesc("movie");
}
#GetMapping("movies/{id}")
public Title findById(#PathVariable Integer id) {
return this.titleService.findById(id);
}
}
What I want is when I make a request to the first method '/movies' i don't want the collection of Telemedia, but if I make a request to the second method '/movies/id' i want the collection of Telemedia.
of course, the annotation #JsonIgnore will ignore the collection whatever the request is.
It may be better to create two models in this case; one to represent the first response and another to represent the second response.
You could also set the collection to null in your second request before sending it back.
You cannot accomplish this with #JsonIgnore alone as you cannot perform conditional logic in annotations.

Lazy attribute is null inside transaction after creation

I have a small example with some get/post mappings and JpaRepository calls in Spring Boot.
Firstly I have two entity Classes:
#Entity
#Table(name = "stock")
public class Stock extends BaseEntity
{
#Column(name = "value")
public String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
#Entity
#Table(name = "stock_item")
public class StockItem extends BaseEntity
{
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "stock_id", insertable = false, updatable = false)
public Stock stock;
#Column(name = "stock_id")
public Long stockId;
#Column(name = "value")
public String value;
}
I have a many-to-one association from StockItem to Stock.
I insert a Stock and have a controller as below:
#Autowired
public Controller(StockItemRepository stockItemRepository) {
this.stockItemRepository = stockItemRepository;
}
#RequestMapping("/")
#Transactional(readOnly = true)
public String get() {
List<StockItem> stockItemList = stockItemRepository.getItemsById(1L);
System.out.println("TX MANAGER: " + TransactionSynchronizationManager.isActualTransactionActive());
for (StockItem stockItem : stockItemList) {
System.out.println(stockItem.getStock().getValue());
}
return "get";
}
#RequestMapping("/fromSave")
#Transactional
public String post() {
StockItem stockItem = new StockItem();
stockItem.setStockId(1L);
stockItemRepository.saveAndFlush(stockItem);
System.out.println("saveCalled");
return get();
}
and getItemsById in the repository is defined as follows:
#Query("FROM StockItem si " +
"JOIN FETCH si.stock stk " +
"WHERE si.stockId = :id")
List<StockItem> getItemsById(#Param("id") Long id);
From my understanding, when I call the post method:
it creates a new item
sets the id of the associated attribute
saves and ends the transaction
Heres where things get strange...
I call get after the post and make the above repository call, which has a join fetch and when I call stockitem.getStock().getValue() I get a null pointer when I expect a LazyInitializationException.
If I call the get() from the mapping, outside the class, it successfully loads the associated object.
I have even removed the #Transaction annotation from the get, as well as
the join-fetch from my query and again, if I call from outside of the class it works and from the post, it crashes with a NullPointerException.
I have put the get inside of a TransactionTemplate.execute() and I still get a NullPointerException when calling from inside the class.
So the main questions are:
Why am I getting a NullPointerException instead of LazyInitializationException?
What is the transaction magic behind having no transaction but successfully fetching a lazy attribute??
The problem here is that you are misusing JPA. As you are seemingly aware judging from the comments on the other answer you have mapped the stock_id column twice. Once as a many-to-one relationship
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "stock_id", insertable = false, updatable = false)
public Stock stock;
and once as a simple column
#Column(name = "stock_id")
public Long stockId;
When you set the simple column and flush the changes as in your post() method the following happens:
the value gets set in the simple column. The reference is still null.
the value gets stored in the database. The reference is still null.
The repository call will find the id of the StockItemin the Persistence Context and return that instance, i.e. the exact same used in the post method, with the reference still null.
What is the transaction magic behind having no transaction but successfully fetching a lazy attribute??
No magic involved here. fetch specifications are only used for object traversal. JPQL queries don't honor these.
The unasked question remains: how to fix the situation?
The obvious fix is to lose the simple column and just use entity references as intended by JPA.
You don't want to do that in order to avoid DB access somewhere. But as long as you only access the id of the referenced Stock it shouldn't get initialized. So it seems that this should be possible with just Lazy Fetching.
Alternatively, I'd suggest removing the many-to-one relationship and creating a repository for Stock and manually loading it when required.
#Entity
#Table(name = "stock_item")
public class StockItem extends BaseEntity
{
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "stock_id", insertable = false, updatable = false) //here is your problem
public Stock stock;
#Column(name = "stock_id")
public Long stockId; // why explicitly define a separate column for foreign key after mapping it above
#Column(name = "value")
public String value;
}
with insertable = false and updatable = false it won't insert in your DB and neither it will allow updation, so you are getting NullPointerException. You should atleast allow insertion in order to run the query based on the foreign key stock_id
UPDATE
Change your Entity class with property-based access:
#Entity
#Table(name = "stock_item")
public class StockItem extends BaseEntity
{
private Stock stock; // variables should always be private since you have getters and setters
private String value;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "stock_id", updatable = false)
public Stock getStock() {
return stock;
}
public void setStock(Stock stock) {
this.stock = stock;
}
#Basic
#Column(name = "value")
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}

Infinite loop with spring-boot in a one to many relation

In a rest application, I use spring boot with jpa.
I have a class Lodger
who have
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "lodger")
private List<Reference> referenceList;
In my class Reference, i have
#ManyToOne
#JoinColumn(name = "lodgerId")
private Lodger lodger;
when i call this method
#RequestMapping(value = "/lodgers/{lodgerId}", method = RequestMethod.GET)
public Lodger getLogderById(#PathVariable("lodgerId") long lodgerId) {
return lodgerService.getLodger(lodgerId);
}
I get this error
org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: Infinite recursion (StackOverflowError) (through reference chain: server.bean.Lodger["referenceList"]->org.hibernate.collection.internal.PersistentBag[0]->server.bean.Reference["lodger"]->server.bean.Lodger["referenceList"]->org.hibernate.collection.internal.PersistentBag[0]->server.bean.Reference["lodger"]->server.bean.Lodger["referenceList"]...
Solution:
Use
#JsonManagedReference annotation for the first objects instantiated
#JsonBackReference annotation for the second objects instantiated
First:
#JsonManagedReference
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "lodger")
private List<Reference> referenceList;
Second:
#JsonBackReference
#ManyToOne
#JoinColumn(name = "lodgerId")
private Lodger lodger;
It happens when you have a cycle in return object and spring tries to serialize it to other type.
Try to create DTO or Value Object (simple POJO) without cycles from returned model and then return it.
If you primary keys in both tables are same name for example : id.
Add this
#Entity
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property = "id")
public class User {
...
}
And to Reference class.
#Entity
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property = "id")
public class Reference {
...
}
The only thing that you need is, in your class in which you have the annotation #ManyToOne, implement the next annotation with the attributes that you want to skip in the value section
#JsonIgnoreProperties(value = {"yourAttribute", "handler", "hibernateLazyInitializer"}, allowSetters = true)
I put an example for your code ->
#ManyToOne(fetch = FetchType.LAZY)
#JsonIgnoreProperties(value = {"referenceList", "handler","hibernateLazyInitializer"}, allowSetters = true)
#JoinColumn(name = "lodgerId")
private Lodger lodger;
All the attributes that you put in the value section on the #JsonIgnoreProperties are ignored, with this you can resolve the infinite loop and use it for other developments with the same format in the future.
Do not return entity with circular dependencies via REST webservice - create new DTO class, map entities fetched from database and return it in webservice.
More info here: http://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application
Of course if you want you may use another mapping library, my personal favourite is Orika (http://orika-mapper.github.io/orika-docs/intro.html)
Lets assume your code looks like below :-
Lodger.class
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "lodger")
private List<Reference> referenceList;
public List<Reference> getReferenceList() {
return referenceList;
}
public void setReferenceList(List<Reference> referenceList) {
this.referenceList = referenceList;
}
#Override
public String toString() {
return "Lodger[referenceList=" + referenceList + "]";
}
Reference.class
#ManyToOne
#JoinColumn(name = "lodgerId")
private Lodger lodger;
public Lodger getLodger() {
return lodger;
}
public void setLodger(Lodger lodger) {
this.lodger = lodger;
}
#Override
public String toString() {
return "Reference[lodger=" + lodger + "]";
}
When you notice at the toString() method written in both the POJO's, you will see that we are calling toString() of both the classes from either side which results in infinite no. of calls to toString() method from both sides which never terminates. To avoid this situation remove any the reference from toString() of Refernce.class[You may remove from Lodger class also.] So toString() of Reference class will not have lodger property in it.
So finally your Reference class will look like :-
Reference.class
#ManyToOne
#JoinColumn(name = "lodgerId")
private Lodger lodger;
public Lodger getLodger() {
return lodger;
}
public void setLodger(Lodger lodger) {
this.lodger = lodger;
}
#Override
public String toString() {
return "Reference[Properties other than lodger=" + properties other than lodger + "]";
}
#JsonIgnoreProperties({"hibernateLazyInitializer","referenceList"}) at class Level
For reference see this article on medium.com.

How Do I Create Many to Many Hibernate Mapping for Additional Property from the Join Table?

I need a many to many hibernate mapping needed 3 joins. I've tried to find out a solution without intermediate entity like LecturerCourse.
I have a many to many relation in my database between my lecturer and course tables. A course can be given by several lecturer while a lecturer can give several courses.
I have courses stored before hand. However, I need to assign courses to lecturer. When I assign courses I also store the capacity of that course.
My database diagram:
I use hibernate and spring. I need a hibernate mapping when a course is assign any lecturer. I need to add values to capacity field.
My lecturer mapping :
#Entity
#Table(name="LECTURER")
public class Lecturer {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="LECTURER_ID_SEQ")
#SequenceGenerator(name="LECTURER_ID_SEQ", sequenceName="LECTURER_ID_SEQ")
private Long Id;
#Column(name="NAME")
private String name;
#Column(name="SURNAME")
private String surname;
#Column(name="EMAIL")
private String email;
#Column(name="USERNAME")
private String username;
#Column(name="PASSWORD")
private String Password;
#ManyToMany
#JoinTable(
name="LECTURER_COURSE",
joinColumns=#JoinColumn(name="LECTURER_ID"),
inverseJoinColumns=#JoinColumn(name="COURSE_ID")
)
private List<Course> courses;
//getters - setters
}
My course mapping :
#Entity
#Table(name="COURSE")
public class Course {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="COURSE_ID_SEQ")
#SequenceGenerator(name="COURSE_ID_SEQ", sequenceName="COURSE_ID_SEQ")
private Long id;
#Column(name="NAME")
private String name;
#Column(name="CODE")
private String code;
}
Any idea how to solve my problem ?
You need to use #EmbeddedId and #Embeddable annotations to solve this issue:
Lecturer Class:
#Entity
#Table(name="LECTURER")
public class Lecturer {
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.lecturer", cascade=CascadeType.ALL)
Set<LecturerCourse> lecturerCourses == new HashSet<LecturerCourse>();
//all others properties Setters and getters are less relevant.
}
Course class:
#Entity
#Table(name="COURSE")
public class Course {
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.course", cascade=CascadeType.ALL)
Set<LecturerCourse> lecturerCourses == new HashSet<LecturerCourse>();
//all others properties Setters and getters are less relevant.
}
LecturerCourse Class:
#Entity
#Table(name = "lecturer_course")
#AssociationOverrides({
#AssociationOverride(name = "pk.lecturer",
joinColumns = #JoinColumn(name = "LECTURER_ID")),
#AssociationOverride(name = "pk.course",
joinColumns = #JoinColumn(name = "COURSE_ID")) })
public class LecturerCourse {
private LecturerCourseID pk = new LecturerCourseID();
#Column(name = "CAPACITY", nullable = false, length = 10)
private String capacity;
#EmbeddedId
public LecturerCourseID getPk() {
return pk;
}
}
Now the Primary Key:
#Embeddable
public class LecturerCourseID implements java.io.Serializable {
private Lecturer lecturer;
private Course course;
#ManyToOne
public Stock getLecturer() {
return lecturer;
}
public void setLecturer(Lecturer lecturer) {
this.lecturer= lecturer;
}
#ManyToOne
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course= course;
}
}
now Your Main should be something like this:
Lecturer lecturer1 = new Lecturer();
Course math = new Course();
LecturerCourse lecturer1math = new LecturerCourse();
lecturer1math.setCapacity("capacity");
lecturer1math.setLecturer(lecturer1);
lecturer1math.setCourse(math);
lecturer1.getLecturerCourses().add(lecturer1math);
//saving object
session.save(lecturer1);
You need to be sure that class marked as #Embeddable should implement Serializable marker interface.
Hope it helps.

Resources