繁体   English   中英

休眠映射JPA集合

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM