【问题标题】:Hibernate: queries by example and many-to-one relationshipsHibernate:示例查询和多对一关系
【发布时间】:2012-06-06 08:50:39
【问题描述】:

假设这些是我的实体:

Table1.java

@Entity
public class Table1 {

    // Many to one
    private Table2 table2;

    // Raw attributes
    // ...

}

Table2.java

@Entity
public class Table2 {

    // Many to one
    private Table3 table3;

    // Raw attributes
    // ...

}

Table3.java

@Entity
public class Table3 {

    // Raw attributes
    private String lang; // "fr", "en", "de"...

}

我想列出所有 Table1 行中的 table2.table3.lang 等于 en。我尝试通过示例使用查询:

Table3 table3Example = new Table3();
table3Example.setLang("en");

Table2 table2Example = new Table2();
table2Example.setTable3(table3Example);

Table1 table1Example = new Table1();
table1Example.setTable2(table2Example);

table1Repository.findByExample(table1Example);

问题是.findByExample(table1Example)返回数据库的所有行,不管lang,这意味着过滤器根本不考虑:(

任何帮助将不胜感激:)

PS:不抛出异常,.findByExample(table1Example) 只返回所有Table1 行。

【问题讨论】:

    标签: java hibernate jpa many-to-one query-by-example


    【解决方案1】:

    试试这样的:

        Query q = entityManager.createQuery("Select o from Table1 o where o.table2.table3.lang = :lang");
        q.setParameter("lang", "en");
        List<Table1> r = (List<Table1>)q.getResultList();
    

    要查看为什么要获得 Table1 中的所有行,请确保您拥有

    <property name="hibernate.show_sql" value="true"/>
    

    在您的 persistence.xml 中,然后查看日志以查看 hibernate 执行的实际选择。

    【讨论】:

    • 效果很好!但这意味着我必须自己实现所有我想要的过滤器。如果示例查询可以自己完成多对一链接,那就太好了。不可能吗?无论如何谢谢:)
    • 据我所知,示例查询和多对一关系存在一些问题。确定运行 findByExample 时发生的情况的最佳方法是查看日志并查看实际的 select hibernate 执行情况。
    • 其实在我的.findByExample方法中(也就是SpringFuse的方法),有一个if (attr.getPersistentAttributeType() == MANY_TO_ONE) continue;。当我评论该行时,我发现了一个异常:object references an unsaved transient instance,这很容易理解,因为对象是示例,而不是真正的持久实体。但是,是的,那里似乎缺乏,通过示例查询有改进的余地:)无论如何谢谢,我给你800+!
    猜你喜欢
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 2018-11-09
    • 2015-02-05
    • 2021-12-29
    • 2010-09-20
    相关资源
    最近更新 更多