[this is my DB design](https://i.stack.imgur.com/7ckz4.png)
[Users entitie](https://i.stack.imgur.com/8mMfR.png)
[Roles entitie](https://i.stack.imgur.com/ACYNB.png)
[Project entitie](https://i.stack.imgur.com/ZJXKC.png)
The relation between Users and Has doesn't need to be unidirectional
Using this composite key class, we can create the entity class, which models the join table:
#Entity
class CourseRating {
#EmbeddedId
CourseRatingKey id;
#ManyToOne
#MapsId("studentId")
#JoinColumn(name = "student_id")
Student student;
#ManyToOne
#MapsId("courseId")
#JoinColumn(name = "course_id")
Course course;
int rating;
// standard constructors, getters, and setters
}
This code is very similar to a regular entity implementation. However, we have some key differences:
We used #EmbeddedId to mark the primary key, which is an instance of the CourseRatingKey class.
We marked the student and course fields with #MapsId.
#MapsId means that we tie those fields to a part of the key, and they're the foreign keys of a many-to-one relationship. We need it because, as we mentioned, we can't have entities in the composite key.
After this, we can configure the inverse references in the Student and Course entities as before:
class Student {
// ...
#OneToMany(mappedBy = "student")
Set<CourseRating> ratings;
// ...
}
class Course {
// ...
#OneToMany(mappedBy = "course")
Set<CourseRating> ratings;
// ...
}
Note that there's an alternative way to use composite keys: the #IdClass annotation.
3.4. Further Characteristics
We configured the relationships to the Student and Course classes as #ManyToOne. We could do this because with the new entity we structurally decomposed the many-to-many relationship to two many-to-one relationships.
Why were we able to do this? If we inspect the tables closely in the previous case, we can see that it contained two many-to-one relationships. In other words, there isn't any many-to-many relationship in an RDBMS. We call the structures we create with join tables many-to-many relationships because that's what we model.
Besides, it's more clear if we talk about many-to-many relationships because that's our intention. Meanwhile, a join table is just an implementation detail; we don't really care about it.
Moreover, this solution has an additional feature we haven't mentioned yet. The simple many-to-many solution creates a relationship between two entities. Therefore, we cannot expand the relationship to more entities. But we don't have this limit in this solution: we can model relationships between any number of entity types.
For example, when multiple teachers can teach a course, students can rate how a specific teacher teaches a specific course. That way, a rating would be a relationship between three entities: a student, a course and a teacher.
In this part of the page on Baeldung, in class CourseRegistration he is not using #MapsId("id") and he is not even using "referencedColumnName" in the JoinColumn annotation. This was not the case with previous examples on this page. I feel that MapsId and JoinColumn with referencedColumnName should have been used. If not why? He has used the above in all other examples in the same page.
I feel that MapsId and JoinColumn with referencedColumnName should have been used. If not why? He has used the above in all other examples in the same page.
In the example that you provided he uses the mappedBy attribute on the other side of the relationship, where OneToMany exists. This mappedBy attribute provides necessary information to JPA to understand how those 2 entities are related. Keep in mind entity fields represent columns in database and JPA knows what those columns are.
The entity that uses the mappedBy indicates that the other entity on the other side is the owner of that relationship between those 2 entities.
#ManyToOne does not have a mappedBy attribute since by default when you have #OneToMany together with #ManyToOne it is the side that has the #ManyToOne that is the owner of the relationship. So no mappedBy exists on #ManyToOne to short circuit this default mechanism.
But there is a way of making the entity that has the #ManyToOne to be the owner of the relationship. You have to also put above #ManyToOne the #JoinColumn(name = "ref", referencedColumnName = "ref2")
To sum up the example that you point to, uses the default mechanism where the side with the #ManyToOne is the owner of the relationship, and that is indicated directly from the other side with the mappedBy attribute on #OneToMany.
Bonus
#JoinColumn(name = "student_id") without referencedColumnName is used not to indicate the owner side of the relationship but just so the JPA is informed that the extra column that would be used as a foreign key would not have the same name as the field of the entity has. So it is just used to override the foreign key column name that JPA will use as foreign key which will not be the same with the java field name.
As for #MapsId check this answer to understand better how it is used
Both are not needed here for different reasons:
#MapsId is mostly used to share a primary key between entities. CourseRegistration is its own entity with its own primary key, thus it is not needed here. Here is a quote from the official documentation:
Designates a ManyToOne or OneToOne relationship attribute that
provides the mapping for an EmbeddedId primary key, an attribute
within an EmbeddedId primary key, or a simple primary key of the
parent entity. The value element specifies the attribute within a
composite key to which the relationship attribute corresponds. If the
entity's primary key is of the same Java type as the primary key of
the entity referenced by the relationship, the value attribute is not
specified.
(https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/MapsId.html)
referencedColumnName uses the name of the primary key of the referenced table as default and thus is not explicitly needed:
Default (only applies if single join column is being used): The same
name as the primary key column of the referenced table.
(https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/JoinColumn.html#referencedColumnName())
I have two tables table1, table2. Both have a one to one relation.
table2 contains foreign key of table1.
If I use
#OneToOne(cascade=CascadeType.ALL) or
#ManyToOne(fetch=FetchType.LAZY) for the method below. Then what will be the effect of it?
#Column( name = "table1_id" )
public Long getTable1Id() {
return this.table1Id;
}
If you use OneToOne than you need to define not id variable in class, but object of another class, like in these examples: http://docs.oracle.com/javaee/5/api/javax/persistence/OneToOne.html.
Lazy means that row from other table will not be fetched until accessed.
CascadeType.ALL means that all operations (like delete) will be propagated to associated object.
Ok so this is probably a trivial question but I'm having trouble visualizing and understanding the differences and when to use each. I'm also a little unclear as to how concepts like uni-directional and bi-directional mappings affect the one-to-many/many-to-many relationships. I'm using Hibernate right now so any explanation that's ORM related will be helpful.
As an example let's say I have the following set-up:
public class Person {
private Long personId;
private Set<Skill> skills;
//Getters and setters
}
public class Skill {
private Long skillId;
private String skillName;
//Getters and setters
}
So in this case what kind of mapping would I have? Answers to this specific example are definitely appreciated but I would also really like an overview of when to use either one-to-many and many-to-many and when to use a join table versus a join column and unidirectional versus bidirectional.
Looks like everyone is answering One-to-many vs. Many-to-many:
The difference between One-to-many, Many-to-one and Many-to-Many is:
One-to-many vs Many-to-one is a matter of perspective. Unidirectional vs Bidirectional will not affect the mapping but will make difference on how you can access your data.
In Many-to-one the many side will keep reference of the one side. A good example is "A State has Cities". In this case State is the one side and City is the many side. There will be a column state_id in the table cities.
In unidirectional, Person class will have List<Skill> skills but
Skill will not have Person person. In bidirectional, both
properties are added and it allows you to access a Person given a
skill( i.e. skill.person).
In One-to-Many the one side will be our point of reference. For example, "A User has Addresses". In this case we might have three columns address_1_id, address_2_id and address_3_id or a look up table with multi column unique constraint on user_id
on address_id.
In unidirectional, a User will have Address address. Bidirectional
will have an additional List<User> users in the Address class.
In Many-to-Many members of each party can hold reference to arbitrary number of members of the other party. To achieve this a look up table is used. Example for this is the relationship between doctors and patients. A doctor can have many patients and vice versa.
One-to-Many: One Person Has Many Skills, a Skill is not reused between Person(s)
Unidirectional: A Person can directly reference Skills via its Set
Bidirectional: Each "child" Skill has a single pointer back up to the
Person (which is not shown in your code)
Many-to-Many: One Person Has Many Skills, a Skill is reused between Person(s)
Unidirectional: A Person can directly reference Skills via its Set
Bidirectional: A Skill has a Set of Person(s) which relate to it.
In a One-To-Many relationship, one object is the "parent" and one is the "child". The parent controls the existence of the child. In a Many-To-Many, the existence of either type is dependent on something outside the both of them (in the larger application context).
Your subject matter (domain) should dictate whether or not the relationship is One-To-Many or Many-To-Many -- however, I find that making the relationship unidirectional or bidirectional is an engineering decision that trades off memory, processing, performance, etc.
What can be confusing is that a Many-To-Many Bidirectional relationship does not need to be symmetric! That is, a bunch of People could point to a skill, but the skill need not relate back to just those people. Typically it would, but such symmetry is not a requirement. Take love, for example -- it is bi-directional ("I-Love", "Loves-Me"), but often asymmetric ("I love her, but she doesn't love me")!
All of these are well supported by Hibernate and JPA. Just remember that Hibernate or any other ORM doesn't give a hoot about maintaining symmetry when managing bi-directional many-to-many relationships...thats all up to the application.
1) The circles are Entities/POJOs/Beans
2) deg is an abbreviation for degree as in graphs (number of edges)
PK=Primary key, FK=Foreign key
Note the contradiction between the degree and the name of the side. Many corresponds to degree=1 while One corresponds to degree >1.
One-to-many
The one-to-many table relationship looks like this:
In a relational database system, a one-to-many table relationship associates two tables based on a Foreign Key column in the child table referencing the Primary Key of one record in the parent table.
In the table diagram above, the post_id column in the post_comment table has a Foreign Key relationship with the post table id Primary Key column:
ALTER TABLE
post_comment
ADD CONSTRAINT
fk_post_comment_post_id
FOREIGN KEY (post_id) REFERENCES post
#ManyToOne annotation
In JPA, the best way to map the one-to-many table relationship is to use the #ManyToOne annotation.
In our case, the PostComment child entity maps the post_id Foreign Key column using the #ManyToOne annotation:
#Entity(name = "PostComment")
#Table(name = "post_comment")
public class PostComment {
#Id
#GeneratedValue
private Long id;
private String review;
#ManyToOne(fetch = FetchType.LAZY)
private Post post;
}
Using the JPA #OneToMany annotation
Just because you have the option of using the #OneToMany annotation, it doesn't mean it should be the default option for all the one-to-many database relationships.
The problem with JPA collections is that we can only use them when their element count is rather low.
The best way to map a #OneToMany association is to rely on the #ManyToOne side to propagate all entity state changes:
#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);
}
}
The parent Post entity features two utility methods (e.g. addComment and removeComment) which are used to synchronize both sides of the bidirectional association.
You should provide these methods whenever you are working with a bidirectional association as, otherwise, you risk very subtle state propagation issues.
The unidirectional #OneToMany association is to be avoided as it's less efficient than using #ManyToOne or the bidirectional #OneToMany association.
One-to-one
The one-to-one table relationship looks as follows:
In a relational database system, a one-to-one table relationship links two tables based on a Primary Key column in the child which is also a Foreign Key referencing the Primary Key of the parent table row.
Therefore, we can say that the child table shares the Primary Key with the parent table.
In the table diagram above, the id column in the post_details table has also a Foreign Key relationship with the post table id Primary Key column:
ALTER TABLE
post_details
ADD CONSTRAINT
fk_post_details_id
FOREIGN KEY (id) REFERENCES post
Using the JPA #OneToOne with #MapsId annotations
The best way to map a #OneToOne relationship is to use #MapsId. This way, you don't even need a bidirectional association since you can always fetch the PostDetails entity by using the Post entity identifier.
The mapping looks like this:
#Entity(name = "PostDetails")
#Table(name = "post_details")
public class PostDetails {
#Id
private Long id;
#Column(name = "created_on")
private Date createdOn;
#Column(name = "created_by")
private String createdBy;
#OneToOne(fetch = FetchType.LAZY)
#MapsId
#JoinColumn(name = "id")
private Post post;
public PostDetails() {}
public PostDetails(String createdBy) {
createdOn = new Date();
this.createdBy = createdBy;
}
//Getters and setters omitted for brevity
}
This way, the id property serves as both Primary Key and Foreign Key. You'll notice that the #Id column no longer uses a #GeneratedValue annotation since the identifier is populated with the identifier of the post association.
Many-to-many
The many-to-many table relationship looks as follows:
In a relational database system, a many-to-many table relationship links two parent tables via a child table which contains two Foreign Key columns referencing the Primary Key columns of the two parent tables.
In the table diagram above, the post_id column in the post_tag table has also a Foreign Key relationship with the post table id Primary Key column:
ALTER TABLE
post_tag
ADD CONSTRAINT
fk_post_tag_post_id
FOREIGN KEY (post_id) REFERENCES post
And, the tag_id column in the post_tag table has a Foreign Key relationship with the tag table id Primary Key column:
ALTER TABLE
post_tag
ADD CONSTRAINT
fk_post_tag_tag_id
FOREIGN KEY (tag_id) REFERENCES tag
Using the JPA #ManyToMany mapping
This is how you can map the many-to-many table relationship with JPA and Hibernate:
#Entity(name = "Post")
#Table(name = "post")
public class Post {
#Id
#GeneratedValue
private Long id;
private String title;
#ManyToMany(cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
#JoinTable(name = "post_tag",
joinColumns = #JoinColumn(name = "post_id"),
inverseJoinColumns = #JoinColumn(name = "tag_id")
)
private Set<Tag> tags = new HashSet<>();
//Getters and setters ommitted for brevity
public void addTag(Tag tag) {
tags.add(tag);
tag.getPosts().add(this);
}
public void removeTag(Tag tag) {
tags.remove(tag);
tag.getPosts().remove(this);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Post)) return false;
return id != null && id.equals(((Post) o).getId());
}
#Override
public int hashCode() {
return getClass().hashCode();
}
}
#Entity(name = "Tag")
#Table(name = "tag")
public class Tag {
#Id
#GeneratedValue
private Long id;
#NaturalId
private String name;
#ManyToMany(mappedBy = "tags")
private Set<Post> posts = new HashSet<>();
//Getters and setters ommitted for brevity
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Tag tag = (Tag) o;
return Objects.equals(name, tag.name);
}
#Override
public int hashCode() {
return Objects.hash(name);
}
}
The tags association in the Post entity only defines the PERSIST and MERGE cascade types. The REMOVE entity state transition doesn't make any sense for a #ManyToMany JPA association since it could trigger a chain deletion that would ultimately wipe both sides of the association.
The add/remove utility methods are mandatory if you use bidirectional associations so that you can make sure that both sides of the association are in sync.
The Post entity uses the entity identifier for equality since it lacks any unique business key. You can use the entity identifier for equality as long as you make sure that it stays consistent across all entity state transitions.
The Tag entity has a unique business key which is marked with the Hibernate-specific #NaturalId annotation. When that's the case, the unique business key is the best candidate for equality checks.
The mappedBy attribute of the posts association in the Tag entity marks that, in this bidirectional relationship, the Post entity owns the association. This is needed since only one side can own a relationship, and changes are only propagated to the database from this particular side.
The Set is to be preferred, as using a List with #ManyToMany is less efficient.
I would explain that way:
OneToOne - OneToOne relationship
#OneToOne
Person person;
#OneToOne
Nose nose;
OneToMany - ManyToOne relationship
#OneToMany
Shepherd shepherd;
#ManyToOne
List<Sheep> sheeps;
ManyToMany - ManyToMany relationship
#ManyToMany
List<Traveler> travelers;
#ManyToMany
List<Destination> destinations;
Take a look at this article: Mapping Object Relationships
There are two categories of object relationships that you need to be concerned with when mapping. The first category is based on multiplicity and it includes three types:
*One-to-one relationships. This is a relationship where the maximums of each of its multiplicities is one, an example of which is holds relationship between Employee and Position in Figure 11. An employee holds one and only one position and a position may be held by one employee (some positions go unfilled).
*One-to-many relationships. Also known as a many-to-one relationship, this occurs when the maximum of one multiplicity is one and the other is greater than one. An example is the works in relationship between Employee and Division. An employee works in one division and any given division has one or more employees working in it.
*Many-to-many relationships. This is a relationship where the maximum of both multiplicities is greater than one, an example of which is the assigned relationship between Employee and Task. An employee is assigned one or more tasks and each task is assigned to zero or more employees.
The second category is based on
directionality and it contains two
types, uni-directional relationships
and bi-directional relationships.
*Uni-directional relationships. A uni-directional relationship when an object knows about the object(s) it is related to but the other object(s) do not know of the original object. An example of which is the holds relationship between Employee and Position in Figure 11, indicated by the line with an open arrowhead on it. Employee objects know about the position that they hold, but Position objects do not know which employee holds it (there was no requirement to do so). As you will soon see, uni-directional relationships are easier to implement than bi-directional relationships.
*Bi-directional relationships. A bi-directional relationship exists when the objects on both end of the relationship know of each other, an example of which is the works in relationship between Employee and Division. Employee objects know what division they work in and Division objects know what employees work in them.
this would probably call for a many-to-many relation ship as follows
public class Person{
private Long personId;
#manytomany
private Set skills;
//Getters and setters
}
public class Skill{
private Long skillId;
private String skillName;
#manyToMany(MappedBy="skills,targetClass="Person")
private Set persons; // (people would not be a good convenion)
//Getters and setters
}
you may need to define a joinTable + JoinColumn but it will possible work also without...
First of all, read all the fine print. Note that NHibernate (thus, I assume, Hibernate as well) relational mapping has a funny correspondance with DB and object graph mapping. For example, one-to-one relationships are often implemented as a many-to-one relationship.
Second, before we can tell you how you should write your O/R map, we have to see your DB as well. In particular, can a single Skill be possesses by multiple people? If so, you have a many-to-many relationship; otherwise, it's many-to-one.
Third, I prefer not to implement many-to-many relationships directly, but instead model the "join table" in your domain model--i.e., treat it as an entity, like this:
class PersonSkill
{
Person person;
Skill skill;
}
Then do you see what you have? You have two one-to-many relationships. (In this case, Person may have a collection of PersonSkills, but would not have a collection of Skills.) However, some will prefer to use many-to-many relationship (between Person and Skill); this is controversial.
Fourth, if you do have bidirectional relationships (e.g., not only does Person have a collection of Skills, but also, Skill has a collection of Persons), NHibernate does not enforce bidirectionality in your BL for you; it only understands bidirectionality of the relationships for persistence purposes.
Fifth, many-to-one is much easier to use correctly in NHibernate (and I assume Hibernate) than one-to-many (collection mapping).
Good luck!
Create Table A (
ID varchar(8),
Primary Key(ID)
);
Create Table B (
ID varchar(8),
A_ID varchar(8),
Primary Key(ID),
Foreign Key(A_ID) References A(ID)
);
Given that I have created two tables using the SQL statements above, and I want to create Entity classes for them, for the class B, I have these member attributes:
#Id
#Column(name = "ID", nullable = false, length = 8)
private String id;
#JoinColumn(name = "A_ID", referencedColumnName = "ID", nullable = false)
#ManyToOne(optional = false)
private A AId;
In class A, do I need to reciprocate the many-to-one relationship?
#Id
#Column(name = "ID", nullable = false, length = 8)
private String id;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "AId")
private List<B> BList; //<-- Is this attribute necessary?
Is it a necessary or a good idea to have a reciprocal #OneToMany for the #ManyToOne? If I make the design decision to leave out the #OneToMany annotated attribute now, would that come back to bite me further along?
Is it a necessary or a good idea to have a reciprocal #OneToMany for the #ManyToOne?
No, it's not mandatory at all, it's a pure design decision. The whole question is... Do you want this (i.e. an uni-directional association):
Or this (i.e. a bi-directional association):
If you don't need to get Bs from A, then you can skip the bs attribute and the OneToMany on A side.
If I make the design decision to leave out the #OneToMany annotated attribute now, will come back to bite me further down.
No, and you can add it later if you discover that you need it.
They are optional. There is no need to add them to your model if you don't want to use them.
I'd sugguest to avoid the reverse mapping at all because such collections may become quite large and most persistance layers don't handle these very good. In many cases you'd have to deal with add/remove of already loaded/managed entities related to these collections yourself. So only add those if they really make things easier for you.
Sure not. Thats design decision between one vs two direction relationship. In most casses, a better choice is to have one direction relationship, especially if its a domain classes. doing this, your design will express better the mean of your domain.