Temporal annotation shows which part of the datetime to be stored to database:
@Temporal(TemporalType.TIMESTAMP) // date & time
@Temporal(TemporalType.DATE) // only date part
@Temporal(TemporalType.TIMESTAMP) // only time part
Nice tutorial: http://shengwangi.blogspot.bg/2014/12/the-value-of-annotation-temporal-for-date-column.html
Monday, March 14, 2016
Thursday, March 10, 2016
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"); } }
Subscribe to:
Comments (Atom)