Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

many to many - Hibernate: How to Join three 3 tables in one join table in Annotation?

Can you please help me how to join three tables with one common join table? I have USER, APPLICATION, and ROLE tables. And I want thier IDs to be joined in a table named USER_APP_ROLE(user.ID, application.ID, role.ID).

When I remove either Application or Role tables in Join Many to Many my code is working.

I have done the following codes:

User.java

@ManyToMany (targetEntity=Role.class)
@JoinTable(name="USER_APPLICATION_ROLE",
    joinColumns=@JoinColumn(name="USER_ID"),
    inverseJoinColumns=@JoinColumn(name="ROLE_ID"))

private Collection<Role> roles;

@ManyToMany (targetEntity=Application.class)
@JoinTable(name="USER_APPLICATION_ROLE",
    joinColumns=@JoinColumn(name="USER_ID"),
    inverseJoinColumns=@JoinColumn(name="APPLICATION_ID"))
private Collection<Application> applications;

Role.java

@ManyToMany(mappedBy="roles", targetEntity=User.class)
private Collection<User> users = new ArrayList<User>();

Application.java

@ManyToMany(mappedBy="applications", targetEntity=User.class)
private Collection<User> users = new ArrayList<User>();

When I tried to run the following test:

    user.getRoles().add(role1);
    user.getRoles().add(role2);

    role1.getUsers().add(user);
    role1.getUsers().add(user);

    role2.getUsers().add(user);
    role2.getUsers().add(user);

    user.getApplications().add(app1);
    user.getApplications().add(app2);

    app1.getUsers().add(user);
    app2.getUsers().add(user);
      ......

      session.beginTransaction();
      session.save(user);
      session.save(role1);
      session.save(role2);
      session.save(app1);
      session.save(app2);

I get the following error:

Hibernate: select seq_cm_user.nextval from dual
Hibernate: select seq_role.nextval from dual
Hibernate: select seq_role.nextval from dual
Hibernate: select seq_application.nextval from dual
Hibernate: select seq_application.nextval from dual
Hibernate: insert into CM_USER (EMAIL, FIRST_NAME, LAST_NAME, MIDDLE_NAME, USERNAME, ID) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into CM_ROLE (DESCRIPTION, ID) values (?, ?)
Hibernate: insert into CM_ROLE (DESCRIPTION, ID) values (?, ?)
Hibernate: insert into CM_APPLICATION (CODE, DESCRIPTION, ID) values (?, ?, ?)
Hibernate: insert into CM_APPLICATION (CODE, DESCRIPTION, ID) values (?, ?, ?)
Hibernate: insert into USER_APPLICATION_ROLE (USER_ID, APPLICATION_ID) values (?, ?)
Hibernate: insert into USER_APPLICATION_ROLE (USER_ID, APPLICATION_ID) values (?, ?)
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:114)
at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:109)
at org.hibernate.jdbc.AbstractBatcher.prepareBatchStatement(AbstractBatcher.java:244)
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1179)
at org.hibernate.action.CollectionRecreateAction.execute(CollectionRecreateAction.java:58)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:265)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:188)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at com.hp.gdas.capman.HibernateTest.main(HibernateTest.java:73)

Caused by: java.sql.BatchUpdateException: ORA-01400: cannot insert NULL into ("SYSTEM"."USER_APPLICATION_ROLE"."ROLE_ID")
at oracle.jdbc.driver.DatabaseError.throwBatchUpdateException(DatabaseError.java:343)
at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:10657)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
... 14 more

Thank you very much!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that you have defined a relationship to roles and a separate relationship to applications. There's no declaration that any specific user is a join of both one role and one application.

When you try to associate with a role, the application is null and visa-versa.

Here's an example of mapping a 3-way join between classes A, B and C using JPA. Note, no entity is required for the join table.

@Entity
public class A {

    @JoinTable(name = "a_b_c",
        joinColumns = @JoinColumn(name = "a_id"),
        inverseJoinColumns = @JoinColumn(name = "c_id"))
    @MapKeyJoinColumn(name = "b_id")
    @ElementCollection
    private Map<B, C> cByB = new HashMap<>();

}

@Entity
public class B {
    ...
}

@Entity
public class C {
    ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...