简体   繁体   中英

Querying composite table in Hibernate

I am working on a Spring-MVC application where I have a many-to-many relationship in which I have to query in 2 tables to get the values I require. I will explain in more detail.

  • I have 2 tables GroupAccount, GroupMembers with many-to-many relationship. Now there is a junction table called membertable where id from GroupMembers and GroupAccount is stored.

This is what I am looking for :

  • I pass a groupAccounId and username as parameters. Now, in the GroupMembers table, there is a username stored. In groupAccount, there is groupAccountId is stored.
  • Now in the memberjunction, I have composite key memberid,GroupAccountId, I would like the member id for the username which has a matching groupAccountId I submit.

Below is the SQL code and Spring-mvc code to understand more better.

CREATE TABLE public.groupaccount (
                groupid NUMERIC NOT NULL,
                groupname VARCHAR,

                groupaccountstatus BOOLEAN DEFAULT false NOT NULL,
                adminusername VARCHAR,
                CONSTRAINT groupid PRIMARY KEY (groupid)
);

CREATE TABLE public.groupmembers (
                memberid INTEGER NOT NULL,
                musername VARCHAR
                CONSTRAINT memberid PRIMARY KEY (memberid)
);
CREATE TABLE public.memberjunction (
                memberid INTEGER NOT NULL,
                groupid NUMERIC NOT NULL,
                CONSTRAINT membergroupid PRIMARY KEY (memberid, groupid)
);

GroupMembersDAOImpl :#

 @Override
    public List<Integer> returnMemberIdWithMatchingUsername(String memberUsername) {
        session = this.sessionFactory.getCurrentSession();
        org.hibernate.Query query = session.createQuery("From GroupMembers as " +
                "n where n.memberUsername=:memberUsername");
        query.setParameter("memberUsername",memberUsername);
        List<GroupMembers> memberList = query.list();
        List<Integer> memberIdList = new ArrayList<>();
        for(GroupMembers members :memberList){
                memberIdList.add(members.getMemberid());
        }
        return memberIdList;
    }

GroupAccount model :

@Entity
@Table(name="groupaccount")
public class GroupAccount {

@Id
    @Column(name="groupid")
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "groupaccount_seq_gen")
    @SequenceGenerator(name = "groupaccount_seq_gen",sequenceName = "groupaccount_seq")
    private Long groupId;

 @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "memberjunction", joinColumns = {@JoinColumn(name = "groupid")},
                inverseJoinColumns = {@JoinColumn(name = "memberid")})
    private Set<GroupMembers> groupMembersSet = new HashSet<>();

    public void setGroupMembersSet(Set<GroupMembers> groupMembersSet){
        this.groupMembersSet = groupMembersSet;
    }
}

GroupMembers model class :

@Entity
@Table(name="groupmembers")
public class GroupMembers {
 @Id
    @Column(name="memberid")
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "groupmembers_seq_gen")
    @SequenceGenerator(name = "groupmembers_seq_gen",sequenceName = "groupmembers_seq")
    private int memberid;

    @ManyToMany(mappedBy = "groupMembersSet")
    private Set<GroupAccount> groupAccounts = new HashSet<>();

    public void setGroupAccounts(Set<GroupAccount> groupAccounts){
        this.groupAccounts = groupAccounts;
    }

    public Set<GroupAccount> getGroupAccounts(){
        return this.groupAccounts;
    }
}

Query I am using :

 @Override
    public int getMemberIdForCanvas(String memberUsername, Long groupId) {
        session = this.sessionFactory.getCurrentSession();
        org.hibernate.Query query = session.createQuery("select distinct m.memberId from GroupMembers m\n" +
                "join m.groupAccounts a\n" +
                "where a.memberUsername = :userName and m.groupId=:groupId");

        query.setParameter(memberUsername,"memberUsername");
        query.setParameter(String.valueOf(groupId),"groupId");
        int memberid = (Integer)query.uniqueResult();
        return memberid;
    }

Any help would be nice. Thanks a lot.

Here's the documentation for joins and HQL . Please read it.

The query is as simple as

select distinct m.memberId from GroupMembers m
join m.groupAccounts a
where a.memberUsername = :userName

Please also fix your naming. A GroupMembers instance is a single group member. So the class should be named GroupMember , without s . Repeating the name of the class in the fields of this class is also redundant: member.getId() is more readable and less verbose than member.getMemberId() . Same for the other fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM