JPA relationship - java

I have created two tables as person and address using JPA. I want to give one-to-many relationship between these tables. If I give the following
#OneToMany(mappedBy="address",targetEntity=person.class,fetch=FetchType.EAGER)
in the address table means it's not working correctly. Can any one help me?
Thanks in advance.

Without knowing anything about your architecture I will guess as to what you need.
JPA is smart enough to know how to join your tables so if you have id's in both tables you actually don't need to have "mappedBy" and "targetEntity".
You simply need to annotate your class as follows: (assuming your relationship is one address has many people).
Within the Address class:
#OneToMany
#JoinColumn(name="address_id")
public List<Person> getPeople()
{
return people;
}
This will place address_id as a field in your person table representing their associated address. Since you are declaring your list of type Person JPA will know to map to the person table (as long as the Person class is annotated properly with #Entity).

this is an example
#ElementCollection
#CollectionTable(name = "NUMBER")
private List<String> number;

Related

How to avoid creating linking table using #ElementCollection?

I have two entities - Person and Car. Instead of mapping them with #OneToMany relationship, I decided to use #ElementCollection (storing car ids only), so that I could have less load on my DB, additionaly fetching cars whenever I fetch Person.
But Hibernate keeps creating new linking table like 'person_car_ids'. So my question is - how do I map Person id in 'car' table?
#Entity
public class Person implements Serializable {
#Id
private String id;
#ElementCollection
private Set<Long> carIds = new HashSet<>();
From the JPA Wiki:
An ElementCollection can be used to define a one-to-many relationship to an Embeddable object, or a Basic value (such as a collection of Strings). [...] The ElementCollection values are always stored in a separate table.
It doesn't say anywhere that it won't use a different table to store your basic values, just makes it more convenient without having to use a wrapper.
To your question:
I decided to use #ElementCollection (storing car ids only), so that I could have less load on my DB, additionaly fetching cars whenever I fetch Person.
Not sure I got it right, but if you want to fetch cars only when you need them instead of loading them when you fetch a person entity, you can use Lazy loading, which is the default when you use OneToMany annotation.

how to generate tables from enums with values in spring boot?

#Entity
public class User{
#Id()
private int id;
private UserStatus userStatus;
}
public enum Country{
Active, Pending, Blocked;
}
I want to create a UserStatus Table with the values inside.
1st approach would be to use #Enumerated with String or Integer.but, i dont want that, since these enum values can be changed.
Another approach is to have declare #Entity on the UserStatus class. add Id and value. Keep a ManyToOne mapping . so that, user will have the referenced foreign key as the userstatus.
Is it the best approach, if we want to persist the enum values in the table or is there any other approach ?
Can we generate the Gender table with enum values in it in spring boot?
[ The UserStatus enum is just an example. The main idea is to know what are the best approaches to create the table and it's value.]
I would be very glad to have some points around this.
Let's assume you are using MySQL as Database.
Now if I ask you
How will you store Country column in User table?
What will be Column type?
VARCHAR I guess.
Same approach is followed in #Entity level as well.
So this approachs sounds good to me
#Enumerated(EnumType.STRING)
private UserStatus gender;
Can read this post for more detail
Regarding your suggestion on
#Entity on the UserStatus
You are adding 1 more layer of complexity.
Will have to manage another Table. LAZY_LODAING, CASCADING and other stuff need to be handled.

What is the difference in using #OneToMany vs #ManyToOne to the otherside for the same relationship?

I have two tables: Student and Address. A student has many addresses and I am trying to use #OneToMany on the Student table. A question came into mind what if I use #ManyToOne on the Address table to mention that one Address belongs to Many Students. Please help my clarify my concern.
A single Student has three addresses say Address1, Address2 and Address3.
The Relationship model for above will be, say Student id is a primary key in Student and will act as a foreign key in Address:-
Then in your Address class, you will define this relationship as below:-
#ManyToOne
#JoinColumn(name ="STUDENT_ID")
private Student student;
We use #OneToMany and #ManyToOne, two different annotations, so that we are able to tell Hibernate which object is the child/many part of the relationship and which object is the parent/one side of the relationship.
We are able to tell Hibernate which object is the parent object by assigning the #OneToMany annotation to the appropriate getter method… and which object is the child object by assigning the #ManyToOne annotation to the appropriate getter method.
Hence, Address becomes child side of relationship and Student becomes
parent side of relationship.
You might even use both if it makes sense. Basically you define in which direction the relation is navigable, e.g. if a student has an address you'll probably want to be able to navigate from that student to her address. However, an address might be shared by multiple persons which are not only students so the relation on that side might be different (or not needed at all).
Whatever you decide there's one thing you should keep in mind: you should define one side of the relation to be the owner (owning side) as otherwise you'd confuse Hibernate and get unexpected results. If there's only one side (i.e. Student->Adress but not the other way round) it's easy, if you got both sides you need to declare one the owning side - in most cases this will be the "many"-side, i.e. where you put the #ManyToOne. The other side must be declared as non-owning or you get two owning sides, e.g. by adding mappedBy="name_on_owning_side" to #OneToMany.
Example:
class Student {
#ManyToOne
Address address;
}
class Address {
#OneToMany( mappedBy = "address" )
Set<Student> residents;
}
Here Student is the owner of the bidirectional relation (which allows you to navigate student->address and address->resident(student) ) and only changes to Student.address would be written to the database.
A final note: as you can see that's quite a complex topic so you might want to have a look at some tutorial, e.g. here: https://en.wikibooks.org/wiki/Java_Persistence/ManyToOne and https://en.wikibooks.org/wiki/Java_Persistence/OneToMany

Difference between using #OneToMany and #ManyToMany

I am having some trouble understanding the difference between #OneToMany and #ManyToMany. When I use #OneToMany it defaults to create a JoinTable and if you add the mappedBy attribute you will have bidirectional relationship between two entities.
I have a Question that may belong to many Categories, and one Category may belong to many Questions. I don't understand if I should use #ManyToMany or #OneToMany because for me it seems exactly the same thing, but it is probably not.
Could somebody explain it?
Well, the difference is in the design you're trying to reflect using objects.
In your case, every Question can be assigned to multiple Categories - so that's a sign of #*ToMany relationship. Now you have to decide if:
each Category can have only one Question assigned to it (it will result in a unique constraint which means that no other Category can refer the same Question) - this will be #OneToMany relationship,
each Category can have multiple Questions assigned to it (there will be no unique constraint in the Category table) - this will be #ManyToMany relationship.
#OneToMany (Question -> Category)
This relationship can be represented by join table only if you explicitly define so using #JoinTable or when it is a unidirectional relationship in which the owning side is the 'One' side (it means that in the Question entity you have a collection of Categories, but in the Categories you don't have any reference to the Question).
If you think about it, it seems quite reasonable that the join table is used. There is no other way the DBMS could save a connection between one row in Question table with multiple rows in Categories table.
However, if you would like to model a bidirectional relationship you need to specify that the Category ('Many' side) is the owning side of the relationship. In this case the DBMS can create a join column with foreign key in the Category table because each Category row can be connected with only one Question.
In this way you don't have any join table but simple foreign keys (still, as pointed at the beginning, you can force to create the join table using #JoinTable).
#ManyToMany
This relationship must be represented as a join table. It basically works very similar to the unidirectional #OneToMany relationship, but in this case you may have multiple rows from Question joined with multiple rows from Categories.
#ManyToMany relationships have mutually referential foreign keys on both sides of the relationship. Sometimes, this relationship is mediated by an adjoining table.
#OneToMany relationships have a foreign key on the "one" side and not on the "many" side. In a #OneToMany relationship, one object is the "parent" and one is the "child". The parent controls the existence of the child.
Remember that a #ManyToMany bi-directional relationship need not be symmetric!
In your Questions & Categories case, you should use #ManyToMany relationship. #ManyToMany basically means that "a Question can belong to many Categories at the same time" and "a Category can contain many Questions at the same time". A new table will automatically be created to store the mappings. Your code would look like this:
#Entity
public class Question implements Serializable {
...
#ManyToMany
private List<Category> categories;
...
}
#Entity
public class Category implements Serializable {
...
#ManyToMany
private List<Question> questions;
...
}
If you use #OneToMany relationship for your Questions and Categories (let's say Category on the One side and Questions on the other), this means that "a Question can only belong to one Category" and "a Category can contain many Questions at the same time". No new table is needed to store the mapping. Instead, a new field will automatically be created in the Many side to record the ID of the One side. Your code would look like this:
#Entity
public class Question implements Serializable {
...
#ManyToOne
private Category theCategory;
...
}
#Entity
public class Category implements Serializable {
...
#OneToMany(mappedBy="theCategory")
private List<Question> questions;
...
}

Many to Many Mapping in Hibernate without Collection

Given a classic example of Student and Subject
where they have a many-to-many relationship,
is there any way to map them using POJOs w/o the use of Collections?
e.g.
Student.java
#Entity
class Student{
#id
int id;
String name;
}
Subject.java
#Entity
class Subject{
#id
int id;
String desc;
}
Tables
student (id,name)
subject (id,desc)
student_subject (student_id, subject_id) /* both foreign keys */
How will you query all subjects of a student?
Is it possible to generate these tables with the given beans?
Thanks in advance!
UPDATE: (I'll just give a background why I ask this ?)
My reason for avoiding Collections is that I would like my Service Layer to return data that is not tied to the Persistence Layer. Returning a Student object that has a list of Subjects will make my Service Layer Clients assume that they can get the subjects from the returned student object (then they'll get a LazyLoadException). If I make it EAGER loading, it would be overkill, since in many situations the client would only like the info about the Student and not get all his subjects.
To get all subjects, you need to join the tables like so:
select *
from subject
join student_subject
on subject.id = student_subject.subject_id
where
student_subject.student_id = ?
Is it possible to generate these tables with the given beans?
If you use the many-to-many mapping from Hibernate, it will create the query for you if you add the collections in the POJOs. Without the collection, you have to do it manually.
Note that the collections won't take memory unless:
You use them for the first time
Or you mark them a "load eagerly" in the POJO.
The default is lazy loading, so even if the tables are huge, you won't notice.
The question you should ask is, can you model your classes such that a many-to-many relationship can be established between them without collections?
It would be ideal to use collections and then let Hibernate use lazy-loading to populate the object graph.

Categories

Resources