简体   繁体   中英

jpa query doesn't seem to resolve enum value correctly and always returns empty list

I'm writing a very simple query which only queries for Foo objects with a given status, but the result I get is always an empty list, but I really have no idea what was wrong with my code.

My findByStatus method looks like this:

public List<Foo> findByStatus(final Status status, final int startIndex, final int maxRows)
{
    List<Foo> foos= getJpaTemplate().executeFind(new JpaCallback()
    {
        @Override
        public Object doInJpa(EntityManager entityManager) throws PersistenceException
        {
            Query q = entityManager.createQuery("SELECT f FROM Foo f WHERE f.status = :status", Foo.class);
            q.setParameter("status", status);    //This will not automatically resolve???
            q.setFirstResult(startIndex).setMaxResults(maxRows);
            return q.getResultList();
        }
    });

    return foos == null ? Collections.EMPTY_LIST : foos;
}

HOWEVER, if I (1) take out the Foo.class (the second param in entityManager.createQuery and (2) do q.setParameter("status", status.name()) instead, then I'll get the correct result list.

Does anyone know what's wrong here?

By the way, my Foo class that looks like this:

public class Foo
{
  @Enumerated(EnumType.STRING) @Column(nullable=false, columnDefinition = "VARCHAR(10) DEFAULT 'ON'")
  private Status status= Status.ON;

  //other fields
}

And status looks like this

public enum Status
{
  ON("ON"),
  OFF("OFF"),
  UNKNOWN("UNKNOWN");

  private String status;

  private Status(String status)
  {
     this.status = status;
  }

  public String getStatus()
  {
     return status;
  }
}

So looks like hibernate bind my enum value to some VARBINARY, which is weird:

2013-12-27 11:38:35,341 TRACE [org.hibernate.type.descriptor.sql.BasicBinder]  - <binding parameter [1] as [VARBINARY] - ON>

I have the same problem in one specific application.

The root cause in that hibernate is ignoring the @Enumerated annotion and always passing to the sql the enum as VARBINARY

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM