2009-08-21 13 views
14

Si consideri il seguente schema di database:Hibernate @OneToMany senza una tabella separata unirsi

create table UserGroup (id int not null auto_increment, name varchar(200), 
    primary key(id)); 
create table User (id int not null auto_increment, name varchar(200), 
    groupId int not null, primary key(id)); 

User.groupId = UserGroup.id, in modo che un utente può essere solo un membro di un gruppo, ma ad un gruppo, può esistere di molti utenti. Bene fino ad ora, facciamo le entità in Hibernate. Ecco User:

@Entity 
@Table(name = "User") 
public class User { 

    @Id 
    @Column(name="id", nullable = false) 
    private Integer id; 

    @Column(name="name", length = 200, nullable = true) 
    private String name; 

    @ManyToOne(fetch=FetchType.EAGER) 
    @JoinColumn(name = "groupId", nullable = false, insertable=false, updatable=false) 
    @ForeignKey(name="FK_GroupId") 
    private UserGroup userGroup; 

    /* Getters, Setters, toString, equals & hashCode */ 
} 

Ecco UserGroup:

@Entity 
@Table(name = "UserGroup") 
public class UserGroup { 

    @Id 
    @Column(name="id", nullable = false) 
    private Integer id; 

    @Column(name="name", length = 200, nullable = true) 
    private String name; 

    @OneToMany(fetch=FetchType.EAGER) 
    private List<User> users; 

    /* Getters, Setters, toString, equals & hashCode */ 
} 

Ora vado a prendere un errore "Table mydb.usergroup_user' doesn't exist" perché si aspetta una join-tavolo. La mia struttura dati è "impostata su pietra" a causa dell'interoperabilità con altre applicazioni che questa applicazione sostituirà, quindi non farò un tavolo da join. Inoltre, non dovrebbe essere necessario. Come posso creare un List<User> users che sia semplicemente un elenco di Utente dove User.groupId == UserGroup.Id?

risposta

16

Penso che sia necessario il mappedBy="UserGroup" nell'annotazione @OneToMany.

+0

Splendido, questo ha fatto il trucco! :-) Grazie mille! – niklassaers

+0

Nel mio caso, ho aggiunto il mappedBy, ma non funziona ancora. C'è qualcos'altro che devo fare? – Chris

+0

Prova ad aggiungere un '@JoinColumn (name =" ")'. – h4k1m

Problemi correlati