JPA 2.1 Specification (JSR-338 section 2.10.3.1 "Unidirectional OneToOne Relationshps") specifies:
"Table A conttains a foreign key to table B. The foreign key column name is formed as the concatenation of the following: the name of the realtionship property or field of entity A; "_"' the name of the primary key column in table B. The foreign key column has the same type as primary key of table B and there is a unique key constraint on it."
But Hibernate does not put unique constraint in such scenario.
First entity:
@Entity public class FootballPlayer {
@Id private long id;
@OneToOne private Ball ball;
public FootballPlayer() { }
public FootballPlayer(long id) { this.id = id; } public long getId() { return id; } public void setBall(Ball ball) { this.ball = ball; } public Ball getBall() { return ball; } } Second entity: @Entity public class Ball { @Id private long id; public Ball() { } public Ball(long id) { this.id = id; }
public long getId() { return id; }
}
Scenario:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("pu"); EntityManager em = emf.createEntityManager();
FootballPlayer firstPlayer = new FootballPlayer(1L); FootballPlayer secondPlayer = new FootballPlayer(2L); Ball ball = new Ball(10L);
firstPlayer.setBall(ball); secondPlayer.setBall(ball);
em.getTransaction().begin(); em.persist(ball); em.persist(firstPlayer); em.persist(secondPlayer); em.getTransaction().commit();
em.close(); emf.close();
persistence unit configuration from persitence.xml:
<persistence-unit name="pu"> <provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.mprzybylak.minefields.jpa.relationships.onetoone.uni.Ball</class> <class>com.mprzybylak.minefields.jpa.relationships.onetoone.uni.FootballPlayer</class>
<properties> <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" /> <property name="javax.persistence.jdbc.url" value="jdbc:derby:memory:test;create=true" /> <property name="javax.persistence.jdbc.user" value="APP" /> <property name="javax.persistence.jdbc.password" value="APP" />
<property name="hibernate.show_sql" value="true" /> <property name="hibernate.use_sql_comments" value="true"/> <property name="hibernate.hbm2ddl.auto" value="create" /> </properties> </persistence-unit>
|