[Solved] JPA query data error: Page 1 of 0 containing UNKNOWN instances

The reason for the error is that there is an empty object according to your query condition, that is, it is not checked. Then double-check the conditions you wrote.
I reported an error because the previous code used cb.equal(root.get(“userName”), res.getName()), which is an absolute query. I copied the previous code directly, but now I want to change it to a fuzzy query, cb.equal(root.get(“userName”), “%” + res.getName().trim() + “%”), here you can see that I only changed the parameter value to a fuzzy query, but the condition is still used equal absolute query reported an error, I searched for more than half an hour to find, and then changed to cb.like(root.get(“userName “), “%” + res.getName().trim() + “%”) and it works.

Specification<TUser> specification = (root, query, cb) -> {
            List<Predicate> predicates = Lists.newArrayList();
            predicates.add(cb.or(cb.equal(root.get("role"), StateEnum.ecgDoctor.name()), cb.equal(root.get("role"), StateEnum.intern.name())));
            //Add name condition
            if (res.getName() != null) {
                predicates.add(cb.like(root.get("userName"), "%" + res.getName().trim() + "%"));
            }
            if (res.getPhoneno() != null) {
                predicates.add(cb.like(root.get("phone"), "%" + res.getPhoneno().trim() + "%"));
            }
            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        };

To sum up, if you use absolute queries in the future, write it like this

//Add name condition
if (res.getName() != null) {
    predicates.add(cb.equal(root.get("userName"), res.getName().trim()));
}

Fuzzy queries are written like this.

//Add name condition
if (res.getName() != null) {
    predicates.add(cb.equal(root.get("userName"), "%" + res.getName().trim() + "%"));
}

This will not be wrong.

Also note that the paging inside the JPA, page is from 0, there is root.get(“property”), the name of this property is the name of the entity class inside, is this private String userName, this @Column(name = “user_name”) is the name of the database, do not get confused.

@Column(name = "user_name")
private String userName;

Read More:

Leave a Reply

Your email address will not be published. Required fields are marked *