0

I have a Post class which is like below and it has a one-to-many relation with Users (people who can see this post) and also it has the same kind of relation (one-to-many) with Groups, now I want to get all the posts by a JPA Query based on Users and Groups, how should I write the JPA Query for this?

/* Post */
public class Post extends Model {

    private String title;
    private String text;

    @OneToMany
    @JoinTable(
        name="tbl_post_users",
        inverseJoinColumns={@JoinColumn(name="userId")},
        joinColumns={@JoinColumn(name="postId")}
    )
    public List<User> users; 

    @OneToMany
    @JoinTable(
        name="tbl_post_groups",
        inverseJoinColumns={@JoinColumn(name="groupId")},
        joinColumns={@JoinColumn(name="postId")}
    )
    public List<Group> groups; 

    public static List<Post> GetPosts(){
        // JPA Query here
    }
}

/* User */
public class User extends Model {

    @Id
    private int id;
    private String name;
    private String email; 
}

/* Group */
public class Group extends Model {

    @Id
    private int id;
    private String title;
    private int ownerId; 
}

So I want to write the query so that I can get a list of all posts where user is {user} or group is {group}

4

1 回答 1

0
select distinct p from Post p 
left join p.users user
left join p.groups group
where user = :user
or group = :group

Read http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#queryhql-joins

于 2012-05-05T11:54:22.877 回答