【问题标题】:Get distinct row form Mysql with Ebean on play framework在游戏框架中使用 Ebean 从 Mysql 中获取不同的行
【发布时间】:2016-01-19 21:54:31
【问题描述】:

我是 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;
}

但多本同名书籍没有被明显过滤。如何在此处正确放置注释,以便同一书名只能获得一行?

【问题讨论】:

  • 看起来您的问题与 SQL 相关,而不是与 Ebean 相关。您是否要返回所有书籍栏但仅按标题区分?还是您只需要标题栏?您使用的是哪个数据库?
  • 我正在使用 mysql。我需要标题上不同的所有列。

标签: java playframework ebean


【解决方案1】:

正如我所说,您的问题也与 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?

然后,您将需要使用 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();
}

【讨论】:

  • 我知道使用普通的 sql 我们可以很容易地做到这一点。而且这里的书桌与用户是“一对多”的关系。因此,如果您不在查询中使用 join,即使您的查询也将无法在这里工作。无论如何,ebean orm 我们可以很容易地获得一对多的关系。我关心的是是否有任何方法可以通过注释来区分 ebean orm 中的标题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-02
相关资源
最近更新 更多