Hibernate映射JPA集合

时间:2014-02-23 17:06:56

标签: java entity-framework hibernate jpa

我想做一件非常简单的事,但无法让它发挥作用。

我有ab实体游戏和实体玩家。每个游戏都应该有两个来自玩家的外键。它有效,但有一个问题:我无法从播放器向多个游戏实体分配相同的外键。这种约束来自何处,我怎么能告诉他不这样做呢?

我正在使用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>

我正在获得实体经理:

util = new JPAUtil();
emf = Persistence.createEntityManagerFactory("PlayerService");
em = emf.createEntityManager();
em.getTransaction().begin();

在我的游戏实体中:

@ElementCollection(targetClass=Player.class)
private Collection<Player> player;

并且有Player-Entity。

我这样做完全错了吗?


@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;
}

1 个答案:

答案 0 :(得分:0)

我会尝试OneToMany关系,而不是ElementCollection

我认为在ElementCollection中,元素(Player)属于Game,因此Hibernate不允许您将其分配给多个Games

在您的游戏实体中:

@OneToMany(mappedBy="game")
private Collection<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