views:

780

answers:

2

Consider the following database schema:

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, so a user can only be a member of one group, but a usergroup can exist of many users. Fine so far, let's make the entities in Hibernate:

/** User **/
package com.saers.data.entities;

import java.io.Serializable;
import javax.persistence.*;
import org.hibernate.annotations.ForeignKey;

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

    private static final long serialVersionUID = 2209767646758652729L;

    @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 */
}

/** UserGroup **/
package com.saers.data.entities;

import java.io.Serializable;
import javax.persistence.*;

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

    private static final long serialVersionUID = 3197951599324630855L;

    @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 */
}

Now I'll get an error "Table mydb.usergroup_user' doesn't exist" because it expects a join-table. My data structure is "set in stone" due to interoperability with other applications that this application will replace, so I won't be making a join-table. Also, it should not be needed. How can I make a List users that simply is a list of User where User.groupId == UserGroup.Id ?

Cheers

Nik

+3  A: 

I think you need the mappedBy="userGroup" in the @OneToMany annotation.

Brian Yarger
Splendid, that did the trick! :-) Thank you very much!
niklassaers
A: 

But what if I don't want bidirectional relation, and I don't have field to map ? Application works fine, but error is shown in eclipse only.

peperg