Java Reference
In-Depth Information
ModelBase
is not itself an entity. By using
@MappedSuperclass
, JPA will
add its properties to each
@Entity
subclass. The
@Id
and
@Generated-
Value
annotations indicate that
id
is the identifier property and its val-
ues should be automatically generated by the database. This is inher-
ited by each of our model classes because they all extend
ModelBase
.
entities, and now we need to establish the relationships between them.
If we work our way from the top to the bottom of the diagram, all entities
have zero or more of the entity below: a user has zero or more folders, a
folder has zero or more messages, and so on. JPA refers to these types
of relationships as one-to-many if you're reading the diagram from top
to bottom or many-to-one if you're going from bottom to top.
JPA provides the
@OneToMany
and
@ManyToOne
annotations to describe
these relationships. The
User
class has a
@OneToMany
relationship with
the
Contact
class, and the
Contact
class has a
@ManyToOne
relation-
ship with the
User
class. We indicate these relationships by adding the
annotations to the properties:
@Entity
public class
User
extends
ModelBase {
@OneToMany(mappedBy="user")
private
Set<Contact> contacts;
/
*
Getters and setters...
*
/
}
Notice that the
mappedBy=
attribute of
@OneToMany
corresponds to the
name of the property in the
Contact
class that refers to the
User
:
@Entity
public class
Contact
extends
ModelBase {
@ManyToOne
private
User user;
/
*
Getters and setters...
*
/
}
We've identified the other side of the relationship with
@ManyToOne
on
the
user
property of the
Contact
class. After doing the same for the other
relationships between entities, we're done with adding JPA annotations
to the model.
Search WWH ::
Custom Search