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())
Related
I came across the terms i.e owning side and non-owning side while studying hibernate.For example :- here is
the statement regarding usage of mappedby element in terms of its usage in one to one mapping
If the relationship is bidirectional, the non-owning side must use the
mappedBy element of the OneToOne annotation
to specify the relationship field or property of the owning side.
But i did not get what actually owning side and non-owning side is?
The idea of a owning side of a bidirectional relation comes from the fact that in relational databases there are no bidirectional relations like in the case of objects.
In databases we only have foreign keys, where only one table can have a foreign key to another. Let's take an example that would not work as expected and see why mappedBy is necessary:
#Entity
#Table(name="PERSONS")
public class Person {
#OneToMany
private List<IdDocument> idDocuments;
}
#Entity
#Table(name="IDDOCUMENT")
public class IdDocument {
#ManyToOne
private Person person;
}
This would create not only tables PERSONS and IDDOCUMENTS, but would also create a third table PERSONS_IDDOCUMENTS:
CREATE TABLE persons_iddocument
(
persons_id bigint NOT NULL,
iddocuments_id bigint NOT NULL,
CONSTRAINT fk_persons FOREIGN KEY (persons_id) REFERENCES persons (id),
CONSTRAINT fk_docs FOREIGN KEY (iddocuments_id) REFERENCES iddocument (id),
CONSTRAINT pk UNIQUE (iddocuments_id)
)
Notice the primary key on documents only. In this case Hibernate tracks both sides of the relation independently: If you add a document to relation Person.idDocuments, it inserts a record in PERSON_IDDOCUMENTS.
If we change the Person of a IdDocument, it changes the foreign key person_id on table IDDOCUMENTS.
Hibernate is creating two unidirectional (foreign key) relations on the database, to implement one bidirectional object relation, because databases do not support bidirectional relations.
But what we want is for the object relation to be only mapped by the foreign key on table IDDOCUMENTS towards PERSON: one document belongs to only one person.
There is no need for the extra table, that would force us to modify both Person.idDocuments and IdDocument.person inside the same database transaction to keep the relation consistent.
To solve this we need to configure Hibernate to stop tracking the modifications on relation Person.idDocuments. Hibernate should only track the other side of the relation IdDocument.person, and to do so we add mappedBy:
#OneToMany(mappedBy="person")
private List<IdDocument> idDocuments;
This means "modifications on this side of the relation are already Mapped By by the other side of the relation IdDocument.person, so no need to track it here separately in an extra table".
This gives us the mapping we want, but has one major consequence:
Modifications on the Person.idDocuments collection are no longer tracked by Hibernate, and it is the responsibility of the developer to modify IdDocument.person instead in order to modify the association.
The 'owning' side is the entity whose table will hold the reference.
If you have a one-to-one relationship between EntityPerson and EntityAddress, then, if EntityPerson is the owning side, it will have in its table something like
ADDRESS_ID int NULL FOREIGN KEY REFERENCES Address (ID)
Here is my understanding with simple example where College has many students(One to many relationship)
corresponds to
College(Value Object) -----------------> College (Database Table)
corresponds to
Student(Value Object) -----------------> Student (Database Table having column which is
foreign key to College table .
So This is owning side and College is
Non-owning side )
In terms of Object representation, Student object is owning side becoz it will be having reference pointing to college column.So Student is owning side and College in non-owning side.
Usage of Owner side and Non-Owning side in hibernate in relation of mapped by element
Non-Owning Side Object
#Entity
public class College {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int collegeId;
#OneToMany(mappedBy="college") // here non-owning side using mapped by elment to specify
// the relationship field of owning side
private List<Student> students;
}
Owning Side Object
#Entity
public class Student {
#ManyToOne
private College college;
}
In conclusion the owning side is the entity that has the reference to the other. In terms of DB, it
translate to table entity having column which is foreign key to column in other table like in
case of College has many students.
Note:- owning-side table must contain a join column that refers to the other table's id.It means owning side entity should contain #joincolumn annotation otherwise it will consider the name as primary key column name of other table. See #OneToOne unidirectional and bidirectional
How do I implement the following relationship using JPA?
table person (
id int,
name text
)
table person_home (
person_id int,
home_id int,
type char(1) -- 'p' = primary, 's' = secondary
)
table home (
id int,
address text
)
A person can have many homes, and a home can have many persons living in it (i.e. ManyToMany relationship).
Furthermore, a home can be a primary residence for one person, but a secondary residence for another person at the same time.
I'm not sure how to model this relationship, even though the database schema is clear.
I have thought of splitting mapping table person_home into person_primary_home and person_secondary_home, however I would prefer to retain the schema if possible.
This question is pretty much asked and answered here:
How to create a composite primary key which contains a #ManyToOne attribute as an #EmbeddedId in JPA?
You need four classes:
Person.java
Home.java
PersonHome.java
PersonHomePk.java
The Person.java and Home.java files you create with one to many relations to the PersonHome.java. They'll have #Id fields to identify the primary keys. Each will have a #OneToMany relation defined with at least a mappedBy attribute mapping to their respective fields in the PersonHome entity. i.e. in the Person.java you could have something like
#OneToMany(cascade = CascadeType.ALL, mappedBy = "Person")
private Collection<PersonHome> personHome;
The PersonHome.java will have an #EmbeddedId field to identify the PersonHomePk instance declaration which is its primary key (that is, instead of an #Id column you will have an #EmbeddedId annotating a declaration of a class representing the primary key of the join table PersonHome). Any other fields are declared as normal columns. The PersonHome.java will also declare two ManyToOne relations one each to person and home. These will use #JoinColumn annotation (make sure they have the attributes insertable=false and updatable=false). The datatypes will be the Person and Home classes. i.e.
#EmbeddedId
protected PersonHomePk personHomePk;
#Column (name = "type")
private String type;
#JoinColumn(name = "person_id", referencedColumnName = "person_id", insertable = false, updatable = false)
#ManyToOne(optional = false)
private Person person;
You'll need the same for the "Home" declaration too. Why are you using only a char for "type". I'd recommend a varchar so people who maintain the thing once you're gone will understand the code and database better when you aren't around. 'detached' is easier to understand the 'd'.
I believe if you're going to have metadata besides the relationship on the person_home table, you need to use three objects with two one-to-many relationships in order to be able to access all of the data.
You could eliminate this need by having two many-to-one relationships from the person table to the home table, by having primary_home_id and secondary_home_id -- unless I'm missing a requirement here and a person can have more than one primary or secondary home.
What is the difference between using a #OneToMany and #ElementCollection annotation since both work on the one-to-many relationship?
ElementCollection is a standard JPA annotation, which is now preferred over the proprietary Hibernate annotation CollectionOfElements.
It means that the collection is not a collection of entities, but a collection of simple types (Strings, etc.) or a collection of embeddable elements (class annotated with #Embeddable).
It also means that the elements are completely owned by the containing entities: they're modified when the entity is modified, deleted when the entity is deleted, etc. They can't have their own lifecycle.
I believe #ElementCollection is mainly for mapping non-entities (embeddable or basic) while #OneToMany is used to map entities. So which one to use depend on what you want to achieve.
#ElementCollection allows you to simplify code when you want to implement one-to-many relationship with simple or embedded type. For instance in JPA 1.0 when you wanted to have a one-to-many relationship to a list of Strings, you had to create a simple entity POJO (StringWrapper) containing only primary key and the String in question:
#OneToMany
private Collection<StringWrapper> strings;
//...
public class StringWrapper {
#Id
private int id;
private String string;
}
With JPA 2.0 you can simply write:
#ElementCollection
private Collection<String> strings;
Simpler, isn't it? Note that you can still control the table and column names using #CollectionTable annotation.
See also:
Java Persistence/ElementCollection
Basic or Embedded: #ElementCollection
Entities: #OneToMany or #ManyToMany
#ElementCollection:
the relation is managed (only) by the entity in which the relation is defined
table contains id reference to the owning entity plus basic or embedded attributes
#OneToMany / #ManyToMany:
can also be managed by the other entity
join table or column(s) typically contains id references only
#ElementCollection marks a collection. This does not necessarily mean that this collection references a 1-n join.
ElementCollection can override the mappings, or table for their collection, so you can have multiple entities reference the same Embeddable class, but have each store their dependent objects in a separate table.
#ElementCollection
This annotation will be applied when there is a relation with non-entity and these associations relation was HAS-A. Every collection is created with a table and gets relation by Foreign Key.
There are two types of element collections
Index (List, Map)
Non-Index (Set)
Index: The index type collection has a table with 3 columns they are
Key Column (Foriegn Key)
Index Column (Position of data in collection)
Element Column (Data)
Non-Index: The Non-Index type collection has a table with 2 columns they are
Key Column
Element Column
Note: Here it won't have any index column because, Since a SET doesn’t retain the insertion order.
Multiplicity
This is a way to implement the HAS-A relation between two entities and the cardinality ratio depends on their relation.
You can use ElementCollection replace for you use #OneToMany. Example you can have one Project in many versions.
#ElementCollection
#CollectionTable(name="versions",
joinColumns = #JoinColumn(name="projectID"))
#LazyCollection(LazyCollectionOption.FALSE)
#JoinColumn(name="version",nullable = false)
private Set<String> versions;
You also can use #ElementCollection in mapping OGM for array in one collection.
#ElementCollection(fetch = FetchType.EAGER)
private Set<String> researchAreas;
Will this work -
#OneToOne()
#JoinColumn(name = "id", referencedColumnName = "type_id")
#Where(clause = "type_name = OBJECTIVE")
public NoteEntity getObjectiveNote() {
return objectiveNote;
}
This is what I am trying to do - get the record from table note whose type_id is the id of the current object and type_name is OBJECTIVE.
I can't get the above mapping to work. What am I doing wrong here?
This just plain does not work, sorry :( You will need to do it as one to many and live with getting a collection with a single element.
If you really want it to work this way, you can trick hibernate by storing both the foreign key ID and the type_name in a join table and telling it that both columns make up the foreign key.
Actually you can achieve this by specifying #OneToOne without any #Where, but putting #Where on the referenced entity class. I tested this on Hibernate 4.3.11.
This works if you don't care about any entity objects that do not match your #Where.
If you do care about other entities, you can probably create a subclass entity, put #Where on it and join that subclass. But I have not tested this scenario.
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!