[英]Hibernate Mapping JPA Collections
我想做一件非常簡單的事情,但無法正常工作。
我有一個實體游戲和一個實體玩家。 每個游戲都應有玩家的兩個外鍵。 它有效,但是有一個陷阱:我無法將Player中的相同外鍵分配給多個Game-entities。 這個約束來自哪里,我怎么能告訴他不要這樣做呢?
我正在使用Hibernate和JPA。 我的persistence.xml看起來像這樣:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="PlayerService" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
<property name="hibernate.connection.username" value="********"/>
<property name="hibernate.connection.password" value="********"/>
<property name="hibernate.connection.url" value="jdbc:postgresql://********"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
</properties>
</persistence-unit>
</persistence>
我得到每個的entitymanager:
util = new JPAUtil();
emf = Persistence.createEntityManagerFactory("PlayerService");
em = emf.createEntityManager();
em.getTransaction().begin();
在我的游戲實體中:
@ElementCollection(targetClass=Player.class)
private Collection<Player> player;
並且有玩家實體。
我這樣做是完全錯誤的嗎?
@Entity
public class Game {
@Id
int gameid;
@OneToMany(mappedBy="game")
private Collection<TestPlayer> test;
}
@Entity
public class TestPlayer {
@Id
int id;
@ManyToOne
@JoinColumn(name="gameid")
private Game game;
}
我將嘗試使用OneToMany
關系而不是ElementCollection
。
我認為在ElementCollection
,元素( Player
)屬於Game
,因此Hibernate不允許您將其分配給多個Games
在您的游戲實體中:
@OneToMany(mappedBy="game")
private Collection<Player> player;
在您的Player實體中:
@ManyToOne
@JoinColumn(name="game_id")
private Game game;
供參考: http : //docs.jboss.org/hibernate/annotations/3.5/reference/en/html/entity.html#entity-mapping-association
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.