Spring JPA LAZY load OneToOne relation won't load - java

i have a LAZY OneToOne relationship,
and i want to load it per use (The same model have more OneToOne relations and i want to do less queries to the Database.)
Looking at the native db queries in the log file, i can see the when i am not trying to access to user.city the SELECT FROM City... statement is not printed.
but when accessing user.city i can see the SQL Statement running in the log, i am getting the class instance. but all filled inside the City entity are null, see below more info:
this code:
System.out.println(user.city);
System.out.println(user.city.location);
will print
Hibernate:
select
city0_.id as id1_3_0_,
city0_.accentName as accentNa2_3_0_,
city0_.location as location3_3_0_,
city0_.name as name4_3_0_,
city0_.state_id as state_id5_3_0_
from
City city0_
where
city0_.id=?
com.dateup.models.City#1ed01095
null
Thous are my models :
#Entity
#Table(
indexes={#Index(name = "name", columnList="name")}
)
public class City {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long id;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
public State state;
public String name;
public String accentName;
#Column(name = "location", columnDefinition = "POINT")
public Point location;
}
#Entity
#Table(
name="User"
)
#Inheritance(strategy=InheritanceType.SINGLE_TABLE)
#DiscriminatorFormula("'User'")
#JsonAutoDetect
public abstract class BaseUser {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public Long id;
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#OneToOne(fetch = FetchType.LAZY)
public City city;
...
}
Just to mention that when testing this with #OneToOne(fetch = FetchType.EAGER) all is working fine..
thank you very much for the help.

I wouldn't do one-to-one.
... in city class:
#ManyToOne state; (I usually do EAGER for one side, lazy for other; (FetchType.EAGER, CascadeType.ALL, mappedBy='city'))
... in state class:
#OneToMany city; (a state has many cities).
Are you sure you have an INSERT statement somewhere in your logs, which adds the correct city with the correct id ?
It's hard to know without seeing all the code.

Related

JPA not saving foreign key in one-to-many relation

I have 2 tables with one-to-many relation on the owner class (Person) and many-to-one on the child class (Email)
My problem is that in the child class' foreign key is (person_id) is always null when I want to save my Person object. I tried different things using other questions' answers, but no luck.
I would like to solve this in an annotation approach, if it is possible.
Person Class:
#Entity
#Table(name="PERSON")
public class Person {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_PERSON")
#SequenceGenerator(name="SEQ_PERSON", sequenceName="SEQ_PERSON", allocationSize=1)
#Column(name = "person_id")
private Long personId;
#OneToMany(mappedBy="person", cascade=CascadeType.ALL)
private List<Email> email;
// getters and setters
}
Email class:
#Entity
#Table(name="EMAIL")
public class Email{
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_EMAIL")
#SequenceGenerator(name="SEQ_EMAIL", sequenceName="SEQ_EMAIL", allocationSize=1)
#Column(name = "email_id")
private Long emailId;
#ManyToOne
#JoinColumn(name="person_id", referencedColumnName="person_id", insertable = true)
private Person person;
// getters and setters
}
I get no exception / errors when I use this.
When I change the JoinColumn to #JoinColumn(name="person_id", referencedColumnName="person_id", nullable = false, updatable = false, insertable = true) then I get this error: org.hibernate.PropertyValueException: not-null property references a null or transient value: com.test.Email.person
I tried to change the Person's email setter like this, nothing changed:
public synchronized void setEmail(List<Email> email) {
this.email=email;
for(Email em: email) {
em.setPerson(this);
}
}
source
I have a Person object, with 2 emails (as a test object to save, every column is filled, except the FK in Email table), do I have to set the FK everytime manually? (it doesn't look good, if I have multiple one-to-many variables)
Edit: I tried this Which is working, but my problem with that if I have a very deep data structure with a lot of One-To-Many relations, I have to implement this to every variable and then save.. So, is there a better solution with pure annotations / getters-setters ?

Spring data jpa operation between table views

in my spring data application i have two TABLE VIEW mapped:
the first view
#Entity
#Immutable
#Table(name="VD_CONT")
#NamedQuery(name="VdContr.findAll", query="SELECT d FROM VdContr d")
public class VdContr {
#Id
#Column(name="CONTR_ID")
private Long id;
#Column(name="CF")
private String cf;
#OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="vdcontr")
private List<VdArr> vdArr;
}
and the second view
#Entity
#Immutable
#Table(name="VD_ARR")
#NamedQuery(name="VdArr.findAll", query="SELECT v FROM VdArr v")
public class VdArr {
#Id
#Column(name="ARR_ID")
private Long id;
#Column(name="FK_CONTR_ID")
private Long fkContrId;
#ManyToOne(fetch=FetchType.LAZY)
public VdContr vdcontr;
}
If i put a relationship "OneToMany" and "ManyToOne" (1, first view : many, second view), i receive errors.
My question is: is it possibile create a relationship between two table view?
you need to add a #JoinColumn to VdContr.
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name = "vdcontr_id", nullable = false)
In general, views are mapped in the same way as tables.
By looking at your classes, the problem is that Hibernate cannot find the correct join column. You need to specify it.
Also, in your VdArr you should delete the fkContrId, because hibernate will need to use this column to map the VdContr relationship.
By looking at your code, the join column is FK_CONTR_ID, so you need to specify it by using #JoinColumn.
#Entity
#Immutable
#Table(name = "VD_ARR")
#NamedQuery(name = "VdArr.findAll", query = "SELECT v FROM VdArr v")
public class VdArr {
#Id
#Column(name = "ARR_ID")
private Long id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "FK_CONTR_ID")
public VdContr vdcontr;
}

Spring boot: JPA incorrectly adds where clause

I have three entity classes; Student, Subject and StudentSubject.
Student has one to many relation on StudentSubject, and Subject also has one to many relation on StudentSubject.
Student class
#Entity
#Getter
#Setter
public class Student {
#Id
private String email;
#OneToMany(mappedBy = "student")
#JsonManagedReference
private List<StudentSubject> subjects;
//more elements
}
Subject class
#Entity
#Getter
#Setter
public class Subject {
#Id
#GeneratedValue
private Long id;
#ManyToOne
#JsonBackReference
private Teacher teacher;
#OneToMany(mappedBy = "student")
#JsonManagedReference
private List<StudentSubject> students;
//more elements
}
StudentSubject class
#Entity
#IdClass(StudentSubjectId.class)
#Getter
#Setter
public class StudentSubject implements Serializable {
//Primary keys
#Id
#Column(name = "subject_id")
Long subjectId;
#Id
#Column(name = "student_email")
String studentEmail;
String uid;
#ManyToOne
#JsonBackReference
#JoinColumn(name = "subject_id", insertable = false, updatable = false)
private Subject subject;
#ManyToOne
#JsonBackReference
#JoinColumn(name = "student_email", insertable = false, updatable = false)
private Student student;
}
I have 3 classes, and not 2, because there are attributes specific to each student subject pair. Hence this arrangement.
When I read a subject from repository, as such
Subject subject = subjectRepository.findByNameAndTeacher(subjectName, teacher);
subject.getStudents();
all it's details are correct, except for list of students. It is always empty.(checked this by adding breakpoint)
The queries that are executed by Hibernate/JPA are,
To get subject(?)
select
subject0_.id as id1_3_,
subject0_.name as name2_3_,
subject0_.teacher_email as teacher_3_3_
from
subject subject0_
left outer join
teacher teacher1_
on subject0_.teacher_email = teacher1_.email
where
subject0_.name =?
and teacher1_.email =?
To select student list(?)
select
students0_.student_email as student_1_2_0_,
students0_.subject_id as subject_2_2_0_,
students0_.student_email as student_1_2_1_,
students0_.subject_id as subject_2_2_1_,
students0_.uid as uid3_2_1_,
subject1_.id as id1_3_2_,
subject1_.name as name2_3_2_,
subject1_.teacher_email as teacher_3_3_2_,
teacher2_.email as email1_5_3_,
teacher2_.name as name2_5_3_
from
student_subject students0_
left outer join
subject subject1_
on students0_.subject_id = subject1_.id
left outer join
teacher teacher2_
on subject1_.teacher_email = teacher2_.email
where
students0_.student_email =?
and some more.
I think the issue here is that the last where clause is incorrectly added, and common attributes in tables are not shown once. How do I fix this?
Your mapping has a typo. In Subject class, it should be #OneToMany(mappedBy = "subject") instead of mappedBy="student" hence your wrong where clause.
This is the reason it is using
where students0_.student_email =?
instead of
where students0_.subject_id =? as it thinks the way to get to students from subject is through student_email column as indicated by your mapping.
You have not specified fetch type. This should fix it.
#OneToMany(mappedBy = "student", fetch = FetchType.EAGER)
#JsonManagedReference
private List<StudentSubject> students;

How to manage OnetoOne inserting data in child only

I am very new to hibernate and I am working with JPA and Hibernate4. Trying to insert parent object in child as onetoone relationship.
I went through some tutorials but All the example in the web shows, inserting both parent and child tables.
I want to insert data in child table only.
I have two tables called user and department.
User table consists of user details with department as onetoone relationship, as follows,
#Entity
#Table(name = "User")
public class UserEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "_id")
private String id;
#Column(name = "firstName")
private String firstName;
#Column(name = "lastName")
private String lastName;
#OneToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "departmentId")
private Department departmentId;
// getters and setters...
}
Below is my Department entity,
#Entity
#Table(name = "Department")
public class Department {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "_id")
private String id;
#Column(name = "name")
private String name;
// getters and setters...
}
In department table there is only 4 data. I want to insert data only in user data while insert into it and don't want to insert in Department.
How can I do that.Please assist.
You have to use mappedBy for this, as mentoned below in child Table, Department in your case
#OneToOne(mappedBy="department")
private UserEntity user;
These posts explain you better this,
JPA JoinColumn vs mappedBy
Understanding mappedBy annotation in Hibernate
You need to specify the relationship owner using mappedBy property in the OneToOne mapping in the owner side, here in your case in the Department class, you should add:
#OneToOne(mappedBy="department")
private UserEntity user;
I updated your code, to included the stated annotation and also renamed the Department property in your UserEntity class from departmentId to department to avoid confusion between relationship owner and its id:
#Entity
#Table(name = "User")
public class UserEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "_id")
private String id;
#Column(name = "firstName")
private String firstName;
#Column(name = "lastName")
private String lastName;
#OneToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "departmentId")
private Department department;
// getters and setters...
}
Below is the Department entity,
#Entity
#Table(name = "Department")
public class Department {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "_id")
private String id;
#Column(name = "name")
private String name;
#OneToOne(mappedBy="department")
private UserEntity user;
// getters and setters...
}
This will give you the right mapping with the expected behaviour.
In the #OneToOne annotation, the default value for parameter optional is true. So your annotation is the same as #OneToOne(fetch = FetchType.EAGER, optional = true). This means you can simply leave the Department in a UserEntity instance empty. In that case, persisting it results in persisting only a user entity and no department.
Even if you created a Department instance and assigned it to a UserEntity instance, persisting the UserEntity would not automatically persist the Department, since you don't have any cascade parameter in your annotation. If you don't automatically cascade persists, you would have to persist the Department first and then persist the corresponding user entity.
Maybe you're asking about using existing departments for your user entities. In that case, you first need to get the department via Hibernate (or the JPA API) from an entity manager. The entity instance you get is managed by Hibernate, and you can then set it in a UserEntity and persist that, to have it refer to the department.
Finally, I think one department will probably have more than one user. It might make more sense to have a #ManyToOne annotation instead of #OneToOne, indicating multiple users can refer to the same department, but that depends on your domain model.

Annotation to join columns with OR condition instead of AND condition

I have 2 java classes, Relation and Person, which both are present in my database.
Person:
#Entity
#Table(name = "persons")
public class Person {
#Id
#Column
private int id;
#Column
private String name;
#OneToMany(fetch = FetchType.EAGER)
#JoinColumns({
#JoinColumn(name = "slave_id", referencedColumnName="id"),
#JoinColumn(name = "master_id", referencedColumnName="id")
})
private List<Relation> relations;
//Getters and setters
}
Relation:
#Entity
#Table(name = "relations")
public class Relation {
#Id
#Column
private int id;
#Column
private int child_id;
#Column
private int parent_id;
#Column
private String type;
//Getters and setters
}
Each Person has a list of relations (or not), the relation should be added to the list when the child_id or the parent_id of the relation is equal to the id of the person.
TL;DR:
When relation.child_id OR relation.parent_id = person.id => add relation to list of relations to the person
The issue I am facing is that this annotation:
#JoinColumns({
#JoinColumn(name = "child_id", referencedColumnName="id"),
#JoinColumn(name = "parent_id", referencedColumnName="id")
})
creates following SQL (just the necessary part):
relations relations6_
on this_.id=relations6_.slave_id
and this_.id=relations6_.master_id
What is the correct annotation in Java Hibernate to generate an SQL statement saying OR instead of AND
Some of the options that you could utilize:
Database views. Create the view that does custom join for you and map the entity to the view.
Join formula. I managed to make them work only on many-to-one associations. Nevertheless, you could make the association bidirectional and apply the formula in the Relation entity.
#Subselect. This is a kind of Hibernate view, suitable if you can't afford to create a real database view or change the db schema to better suit the entity model structure.
This and this answer could also be helpful.
Also, you can always use two separate associations for slaves and masters:
public class Person {
#OneToMany
#JoinColumn(name = "slave_id"),
private List<Relation> slaves;
#OneToMany
#JoinColumn(name = "master_id"),
private List<Relation> masters;
public List<Relation> getRelations() {
List<Relation> result = new ArrayList<>(slaves);
result.addAll(masters);
return result;
}
}
However, keep in mind that joining all of them in a single query requires full Cartesian product between masters and slaves.
You can use #FilterDef and #Filter annotations.

Categories