0

I have an entity, and the DAO with interface JpaRepository<MyEntity, Long>. Using EclipseLink.

I'm using the following method from the DAO:

Iterable<MyEntity> findAll(Iterable<Long> ids);

in this way:

List<Long> listOfIds = Arrays.asList(new Long[] {1,2,3});
Iterable<MyEntity> entities = dao.findAll(listOfIds);

I've got the MySQL exception:

java.sql.SQLException: Operand should contain 1 column(s)

The SQL query that is executed in the database has the following syntax:

SELECT id, creation_date, column1, column2 FROM my_entity WHERE (id IN ((1,2,3)))

The problem is in the last braces - there are too many of them. The working query is:

SELECT id, creation_date, column1, column2 FROM my_entity WHERE (id IN (1,2,3))

Any reason why the Spring Data adds these unnecessary braces? Any way to fix it?

4

1 回答 1

3

FOUND WORKAROUND

First of all, your DAO must also implement the JpaSpecificationExecutor<MyEntity>. Then, create a Specification-factory class like this:

public final class MyEntitySpecifications {
    public static Specification<MyEntity> idsIn(final Collection<Long> ids) {
        return new Specification<MyEntity>() {
            @Override
            public Predicate toPredicate(Root<MyEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                return root.get("id").in(ids);
            }
        };
    }
}

and use your DAO like this:

Iterable<MyEntity> entities = dao.findAll(MyEntitySpecifications.idsIn(listOfIds));

Produced query is now as expected.

于 2013-09-27T18:27:08.500 回答