I want to do a pretty simple thing but can't get it to work.
I have ab entity Game and an Entity Player. Every Game should have two foreign keys from Players. And it works, but there is one catch: I cant assign the same foreign key from Player to multiple Game-entities. Where is this constraint coming from, and how can I tell him to not do that?
I'm using Hibernate and JPA. My persistence.xml looks like this:
<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>
I'm getting the entitymanager per:
util = new JPAUtil();
emf = Persistence.createEntityManagerFactory("PlayerService");
em = emf.createEntityManager();
em.getTransaction().begin();
in my Games-Entity:
@ElementCollection(targetClass=Player.class)
private Collection<Player> player;
and there is Player-Entity.
Am I doing this entirely wrong?
@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;
}
I'll try an OneToMany
relationship instead of ElementCollection
.
I think that in an ElementCollection
the elements ( Player
) belongs to the Game
and therefore Hibernate doesn't let you assign it to multiple Games
in your Game Entity:
@OneToMany(mappedBy="game")
private Collection<Player> player;
in your Player entity:
@ManyToOne
@JoinColumn(name="game_id")
private Game game;
for reference: http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html/entity.html#entity-mapping-association
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.