Why an #ManyToMany should caused a NullPointerException? - java-8

I know that it could be too much vague but what could cause a NullPointerException after adding a #ManyToMany in my jpa entities?
All code is the same, I deleted only the entity linked to the croos table and modified the two entities that before were linked to that entity adding #ManyToMany so the problem isn't the external code or in the db.
The two entities are also linked with a #OneToMany with a second field. Could be this the problem?
This is a structure of my database:
table1: id, name, description and table2_id;
table2: id, name and description;
cross_table: id, table1_id, table2_id and timestamp
Could be a problem the two Set into the entity Table2?
My specs are:
java8
hibernate5.2
jpa2.1

As usual, for me, the message caused a misterunderstanding, I thought the problem was #ManyToMany instead the problem was a my error in hibernate.cfg because I removed only the entity table1_table2 and not the mapping annotation on hibernate.cfg!
Thank you #holi-java for your hint!

Related

Why is Hibernate #OnetoMany relationship required?

I have two entities Library and Books which are associated by Hibernate #OneToMany in a spring boot project. Fetching books in a particular library through the getter functions renders a LazyInitialisationException. The solution that I could find was making a query in the Books entity and fetching all the books corresponding to the library-id of the library. So, I was thinking why is oneToMany relationship required if we can just store a key corresponding to library in the Books table.
Simply storing a key doesn't provide any consistency assurances. Also, using defined OneToMany or ManyToOne you can also define the cascade types (you would only need to save the parent entity and then all the children would automatically be saved, in a single transaction).
The quick way to fix your problem would be to use FetchType EAGER, but I would recommend fixing whatever you have misconfigured.

Spring Boot + Hibernate - lazy initialization error on two levels of child hibernate objects

I feel like this issue has been discussed before, but I can't find a solid answer. I'm getting a LazyInitializationException...no Session when attempting to go two levels deep in accessing lazily-loaded hibernate objects. I'm doing this through Spring Boot.
Suppose I have three Hibernate objects, Table1, Table2 & Table3. Table1 has a one-to-many foreign-key reference to Table2 & Table2 has a one-to-many foreign-key reference to Table3. Each foreign-key reference is LAZY loaded (I think this issue occurs with one-to-one relationships as well, but not 100% sure)
Table1 has the following code:
#OneToMany(mappedBy = "table1", fetch = FetchType.LAZY)
private Set<Table2> table2s;
//and corresponding getter method
public Set<Table2> getTable2s(){
return table2s
}
And the same pattern in the Table2 class for referencing Table3.
I would expect that I can write the following code:
Table1 table1 = tableOneRepository.getOne(...);
Set<Table2> table2s = table1.getTable2s()
singleTable2 = table2s.iterator().next() // just get any one element, assume set in not empty
Set<Table3> table3s = singleTable2.getTable3s() // "no session" error
However, the final line always produces this error:
Caused by: org.hibernate.LazyInitializationException: could not initialize proxy [com...] - no Session
Note this issue never occurs when doing the first lazy load, it's always when doing a lazy load from an object that was itself lazy loaded
I've seen lots of suggestions about adding #Transactional to methods, but it hasn't worked. Help please?
Well we need more informations. First the declaration of the entities. Somehting might be missing. Then more code. Here we don't even have the declaration of the function
Even if it might not be the real cause, check you have imported the spring transactional annotation and not the javax annotation
Edit : as far as I remember I've also worked with "nested" objects like this.
Not sure, but might work : try to do this after you retrieved the singleTable2. I don't remember you have to do this when you access an object, but try it anyway
Hibernate.initialize(singleTable2)

#JoinColumn and how it links two tables

I am completely new to working with databases and a beginner to Spring Boot as well really so apologies for any wrong terminology/fuzzy logic. There are some similar questions to this on here but I have not found exactly the answer to what I was looking for so I decided to post. Ramble over.
I am reading an article about joining tables in Spring Boot. They have a teacher class and a course class and it is a one-to-many relationship. They don't have the full classes written out but it says that you can go into Teacher class and do:
#OneToMany
#JoinColumn(name = "TEACHER_ID", referencedColumnName = "ID")
private List<Course> courses;
or go to Course class and do:
#ManyToOne
#JoinColumn(name = "TEACHER_ID", referencedColumnName = "ID")
private Teacher teacher;
What threw me off is that the parameters given to JoinColumn were the same in both cases. Assuming that both tables have something called ID, how does Spring know which one to use? Does it start by looking at both tables, looking for teacher_id. Then, after finding that it switches to the other table to get the ID?
Actually this is in the methodology of One-To-Many mappings in relational databases.
To achieve 1-N relation you only need to have:
Table One -> primary_key
Table Many -> primary_key, fk_one_primary_key
With the above configuration, given a table One entity, you can get all it's Many relations using the primaryKey-foreignKey join, and vice versa.
Now, in the code you've shared, the two parameters are described as:
ID -> Primary key column of table One / Teacher
TEACHED_ID -> foreign key column of table Many / Course

I am using Spring boot jpa with Restful api services to insert multiple users in array or list

As I am new to Spring boot. I am not at all clear about mappings. By using #Onetomany mapping in one entity and #manytoOne mapping at other entities. Using the controller I have to write REST API functions to insert multiple users at a time inside an array or set. Can anyone please suggest some websites or provide some existing codes?
The #OneToMany and #ManyToOne mappings can be used according to your use-case, whether you need bi-directional mappping or not. For a simple example consider the following :
#Entity
#Table(name="ENTITY_A")
public class EntityA{
//...
#OneToMany(mappedBy="EntityA")
private Set<EntityB> entityBItems;
// getters and setters
}
#Entity
#Table(name="ENTITY_B")
public class EntityB{
//...
#ManyToOne
#JoinColumn(name="entityA_id", nullable=false)
private EntityA entityA;
public EntityB() {}
// getters and setters
}
What you need to look out for is the owning side of the relation indicated by the mappedBy . The owning entity can be used to persist and get the data from the database. But from the description in your question I cannot understand whether you actually need to use mappings at all as you just have to insert multiple users into a table without any relations to another entity. It will be more helpful if you could explain more about your use case and provide code samples for furthur analysis.
For details about the mappings article or article .
Official doc .
MappedBy signals hibernate that the owner of key (relationship) is on the other side.
This means that although you link 2 tables together, only 1 of those tables has a foreign key constraint to the other one.
MappedBy allows you to still link from the table not containing the constraint to the other table.
If you still want use #JoinColumn on both the Entities you can use #JsonManagedReference and #JsonBackReference from com.fasterxml.jackson
To save the multiple records at same time you can use yourRepository.saveAll(entities)

Hibernate Mysql mapping relationship

I'm not sure if this is possible to do in Spring 3 framework using hibernate and mysql but I would appreciate any help. I have two classes - Employee and Examiner. The examiner is an employee and an employee is also an examiner. At the same time each Examiner can examine one or more employees and an employee can only have one Examiner.
Basically what I want to know is if it is possible to show the inheritance between the Employee and Examiner, and at the same time map a unidirectional one to many from Examiner to Employee?
What I have so far - the Examiner table with the inheritance constraint:
CREATE TABLE `examiner` (
`employee_id` varchar(255) NOT NULL,
`employee_name` varchar(255) NOT NULL,
PRIMARY KEY (`enployee_id`),
FOREIGN KEY (`employee_id`) REFERENCES `employee` (`employee_id`)):
The employee table:
CREATE TABLE `employee` (
`employee_id` varchar(255) NOT NULL,
`employee_name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`employee_id`)):
I was thinking of a join table for showing the one to many behaviour but getting a compsite key for the table is not possible as I have a primarykeyjoin column.
I would appreciate any help in pulling this together as I have been stumped for days.
Java doesn't allow multiple inheritance, so unless you are using an interface I am not sure how you plan to make the two described classes instances of each other.
You could just make a class called EmployeeExaminer, and make it reference itself. With annotations it might look something like:
#Entity
public class EmployeeExaminer {
#ManyToOne
private EmployeeExaminer getExaminer() {/*...*/}
#OneToMany
private List<EmployeeExaminer> getEmployees() { /*...*/}
}
Documentation on the annotations can be found here.
Thanks #CodeChimp for your replies. I ended up following the first suggestion, and created a Self Reference class with the #onetomany and #manytoone annotations. The helper class for it works. I just have some problems implementing a controller and jsp page for adding the parent/child. But I will make a new question for that. Thanks again.

Resources