How to execute a query using a built-in example containing null values ​​using hibernate?

I have a problem with a request using sleep mode. The entity class EntityClasshas a built-in embeddedtype property EmbeddedClass, and this property has a nullable property optional. When all the properties are set, I can execute a very simple HQL query:

Query query = getSession().createQuery(
    "FROM EntityClass t WHERE t.embedded = :embedded");
query.setParameter("embedded", embedded);
return (EntityClass) query.uniqueResult();

But when the property optionalis null, this does not work, because hibernate creates an SQL query, for example t.optional=?, but =NULLmust be IS NULLin SQL. The WHERE clause never matches, the query does not return rows.

Some additional reading points to an example that handles null correctly. Now my code is as follows:

Criteria query = getSession().createCriteria(EntityClass.class);
query.createCriteria("embedded").add(Example.create(embedded));
return (EntityClass) query.uniqueResult();

When I run the code, I get ClassCastException:

java.lang.ClassCastException: EmbeddedClass
    at org.hibernate.criterion.Example.getEntityMode(Example.java:279)
    at org.hibernate.criterion.Example.toSqlString(Example.java:209)
    at org.hibernate.loader.criteria.CriteriaQueryTranslator.getWhereCondition(CriteriaQueryTranslator.java:357)
    at org.hibernate.loader.criteria.CriteriaJoinWalker.<init>(CriteriaJoinWalker.java:113)
    at org.hibernate.loader.criteria.CriteriaJoinWalker.<init>(CriteriaJoinWalker.java:82)
    at org.hibernate.loader.criteria.CriteriaLoader.<init>(CriteriaLoader.java:91)
    at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1577)
    at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:306)
    at org.hibernate.impl.CriteriaImpl.uniqueResult(CriteriaImpl.java:328)

EntityPersister.guessEntityMode() null, hibernate , .

, org.hibernate.criterion.Example . , ? ohter?

:

@Entity
public class EntityClass {
    ...

    @Embedded
    private EmbeddedClass embedded;

    ...
}

@Embeddable
public class EmbeddedClass {
    private String name;
    private String optional;
    ...
}

hibernate 3.3.1 10g, .

+3
2

, :

, . , :

Criteria query = getSession().createCriteria(EntityClass.class);
EntityClass example = new EntityClass();
example.setEmbedded(embedded);
query.add(Example.create(example).excludeNone()
    .excludeProperty("id").excludeProperty("other"));
return (EntityClass) query.uniqueResult();
+2

isNull . , :

Criteria entityCriteria = getSession().createCriteria(EntityClass.class);
entityCriteria.add(Restrictions.isNull("optional")); // isNull restriction on the optional attribute of your EntityClass
List results = entityCriteria.list();
0

Source: https://habr.com/ru/post/1735454/


All Articles