Monday, March 7, 2016

Named query examples

Here are some examples of Java Named Queries:

Define named queries:

@NamedQueries({
        @NamedQuery(name = "MyClass.getBySomething",
                query = " select mc from MyClass mc " +
                        " where mc.something = :something"),
        @NamedQuery(name = "MyClass.getBySomethingOther",
                query = " select mc from MyClass mc " +
                        " where mc.somethingOther = :somethingOther")

})
public class MyClass  {
  // ...
}
 

Get single result:

    public static MyClass getBySomething( xxx something, EntityManager em ){
        TypedQuery<MyClass> query = em.createNamedQuery("MyClass.getBySomething", MyClass.class);
        query.setParameter("something", something);
        try {
            return query.getSingleResult();
        } catch (NoResultException e) {
            return null;
        } catch (NonUniqueResultException e) {
            e.printStackTrace(); // do nothing ...
            return null;
        }
    }
 

Multi-result query:

    public List<DsAisFlight> getAllUnarchived() {
       TypedQuery<DsAisFlight> query  = entityManager.createNamedQuery("MyClass.getAllUnarchived", MyClass.class);
       query.setParameter("something", something);
       try {
           return query.getResultList();
       } catch (NoResultException e) {
           return new ArrayList();
       }
   }
 

Update query:

    public static void updateXxx( EntityManager em ){
        TypedQuery query = em.createNamedQuery("MyClass.someUpdateQuery",
                MyClass.class);
        query.setParameter("someValue", 1);
        int updatedRows = query.executeUpdate();
 // ...
    }
 

Count query

@Entity
@Table( name = "my_class" )
@NamedQueries({
        @NamedQuery(name = "MyClass.countAll",
                query = "select count(l) from MyClass l")
})
public class MyClass {
...
    public static long countAll( EntityManager em ){
        Query query = em.createNamedQuery("MyClass.countAll");
        try {
            return (Long)query.getSingleResult();
        } catch (NoResultException e) {
            return 0;
        } catch (NonUniqueResultException e) {
            throw new UnsupportedOperationException("this is not possible");
        }
    }
 

No comments:

Post a Comment