JPA

Page 95

Java Persistence/ Print version @Id @Column(name="DEP_ID" insertable=false, updateable=false) private long departmentId; @Id @Column(name="COM_ID" insertable=false, updateable=false) private long companyId; ... @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="COM_ID") private Company company; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="DEP_ID") @PrimaryKeyJoinColumn(name="COM_ID") private Department department; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="MNG_ID") @PrimaryKeyJoinColumn(name="DEP_ID") @PrimaryKeyJoinColumn(name="COM_ID") private Employee manager; @OneToOne(fetch=FetchType.LAZY) @JoinColumn(name="ADD_ID") @PrimaryKeyJoinColumn(name="EMP_ID") @PrimaryKeyJoinColumn(name="DEP_ID") @PrimaryKeyJoinColumn(name="COM_ID") private Address address; ... }

Mapping a OneToOne Using a Join Table In some data models, you may have a OneToOne relationship defined through a join table. For example consider you had existing EMPLOYEE and ADDRESS tables with no foreign key, and wanted to define a OneToOne relationship without changing the existing tables. To do this you could define an intermediate table that contained the primary key of both objects. This is similar to a ManyToMany relationship, but if you add a unique constraint to each foreign key you can enforce that it is OneToOne (or even OneToMany). JPA defines a join table using the @JoinTable (https:/ / java. sun. com/ javaee/ 5/ docs/ api/ javax/ persistence/ JoinTable. html) annotation and <join-table> XML element. A JoinTable can be used on a ManyToMany or OneToMany mappings, but the JPA 1.0 specification is vague whether it can be used on a OneToOne. The JoinTable documentation does not state that it can be used in a OneToOne, but the XML schema for <one-to-one> does allow a nested <join-table> element. Some JPA providers may support this, and others may not. If your JPA provider does not support this, you can workaround the issue by instead defining a OneToMany or ManyToMany relationship and just define a get/set method that returns/sets the first element on the collection.

95


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.