-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 posts ] 
Author Message
 Post subject: ManyToMany, problem by saving?
PostPosted: Wed May 30, 2007 7:18 am 
Newbie

Joined: Wed May 30, 2007 6:47 am
Posts: 5
I have problem by saving the Objects.
what make I wrong?
thx.


Hibernate version: 3.3

Mapping documents:
Code:
@Entity
@Table(name="USER")
public class User {

  @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> userRoles;

}

@Table(name="ROLE")
@Entity
public class Role {

  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  private Long id;

  @Column(name="NAME")
  private String name;

  @OneToMany(mappedBy="role")
  private Set<UserRole> userRoles;
}

@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
  @JoinColumn(name="USER_ID")
  private User user;

  @ManyToOne
  @JoinColumn(name="ROLE_ID")
  private Role role;

  @Column(name="ENABLED")
  private boolean enabled;
}

public class UserRolePK {

  private Long userId;
  private Long roleId;
}


Code between sessionFactory.openSession() and session.close():
Code:
emf2 = Persistence.createEntityManagerFactory("hacon_w");
        entityManager = (Session) emf2.createEntityManager().getDelegate();
        tx2 = entityManager.getTransaction();
        tx2.begin();
       
        User u = new User();
        u.setUsername("a");
        u.setPassword("a");
       
        Role r = new Role();
        r.setName("b");
       
        UserRole ur = new UserRole(u,r,true);
       
        entityManager.save(u);
        entityManager.save(r);       
        entityManager.save(ur);
       
        tx2.commit();
        entityManager.close();


Full stack trace of any exception that occurs:
    17:45:03,388 DEBUG AbstractFlushingEventListener:154 - dirty checking collections
    17:45:03,388 DEBUG AbstractFlushingEventListener:171 - Flushing entities and processing referenced collections
    17:45:03,390 DEBUG AbstractFlushingEventListener:210 - Processing unreferenced collections
    17:45:03,390 DEBUG AbstractFlushingEventListener:224 - Scheduling collection removes/(re)creates/updates
    17:45:03,390 DEBUG AbstractFlushingEventListener:85 - Flushed: 1 insertions, 0 updates, 0 deletions to 3 objects
    17:45:03,390 DEBUG AbstractFlushingEventListener:91 - Flushed: 0 (re)creations, 0 updates, 0 removals to 0 collections
    17:45:03,391 DEBUG Printer:83 - listing entities:
    17:45:03,391 DEBUG Printer:90 - de.hacon.warehouse.Role{id=1, userRoles=null, name=b}
    17:45:03,391 DEBUG Printer:90 - de.hacon.warehouse.User{id=1, username=a, userRoles=null, password=a}
    17:45:03,391 DEBUG Printer:90 - de.hacon.warehouse.UserRole{enabled=true, role=de.hacon.warehouse.Role#1, user=de.hacon.warehouse.User#1}
    17:45:03,391 DEBUG AbstractFlushingEventListener:290 - executing flush
    17:45:03,392 DEBUG ConnectionManager:467 - registering flush begin
    17:45:03,392 DEBUG AbstractEntityPersister:2200 - Inserting entity: [de.hacon.warehouse.UserRole#component[userId,roleId]{userId=null, roleId=null}]
    17:45:03,395 DEBUG AbstractBatcher:358 - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
    17:45:03,395 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 (?, ?, ?, ?, ?)
    17:45:03,395 DEBUG AbstractBatcher:476 - preparing statement
    17:45:03,396 DEBUG AbstractEntityPersister:1988 - Dehydrating entity: [de.hacon.warehouse.UserRole#component[userId,roleId]{userId=null, roleId=null}]
    17:45:03,397 DEBUG AbstractBatcher:44 - Executing batch size: 1
    17:45:03,398 DEBUG AbstractBatcher:366 - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
    17:45:03,398 DEBUG AbstractBatcher:525 - closing statement
    17:45:03,399 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 de.hacon.contoller.Controller.proba(Controller.java:584)
    at de.hacon.main.ParserStart.main(ParserStart.java:23)
    17:45:03,400 WARN JDBCExceptionReporter:77 - SQL Error: 1048, SQLState: 23000
    17:45:03,400 ERROR JDBCExceptionReporter:78 - Column 'userId' cannot be null
    17:45:03,400 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 de.hacon.contoller.Controller.proba(Controller.java:584)
    at de.hacon.main.ParserStart.main(ParserStart.java:23)
    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)
    ... 9 more
    Exception in thread "main" 17:45:03,402 DEBUG ConnectionManager:476 - registering flush end
    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 de.hacon.contoller.Controller.proba(Controller.java:584)
    at de.hacon.main.ParserStart.main(ParserStart.java:23)
    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)
    ... 9 more

Name and version of the database you are using:
MySQL 5

The generated SQL (show_sql=true):[list=]
CREATE TABLE USER (
ID BIGINT AUTO_INCREMENT NOT NULL,
USERNAME VARCHAR(255),
PASSWORD VARCHAR(255), PRIMARY KEY (ID))

CREATE TABLE ROLE (
ID BIGINT AUTO_INCREMENT NOT NULL,
NAME VARCHAR(255),
PRIMARY KEY (ID))

CREATE TABLE USER_ROLE (
USER_ID BIGINT NOT NULL,
ROLE_ID BIGINT NOT NULL,
PRIMARY KEY (USER_ID, ROLE_ID),
ENABLED TINYINT(1) default 0)

ALTER TABLE USER_ROLE ADD CONSTRAINT
FK_USER_ROLE_USER_ID FOREIGN KEY (USER_ID)
REFERENCES USER (ID)
ALTER TABLE USER_ROLE ADD CONSTRAINT
FK_USER_ROLE_ROLE_ID
FOREIGN KEY (ROLE_ID) REFERENCES ROLE (ID)[/list]


Top
 Profile  
 
 Post subject: Try replacing @JoinColumn with @PrimaryKeyJoinColumn
PostPosted: Wed May 30, 2007 11:12 am 
Newbie

Joined: Tue May 29, 2007 12:33 am
Posts: 13
Hi,

The problem is that you are specifying in UserRole @Id properties with a default GenerationType (AUTO) and not insertable/updatable (probably because you want those values set with the primary key of User (for userId property) and Role (for roleId property).

Here's what the spec (JSR-220) says about @PrimaryKeyJoinColumn:

Quote:
"The PrimaryKeyJoinColumn annotation specifies a primary key column that is used as a foreign
key to join to another table.
"


From what I see, this is your situation. Although it says that this annotation is used when joining sublass with superclass, secondary with primary tables and one-to-one relationships, it's worth a shot trying it with your many-to-one relationships.

Just replace @JoinColumn annotations with @PrimaryKeyJoinColumn annotations in UserRole class:

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
  @PrimaryKeyJoinColumn(name="USER_ID", referencedColumnName="ID")
  private User user;

  @ManyToOne
  @PrimaryKeyJoinColumn(name="ROLE_ID", referencedColumnName="ID")
  private Role role;

  @Column(name="ENABLED")
  private boolean enabled;
}


Top
 Profile  
 
 Post subject:
PostPosted: Wed May 30, 2007 11:44 am 
Newbie

Joined: Tue May 29, 2007 12:33 am
Posts: 13
One last comment, forget about the GenerationType (AUTO) in my last post, I thought I saw it somewhere in your code. The rest is OK, let me know if it helped!


Top
 Profile  
 
 Post subject:
PostPosted: Wed May 30, 2007 1:05 pm 
Newbie

Joined: Wed May 30, 2007 6:47 am
Posts: 5
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


Top
 Profile  
 
 Post subject:
PostPosted: Wed May 30, 2007 1:13 pm 
Newbie

Joined: Wed May 30, 2007 6:47 am
Posts: 5
ups twice :)


Top
 Profile  
 
 Post subject:
PostPosted: Wed May 30, 2007 10:54 pm 
Newbie

Joined: Tue May 29, 2007 12:33 am
Posts: 13
Hi again,

Yep, bad stuff... I had a similar problem, and after a looooot of tries, the only workaround I found was to break up the composite primary key of the join table; I had to define a new @Id, and then you would treat your @ManyToOne relationships like you normally do, annotating the field also with @JoinColumn and using the name attribute of the annotation to specify the foreign key.

The key factor is NOT that a field is being inserted as null. If you closely look at your logging statements, you will see the following:

Code:
DEBUG org.hibernate.persister.entity.AbstractEntityPersister - Static SQL for entity: unkis.UserRole
DEBUG org.hibernate.persister.entity.AbstractEntityPersister -  Insert 0: insert into USER_ROLE (role_id, user_id, ENABLED, roleId, userId) values (?, ?, ?, ?, ?)
...
insert into USER_ROLE (user_id, role_id, ENABLED, userId, roleId) values (?, ?, ?, ?, ?)


As you can see, when Hibernate generates the static sql for your USER_ROLE class, hibernate is trying to insert values for 5 FIELDS, not 3 (which would be the correct). This may be happening because you have a composite key for which every column is a foreign key to a primary key of a different table.

The example in the spec shows the use of @IdClass and @PrimaryKeyJoinColumn when the composite Id maps to a composite primary key of another table.

Let me know if you did manage to find a different solution, 'cause probably I could also use it!!

Regards


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.