Reputation: 30127
Suppose I have User
and Group
entities and wish them to have 1 to many relationship between. I.e. each User
belongs to one Group
, while any Group
can contain many User
s.
Group entity:
@Entity
@Table(name="GroupTable")
public class Group {
@Id
@Column(name="Id")
private long id;
@Column(name="Name")
private String name;
@OneToMany(mappedBy="group")
private Set<User> users;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
}
and User entity:
@Entity
@Table(name="User")
public class User {
@Id
@Column(name="Id")
private long id;
@ManyToOne
@JoinColumn(name="GroupId")
private Group group;
@Column(name="Name")
private String name;
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The following is application code:
public class App_Tester_Hibernate_01
{
private static Logger log = LoggerFactory.getLogger(App_Tester_Hibernate_01.class);
public static void main( String[] args )
{
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry;
SessionFactory sessionFactory;
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session;
session = sessionFactory.openSession();
session.beginTransaction();
Group group;
User user;
group = (Group) session.byId(Group.class).load(1l);
if( group == null ) {
group = new Group();
group.setId(1l);
group.setName("Group #1");
session.save(group);
}
log.info("Group.Users = {}", StringUtils.collectionToCommaDelimitedString(group.getUsers()));
user = (User) session.byId(User.class).load(1l);
if( user == null ) {
user = new User();
user.setId(1l);
user.setName("Bob");
user.setGroup(group);
session.save(user);
}
log.info("Group.Users = {}", StringUtils.collectionToCommaDelimitedString(group.getUsers()));
user = (User) session.byId(User.class).load(2l);
if( user == null ) {
user = new User();
user.setId(2l);
user.setName("Alice");
user.setGroup(group);
session.save(user);
}
log.info("Group.Users = {}", StringUtils.collectionToCommaDelimitedString(group.getUsers()));
user = (User) session.byId(User.class).load(3l);
if( user == null ) {
user = new User();
user.setId(3l);
user.setName("Peter");
user.setGroup(group);
session.save(user);
}
log.info("Group.Users = {}", StringUtils.collectionToCommaDelimitedString(group.getUsers()));
session.update(group);
log.info("Group.Users = {}", StringUtils.collectionToCommaDelimitedString(group.getUsers()));
session.getTransaction().commit();
session.close();
}
}
Unfortunaley, getUser()
always return null
. Why? Isn't it set as representation of related users? What I am doing wrong?
Should I do collection synchronization myself? Doesn't Hibernate fill the fields automatically?
UPDATE 1
My hibernate config follows:
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/tester_hibernate_01</property>
<property name="connection.username">root</property>
<property name="connection.password">sa</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">false</property>
<property name="hibernate.query.substitution">true 1, false 0, yes 'Y', no 'N'</property>
<property name="hbm2ddl.auto">create</property>
<mapping class="test.Tester_Hibernate_01.Group"/>
<mapping class="test.Tester_Hibernate_01.User"/>
</session-factory>
</hibernate-configuration>
adding of
@OneToMany(mappedBy="group", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<User> users;
didn't help.
UPDATE 2
Adding
Hibernate.initialize(group);
didn't help, getUsers()
still returns null.
Upvotes: 0
Views: 252
Reputation: 2288
interessting example: you are using 2 transactions the group-entity is detached at the time your are saving the users so it will not be updated (actually i'm curius if hibernate could figure this out if it was attached, i do not think so, if you try it let me know). what you may want to do is adding the users to the collection in the group-entity and then flush it so the ids will be assigned in the user-entity. What you need to add however is an appropriate cascade-annotation to the collection-field in the group entity (http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-hibspec-cascade) for this to work
Upvotes: 1