在Play框架上使用Ebean获取不同的行形式Mysql

时间:2016-01-19 21:54:31

标签: java playframework ebean

我是Ebean的游戏框架世界的新手。

我基本上有两个类,User和Book。

用户有几本书。此外,用户可以多次具有相同标题的书籍,无论作者或版本是什么。我需要的是将书籍与用户联系起来,无论本书的其他任何内容如何,​​书籍的相同名称都只会出现一次。这意味着在书的标题上检索不同的图书清单。

这是我到目前为止所做的事情

用户类

@Entity
public class User extends Model{
    @Id
    public int id;  
    public String name; 
    @ManyToMany(targetEntity = Book.class,cascade=CascadeType.ALL)
    public List<Book> book;
}

图书类

@Entity
public class Book extends Model{
    @Id
    public int id;
    @Column(unique=true)
    public String name;
    public String author;
    public int edition;
    public int user_id;
}

但是,具有相同标题的多本书未被明确过滤。如何正确地将注释放在这里,以便我只能为同一个书名获得一行?

1 个答案:

答案 0 :(得分:0)

正如我所说,你的问题也与SQL有关,而不仅仅是Ebean。首先,这里有一些关于如何选择多个列但只能区分一个列的讨论:

  1. mySQL select one column DISTINCT, with corresponding other columns
  2. How to select distinct value from one column only
  3. MySQL - SELECT all columns WHERE one column is DISTINCT
  4. SQL/mysql - Select distinct/UNIQUE but return all columns?
  5. 然后,您需要使用Ebean执行正确的SQL查询(基于上述问题):

    public static List<Book> findDistinctBooks(String author) {
        String sql = "select b.id, b.name, b.author, b.edition from book b where author = :author group by name";
        RawSql rawSql = RawSqlBuilder.parse(sql)
                .columnMapping("b.id", "id")
                .columnMapping("b.name", "name")
                .columnMapping("b.author", "author")
                .columnMapping("b.edition", "edition")
                .create();
    
        return Ebean.createQuery(Book.class)
                .setRawSql(rawSql)
                .setParameter("author", author)
                .findList();
    }