简体   繁体   English

如何在 Hibernate 中选择没有子对象的父对象?

[英]How to select parent objects without children in Hibernate?

I have the following entities, parent and child, it's possible that a parent object doesn't have children.我有以下实体,父对象和子对象,父对象可能没有子对象。 How to select parents that don't have children in hibernate?如何选择没有孩子休眠的父母? It would be similar to the not existing clause in SQL.它类似于 SQL 中not existing子句。 Here are my entities:这是我的实体:

@Entity
@Table(name = "PARENT")
public class Parent implements Serializable {

    @Id
    @Column(name="PARENT_ID")
    private Long parentId;

    @Column(name="NAME")
    private String name;

    @OneToMany(mappedBy="parent", fetch=FetchType.EAGER)
    Set<Child> children;
}
@Entity
@Table(name = "CHILD")
public class Child implements Serializable {

    @Id
    @Column(name="CHILD_ID")
    private Long childId;

    @Column(name="NAME")
    private String name;

    @ManyToOne(cascade={CascadeType.ALL}, fetch=FetchType.EAGER)
    @JoinColumn(name="PARENT_ID", nullable=false, updatable=false)
    private Parent parent;
}

My query:我的查询:

public List<Parent> getParentsNotHavingChildren() {
    Session session = this.sessionFactory.getCurrentSession();
    Transaction txn = session.beginTransaction();
    List<Parent> result = null;
    Criteria criteria = session.createCriteria(Parent.class)
            .add(Restrictions.eq("children", null));
    result = criteria.list();
    txn.commit();
    if (session.isOpen()) {
        session.close();
    }
    log.info(String.format("Get %s parents", result.size()));
    return result;
}

Then I got errors然后我得到了错误

org.hibernate.exception.GenericJDBCException: could not execute query
    at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:140)
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:128)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.loader.Loader.doList(Loader.java:2545)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2276)
    at org.hibernate.loader.Loader.list(Loader.java:2271)
    at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:119)
    at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1716)
    at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:347)
    at HibernateParentDao.getParentsNotHavingChildren(HibernateParentDao.java:42)
Caused by: java.sql.SQLException: Missing IN or OUT parameter at index:: 1
    at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
    at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:110)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:171)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:227)
    at oracle.jdbc.driver.OraclePreparedStatement.processCompletedBindRow(OraclePreparedStatement.java:1737)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3376)
    at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3425)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1202)
    at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:76)
    at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208)
    at org.hibernate.loader.Loader.getResultSet(Loader.java:1953)
    at org.hibernate.loader.Loader.doQuery(Loader.java:802)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274)
    at org.hibernate.loader.Loader.doList(Loader.java:2542)

I'm sure my criteria isn't correct, but I can't find what should be the right way of this type of query.我确定我的标准不正确,但我找不到此类查询的正确方法。 Any help would be very appreciated!任何帮助将不胜感激!

To test an attribute to be null, then use isNull ... change要测试一个属性为空,然后使用isNull ...更改

Criteria criteria = session.createCriteria(Parent.class)
        .add(Restrictions.eq("children", null));

for对于

Criteria criteria = session.createCriteria(Parent.class)
        .add(Restrictions.isNull("children"));

Otherwise, Hibernate will expect a non-null value to perform the eq否则,Hibernate 将期望一个非空值来执行eq

This is a simple criteria to select a parent with no children (for one to many relations you should use isEmpty ).这是选择没有子级的父级的简单标准(对于一对多关系,您应该使用isEmpty )。

Criteria criteria = currentSession().createCriteria(Parent.class);
criteria.add(Restrictions.isEmpty("children"));
return criteria.list();

And by the way, for a simple "select" query you don't need to create a transaction .顺便说一下,对于简单的“选择”查询,您不需要创建transaction Just with the three lines above it should be enough.只要有上面的三行就足够了。

The other answer may work but only in one to one relationships.另一个答案可能有效,但仅适用于一对一的关系。 Hope it works!希望它有效!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 休眠:选择有孩子条件的父母 - Hibernate: Select Parent with Children Conditions 如何在Hibernate中让没有孩子且没有懒惰例外的唯一父母? - How to get only parent without children in Hibernate and without lazy exception? 休眠条件,分组/选择父母的不同孩子 - Hibernate Criteria, group/select distinct children of a parent 休眠-选择“子项”,然后与“父项”一起加入,并与其他子项一起返回“父项” - Hibernate - Select Child and then join with Parent returns Parent with other children as well Hibernate - 如何只保留父母,让孩子保持原样 - Hibernate - How to persist only the parent, keeping the children as they are 休眠:保存具有现有子级的父对象(单向) - Hibernate: Saving parent objects with already existing children(unidirectional) 休眠检索父母/孩子 - Hibernate retrieving parent/children Hibernate 5 和 JPA:select 表没有他的孩子,但在保存时保持持久性 - Hibernate 5 and JPA: select table without his children but maintain persistence on save 如何从 java 中的父对象列表中获取子对象列表 - How to get list of children objects from a list of parent objects in java 休眠:分离父母和所有孩子 - HIbernate: Detach parent and all children
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM