Mapping many-to-many association table with extra column(s)

Posted by user635524 on Stack Overflow See other posts from Stack Overflow or by user635524
Published on 2011-02-26T13:20:10Z Indexed on 2012/09/16 3:38 UTC
Read the original article Hit count: 159

My database contains 3 tables: User and Service entities have many-to-many relationship and are joined with the SERVICE_USER table as follows:

USERS - SERVICE_USER - SERVICES

SERVICE_USER table contains additional BLOCKED column.

What is the best way to perform such a mapping? These are my Entity classes

@Entity
@Table(name = "USERS")
public class User implements java.io.Serializable {

private String userid;
private String email;

@Id
@Column(name = "USERID", unique = true, nullable = false,)
public String getUserid() {
return this.userid;
}

.... some get/set methods
}

@Entity
@Table(name = "SERVICES")
public class CmsService implements java.io.Serializable {
private String serviceCode;

@Id
@Column(name = "SERVICE_CODE", unique = true, nullable = false, length = 100)
public String getServiceCode() {
return this.serviceCode;
}
.... some additional fields and get/set methods
}

I followed this example http://giannigar.wordpress.com/2009/09/04/m ... using-jpa/ Here is some test code:

User user = new User();
user.setEmail("e2");
user.setUserid("ui2");
user.setPassword("p2");

CmsService service= new CmsService("cd2","name2");

List<UserService> userServiceList = new ArrayList<UserService>();

UserService userService = new UserService();
userService.setService(service);
userService.setUser(user);
userService.setBlocked(true);
service.getUserServices().add(userService);

userDAO.save(user);

The problem is that hibernate persists User object and UserService one. No success with the CmsService object

I tried to use EAGER fetch - no progress

Is it possible to achieve the behaviour I'm expecting with the mapping provided above?

Maybe there is some more elegant way of mapping many to many join table with additional column?

© Stack Overflow or respective owner

Related posts about hibernate

Related posts about jpa