Domanda

I'm working on website where user can subscribe to Organisation. when I'm going to implement Subscribe function and I face the following problem.

In sort I want to create model class of ManyToMany join table for retrieve rows from table to check which Organisations are subscribe by user. And In Hibernate I can't create Table without primary key.but in join table one user can subscribe to many organisation and one organisation has many subscriber so primary key are repeat and I got exception ERROR: Duplicate entry '1' for key 'PRIMARY'.

hibernate.cfg.xml contain

<mapping class="model.User"/>
<mapping class="model.Post"/>
<mapping class="model.UserSubscribes"/>

User.java

package model;
    
@Entity
@Table(name="user",
        uniqueConstraints = {@UniqueConstraint(columnNames={"email"})}
        )
@org.hibernate.annotations.Entity(dynamicUpdate=true,selectBeforeUpdate=true)

public class User implements Serializable {
    
    @Id 
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long userId;//1
    private String email;//1
    private String password;//
    
    public User(long userId, String email, String password){
        this.userId = userId;
        this.email = email;
        this.password = password;
    }
    
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(
            name="UserSubscribes",
            joinColumns={ @JoinColumn(name="userId",referencedColumnName="userId") },
            inverseJoinColumns={ @JoinColumn(name="orgId", referencedColumnName="orgId") }
    )
    private Collection<Organisation> orgSubscribes = new ArrayList<Organisation>();
    

    //Getter & Setter
    
}

Organisation.java

package model;

@Entity
@Table(name="org",
        uniqueConstraints = {@UniqueConstraint(columnNames={"email"})}
        )
@org.hibernate.annotations.Entity(dynamicUpdate=true,selectBeforeUpdate=true)

public class Organisation implements Serializable {

    @Id 
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long orgId;
    private String email;
    private String password;
    
    public Organisation(long orgId, String email, String password){
        this.orgId = orgId;
        this.email = email;
        this.password = password;
    }
    
    //Getter & Setter
}

UserSubscribes.java

package model;

@Entity
@Table(name="UserSubscribes")
public class UserSubscribes implements Serializable {
    
    @Id 
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long userId;
    private long orgId;
    
    //Getter & Setter
}

Subscribe.java

package view.action;

public class Subscribe extends ActionSupport {

    public String execute(){
        
        Session session = HibernateUtill.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        
        System.out.println("Subscribbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
        
        User u1 = new User(1, "ppp", "ppp");
        User u2 = new User(2, "qqq", "qqq");
        Organisation o1 = new Organisation(1, "ppp", "ppp");
        Organisation o2 = new Organisation(2, "qqq", "qqq");
        Organisation o3 = new Organisation(3, "www", "www");
        Organisation o4 = new Organisation(4, "eee", "eee");
        
        session.save(o1);
        session.save(o2);
        session.save(o3);
        session.save(o4);
        session.save(u1);
        session.save(u2);
        
        u1.getOrgSubscribes().add(o1);
        u1.getOrgSubscribes().add(o2);
        u1.getOrgSubscribes().add(o3);
        
        session.saveOrUpdate(u1);
        
        session.getTransaction().commit();
        
        return SUCCESS;
    }
}

and I got this output and error

Subscribbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into user (email, password) values (?, ?)
Hibernate: insert into user (email, password) values (?, ?)
Hibernate: insert into UserSubscribes (userId, orgId) values (?, ?)
Hibernate: insert into UserSubscribes (userId, orgId) values (?, ?)
Apr 27, 2014 4:43:52 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1062, SQLState: 23000
Apr 27, 2014 4:43:52 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Duplicate entry '1' for key 'PRIMARY'

If I remove <mapping class="model.UserSubscribes"/> from hibernate.cfg.xml mapping then it works perfect as following output.

Subscribbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into user (email, password) values (?, ?)
Hibernate: insert into user (email, password) values (?, ?)
Hibernate: insert into UserSubscribes (userId, orgId) values (?, ?)
Hibernate: insert into UserSubscribes (userId, orgId) values (?, ?)
Hibernate: insert into UserSubscribes (userId, orgId) values (?, ?)

and output is

enter image description here

but I can't retrieve rows(using HQL) from it without map this table in hibernate.cfg.xml file.
If any possible solution for this problem I'm really thankful to you. Thank you in advance.

È stato utile?

Soluzione

The join table should not be mapped as an entity. You simply need User, Organization, and a ManyToMany association between those 2 entities.

In sort I want to create model class of ManyToMany join table for retrieve rows from table to check which Organisations are subscribe by user

That can be done with the association:

User user = em.find(User.class, userId);
Set<Organization> organizations = user.getOrganizations();

or with a simple JPQL query:

select o from User u inner join u.organizations o where u.id = :userId

Altri suggerimenti

Thanks JB Nizet

I implement code as you suggest and it works perfect. Here is Solved Code.

GetSubscriber.java

package view.action;

public class GetSubscriber extends ActionSupport {

    public String execute(){

        Session session = HibernateUtill.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        User u = (User) session.get(User.class, (long)1);
        List<Organisation> s = (List<Organisation>) u.getOrgSubscribes();

        for(int i=0;i<s.size();i++){
            System.out.println(s.get(i).getOrgId() + "  " + s.get(i).getEmail());
        }

        return SUCCESS;
    }
}

Output:

1  ppp
2  qqq
3  www
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top