Thanks, I have made as you have told, but is similar, that nothing has changed.
I just need a many-to-many relationship between two entities with additional columns in the association table.
Can you help me please
Here all my code with exception.
thx.
Code:
@Table(name = "ROLE")
@Entity
public class Role implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "NAME")
private String name;
@OneToMany(mappedBy = "role")
private Set<UserRole> userRoles = new HashSet<UserRole>();;
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<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
public Role() {
super();
// TODO Auto-generated constructor stub
}
public Role(String name, Set<UserRole> userRoles) {
super();
this.name = name;
this.userRoles = userRoles;
}
}
Code:
@Entity
@Table(name = "USER")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "USERNAME")
private String username;
@Column(name = "PASSWORD")
private String password;
@OneToMany(mappedBy = "user")
private Set<UserRole> userRoles1 = new HashSet<UserRole>();
public User(String username, String password, Set<UserRole> userRoles) {
super();
this.username = username;
this.password = password;
this.userRoles1 = userRoles;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Set<UserRole> getUserRoles1() {
return userRoles1;
}
public void setUserRoles1(Set<UserRole> userRoles) {
this.userRoles1 = userRoles;
}
}
Code:
@Entity
@Table(name = "USER_ROLE")
@IdClass(UserRolePK.class)
public class UserRole {
@Id
@Column(name = "USER_ID", insertable = false, updatable = false)
private Long userId;
@Id
@Column(name = "ROLE_ID", insertable = false, updatable = false)
private Long roleId;
@ManyToOne(cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn(name = "USER_ID", referencedColumnName = "ID")
private User user;
@ManyToOne(cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn(name = "ROLE_ID", referencedColumnName = "ID")
private Role role;
@Column(name = "ENABLED")
private boolean enabled;
public UserRole() {
super();
// TODO Auto-generated constructor stub
}
public UserRole(User user, Role role, boolean enabled) {
super();
this.user = user;
this.role = role;
this.enabled = enabled;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public Long getRoleId() {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
}
Code:
public class UserRolePK implements Serializable {
private Long userId;
private Long roleId;
}
Code:
emf = Persistence.createEntityManagerFactory("hacon_w");
entityManager = emf.createEntityManager();
tx2 = entityManager.getTransaction();
User u = new User();
u.setUsername("a");
u.setPassword("a");
Role r = new Role();
r.setName("b");
UserRole ur = new UserRole(u,r,true);
tx2.begin();
entityManager.persist(ur);
tx2.commit();
entityManager.close();
System.out.println("Done.");
Code:
18:58:54,672 DEBUG SessionImpl:220 - opened session at timestamp: 11805443346
18:58:54,673 DEBUG JDBCTransaction:54 - begin
18:58:54,673 DEBUG ConnectionManager:419 - opening JDBC connection
18:58:54,673 DEBUG DriverManagerConnectionProvider:93 - total checked-out connections: 0
18:58:54,674 DEBUG DriverManagerConnectionProvider:99 - using pooled JDBC connection, pool size: 0
18:58:54,674 DEBUG JDBCTransaction:59 - current autocommit status: true
18:58:54,674 DEBUG JDBCTransaction:62 - disabling autocommit
18:58:54,674 DEBUG JDBCContext:210 - after transaction begin
18:58:54,676 DEBUG IdentifierValue:77 - id unsaved-value strategy UNDEFINED
18:58:54,676 DEBUG AbstractSaveEventListener:514 - transient instance of: de.hacon.warehouse.UserRole
18:58:54,676 DEBUG DefaultPersistEventListener:124 - saving transient instance
18:58:54,677 DEBUG AbstractSaveEventListener:112 - generated identifier: component[userId,roleId]{userId=null, roleId=null}, using strategy: org.hibernate.id.Assigned
18:58:54,678 DEBUG AbstractSaveEventListener:153 - saving [de.hacon.warehouse.UserRole#component[userId,roleId]{userId=null, roleId=null}]
18:58:54,681 DEBUG Cascade:115 - processing cascade ACTION_PERSIST for: de.hacon.warehouse.UserRole
18:58:54,681 DEBUG CascadingAction:293 - cascading to persist: de.hacon.warehouse.User
18:58:54,681 DEBUG AbstractSaveEventListener:514 - transient instance of: de.hacon.warehouse.User
18:58:54,682 DEBUG DefaultPersistEventListener:124 - saving transient instance
18:58:54,682 DEBUG AbstractSaveEventListener:153 - saving [de.hacon.warehouse.User#<null>]
18:58:54,682 DEBUG AbstractSaveEventListener:244 - executing insertions
18:58:54,689 DEBUG WrapVisitor:87 - Wrapped collection in role: de.hacon.warehouse.User.userRoles1
18:58:54,692 DEBUG AbstractSaveEventListener:297 - executing identity-insert immediately
18:58:54,693 DEBUG AbstractEntityPersister:2140 - Inserting entity: de.hacon.warehouse.User (native id)
18:58:54,694 DEBUG AbstractBatcher:358 - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
18:58:54,694 DEBUG SQL:393 - insert into USER (USERNAME, PASSWORD) values (?, ?)
Hibernate: insert into USER (USERNAME, PASSWORD) values (?, ?)
18:58:54,694 DEBUG AbstractBatcher:476 - preparing statement
18:58:54,706 DEBUG AbstractEntityPersister:1988 - Dehydrating entity: [de.hacon.warehouse.User#<null>]
18:58:54,707 DEBUG IdentifierGeneratorFactory:37 - Natively generated identity: 1
18:58:54,707 DEBUG AbstractBatcher:366 - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
18:58:54,707 DEBUG AbstractBatcher:525 - closing statement
18:58:54,709 DEBUG CascadingAction:293 - cascading to persist: de.hacon.warehouse.Role
18:58:54,709 DEBUG AbstractSaveEventListener:514 - transient instance of: de.hacon.warehouse.Role
18:58:54,709 DEBUG DefaultPersistEventListener:124 - saving transient instance
18:58:54,709 DEBUG AbstractSaveEventListener:153 - saving [de.hacon.warehouse.Role#<null>]
18:58:54,709 DEBUG AbstractSaveEventListener:244 - executing insertions
18:58:54,710 DEBUG WrapVisitor:87 - Wrapped collection in role: de.hacon.warehouse.Role.userRoles
18:58:54,710 DEBUG AbstractSaveEventListener:297 - executing identity-insert immediately
18:58:54,710 DEBUG AbstractEntityPersister:2140 - Inserting entity: de.hacon.warehouse.Role (native id)
18:58:54,710 DEBUG AbstractBatcher:358 - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
18:58:54,711 DEBUG SQL:393 - insert into ROLE (NAME) values (?)
Hibernate: insert into ROLE (NAME) values (?)
18:58:54,711 DEBUG AbstractBatcher:476 - preparing statement
18:58:54,712 DEBUG AbstractEntityPersister:1988 - Dehydrating entity: [de.hacon.warehouse.Role#<null>]
18:58:54,712 DEBUG IdentifierGeneratorFactory:37 - Natively generated identity: 1
18:58:54,712 DEBUG AbstractBatcher:366 - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
18:58:54,713 DEBUG AbstractBatcher:525 - closing statement
18:58:54,713 DEBUG Cascade:150 - done processing cascade ACTION_PERSIST for: de.hacon.warehouse.UserRole
18:58:54,715 DEBUG Cascade:115 - processing cascade ACTION_PERSIST for: de.hacon.warehouse.UserRole
18:58:54,715 DEBUG Cascade:150 - done processing cascade ACTION_PERSIST for: de.hacon.warehouse.UserRole
18:58:54,715 DEBUG JDBCTransaction:103 - commit
18:58:54,715 DEBUG SessionImpl:337 - automatically flushing session
18:58:54,716 DEBUG AbstractFlushingEventListener:58 - flushing session
18:58:54,716 DEBUG AbstractFlushingEventListener:111 - processing flush-time cascades
18:58:54,716 DEBUG Cascade:115 - processing cascade ACTION_PERSIST_ON_FLUSH for: de.hacon.warehouse.User
18:58:54,717 DEBUG Cascade:150 - done processing cascade ACTION_PERSIST_ON_FLUSH for: de.hacon.warehouse.User
18:58:54,717 DEBUG Cascade:115 - processing cascade ACTION_PERSIST_ON_FLUSH for: de.hacon.warehouse.Role
18:58:54,717 DEBUG Cascade:150 - done processing cascade ACTION_PERSIST_ON_FLUSH for: de.hacon.warehouse.Role
18:58:54,717 DEBUG Cascade:115 - processing cascade ACTION_PERSIST_ON_FLUSH for: de.hacon.warehouse.UserRole
18:58:54,718 DEBUG CascadingAction:321 - cascading to persistOnFlush: de.hacon.warehouse.User
18:58:54,718 DEBUG AbstractSaveEventListener:488 - persistent instance of: de.hacon.warehouse.User
18:58:54,718 DEBUG DefaultPersistEventListener:100 - ignoring persistent instance
18:58:54,718 DEBUG Cascade:115 - processing cascade ACTION_PERSIST_ON_FLUSH for: de.hacon.warehouse.User
18:58:54,718 DEBUG Cascade:150 - done processing cascade ACTION_PERSIST_ON_FLUSH for: de.hacon.warehouse.User
18:58:54,718 DEBUG Cascade:115 - processing cascade ACTION_PERSIST_ON_FLUSH for: de.hacon.warehouse.User
18:58:54,718 DEBUG Cascade:150 - done processing cascade ACTION_PERSIST_ON_FLUSH for: de.hacon.warehouse.User
18:58:54,718 DEBUG CascadingAction:321 - cascading to persistOnFlush: de.hacon.warehouse.Role
18:58:54,718 DEBUG AbstractSaveEventListener:488 - persistent instance of: de.hacon.warehouse.Role
18:58:54,719 DEBUG DefaultPersistEventListener:100 - ignoring persistent instance
18:58:54,719 DEBUG Cascade:115 - processing cascade ACTION_PERSIST_ON_FLUSH for: de.hacon.warehouse.Role
18:58:54,719 DEBUG Cascade:150 - done processing cascade ACTION_PERSIST_ON_FLUSH for: de.hacon.warehouse.Role
18:58:54,719 DEBUG Cascade:115 - processing cascade ACTION_PERSIST_ON_FLUSH for: de.hacon.warehouse.Role
18:58:54,719 DEBUG Cascade:150 - done processing cascade ACTION_PERSIST_ON_FLUSH for: de.hacon.warehouse.Role
18:58:54,719 DEBUG Cascade:150 - done processing cascade ACTION_PERSIST_ON_FLUSH for: de.hacon.warehouse.UserRole
18:58:54,719 DEBUG AbstractFlushingEventListener:154 - dirty checking collections
18:58:54,719 DEBUG AbstractFlushingEventListener:171 - Flushing entities and processing referenced collections
18:58:54,724 DEBUG Collections:176 - Collection found: [de.hacon.warehouse.User.userRoles1#1], was: [<unreferenced>] (initialized)
18:58:54,725 DEBUG Collections:176 - Collection found: [de.hacon.warehouse.Role.userRoles#1], was: [<unreferenced>] (initialized)
18:58:54,725 DEBUG AbstractFlushingEventListener:210 - Processing unreferenced collections
18:58:54,725 DEBUG AbstractFlushingEventListener:224 - Scheduling collection removes/(re)creates/updates
18:58:54,728 DEBUG AbstractFlushingEventListener:85 - Flushed: 1 insertions, 0 updates, 0 deletions to 3 objects
18:58:54,728 DEBUG AbstractFlushingEventListener:91 - Flushed: 2 (re)creations, 0 updates, 0 removals to 2 collections
18:58:54,729 DEBUG Printer:83 - listing entities:
18:58:54,729 DEBUG Printer:90 - de.hacon.warehouse.Role{id=1, userRoles=[], name=b}
18:58:54,729 DEBUG Printer:90 - de.hacon.warehouse.User{id=1, userRoles1=[], username=a, password=a}
18:58:54,730 DEBUG Printer:90 - de.hacon.warehouse.UserRole{enabled=true, role=de.hacon.warehouse.Role#1, user=de.hacon.warehouse.User#1}
18:58:54,730 DEBUG AbstractFlushingEventListener:290 - executing flush
18:58:54,730 DEBUG ConnectionManager:467 - registering flush begin
18:58:54,730 DEBUG AbstractEntityPersister:2200 - Inserting entity: [de.hacon.warehouse.UserRole#component[userId,roleId]{userId=null, roleId=null}]
18:58:54,732 DEBUG AbstractBatcher:358 - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
18:58:54,732 DEBUG SQL:393 - insert into USER_ROLE (user_id, role_id, ENABLED, userId, roleId) values (?, ?, ?, ?, ?)
Hibernate: insert into USER_ROLE (user_id, role_id, ENABLED, userId, roleId) values (?, ?, ?, ?, ?)
18:58:54,733 DEBUG AbstractBatcher:476 - preparing statement
18:58:54,734 DEBUG AbstractEntityPersister:1988 - Dehydrating entity: [de.hacon.warehouse.UserRole#component[userId,roleId]{userId=null, roleId=null}]
18:58:54,734 DEBUG AbstractBatcher:44 - Executing batch size: 1
18:58:54,735 DEBUG AbstractBatcher:366 - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
18:58:54,735 DEBUG AbstractBatcher:525 - closing statement
18:58:54,737 DEBUG JDBCExceptionReporter:69 - Could not execute JDBC batch update [insert into USER_ROLE (user_id, role_id, ENABLED, userId, roleId) values (?, ?, ?, ?, ?)]
java.sql.BatchUpdateException: Column 'userId' cannot be null
at com.mysql.jdbc.ServerPreparedStatement.executeBatch(ServerPreparedStatement.java:665)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:139)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:54)
at Main.start(Main.java:37)
at Main.<init>(Main.java:23)
at Main.main(Main.java:47)
18:58:54,739 WARN JDBCExceptionReporter:77 - SQL Error: 1048, SQLState: 23000
18:58:54,740 ERROR JDBCExceptionReporter:78 - Column 'userId' cannot be null
18:58:54,740 ERROR AbstractFlushingEventListener:301 - Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:249)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:139)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:54)
at Main.start(Main.java:37)
at Main.<init>(Main.java:23)
at Main.main(Main.java:47)
Caused by: java.sql.BatchUpdateException: Column 'userId' cannot be null
at com.mysql.jdbc.ServerPreparedStatement.executeBatch(ServerPreparedStatement.java:665)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)
... 11 more
18:58:54,741 DEBUG ConnectionManager:476 - registering flush end
18:58:54,741 DEBUG JDBCTransaction:152 - rollback
18:58:54,742 DEBUG JDBCTransaction:193 - re-enabling autocommit
18:58:54,743 DEBUG JDBCTransaction:163 - rolled back JDBC Connection
18:58:54,743 DEBUG JDBCContext:215 - after transaction completion
18:58:54,743 DEBUG ConnectionManager:402 - aggressively releasing JDBC connection
18:58:54,743 DEBUG ConnectionManager:439 - releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]
18:58:54,743 DEBUG DriverManagerConnectionProvider:129 - returning connection to pool, pool size: 1
18:58:54,743 DEBUG SessionImpl:422 - after transaction completion
Exception in thread "main" javax.persistence.RollbackException: Error while commiting the transaction
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:71)
at Main.start(Main.java:37)
at Main.<init>(Main.java:23)
at Main.main(Main.java:47)
Caused by: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:249)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:139)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:54)
... 3 more
Caused by: java.sql.BatchUpdateException: Column 'userId' cannot be null
at com.mysql.jdbc.ServerPreparedStatement.executeBatch(ServerPreparedStatement.java:665)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)
... 11 more