Enterprise Java Development@TOPIC@
Uni-directionalOnly one side ("owner") knows of the relationship
Uses the @ManyToOne annotation
Defines mapping to database
Uses either @JoinColumn or @JoinTable
Bi-directionalSame as One-to-Many Bi-directional
Example uses composite key and derives primary key from foreign key
Foreign key auto-generated
Figure 61.2. Many-to-One Uni-directional Database Schema
create table ORMREL_MEDIA (
+--------> MEDIA_ID bigint generated by default as identity,
| title varchar(255),
| primary key (MEDIA_ID)
| )
| create table ORMREL_MEDIACOPY (
| COPY_NO integer not null,
`--------- MEDIACOPY_MID bigint not null,
primary key (COPY_NO, MEDIACOPY_MID)
)
alter table ORMREL_MEDIACOPY
add constraint FKCDB47669F152B359
foreign key (MEDIACOPY_MID)
references ORMREL_MEDIAFigure 61.3. Many-to-One Uni-directional Database Java Mapping
@Entity @Table(name="ORMREL_MEDIACOPY2")
@IdClass(MediaCopyPK2.class)
@AttributeOverrides({
@AttributeOverride(name="copyNo", column=@Column(name="COPY_NO"))
})
public class MediaCopy2 {
@Id //mapped to COPY_NO by attribute override
private int copyNo;
@Id
@ManyToOne
@JoinColumn(name="MEDIACOPY_MID")
+----- private Media media;
|
| private MediaCopy2() {}
| public MediaCopy2(Media media, int copyNo) {
| this.media=media;
| this.copyNo=copyNo;
| }
| ...
| @Entity @Table(name="ORMREL_MEDIA")
| public class Media {
`----> @Id @GeneratedValue @Column(name="MEDIA_ID")
private long id;
Figure 61.4. Many-to-One Uni-directional Database Usage
ejava.examples.orm.rel.annotated.Media media = new Media();
media.setTitle("EJB31");
//add media to DB
assertTrue(media.getId() == 0);
em.persist(media);
log.info("created media:" + media);
//create some copies
for(int i=0; i<5; i++) {
ejava.examples.orm.rel.annotated.MediaCopy2 mc =
new MediaCopy2(media, i);
assertNotNull(mc.getMedia());
assertEquals(i, mc.getCopyNo());
em.persist(mc);
log.info("created copy:" + mc);
}
Figure 61.5. Many-to-One Uni-directional Database Output
Hibernate:
insert into ORMREL_MEDIA (MEDIA_ID, title)
values (null, ?)
-created media:Media@51942b40, id=1, title=EJB31, authors(0)={}
-created copy:MediaCopy2@3787f275, mediaId=1, copyNo=0, media=Media@51942b40, id=1, title=EJB31, authors(0)={}
...
-created copy:MediaCopy2@7a7fdbb0, mediaId=1, copyNo=4, media=Media@51942b40, id=1, title=EJB31, authors(0)={}
Hibernate:
insert into ORMREL_MEDIACOPY2 (COPY_NO, MEDIACOPY_MID)
values (?, ?)
...
Hibernate:
insert into ORMREL_MEDIACOPY2 (COPY_NO, MEDIACOPY_MID)
values (?, ?)