Thursday, March 20, 2014

Getting last element in Hibernate's repository by annotations

Getting last element in hibernate is useful for integration testing, where you have to ensure some object is stored in database, for example.

Using Hibernate SQL.


public interface MyObjectRepository extends CrudRepository<MyObject, Long> {
  @Query("FROM com.yourcompany.zzz.MyObject c WHERE ( IN (select max(id) from com.yourcompany.zzz.MyObject)")
  MyObject getLastOne();   

It returns null, when there are no elements in table (do not throw an exception).

No comments:

Post a Comment