Wednesday, August 13, 2014

Learn something new every day.

Dear colleagues! Did you ever hear about Spring [persistence API] interface CrudRepository<T,U>. May be that's just me - poor newbie. But if not - this interface is awesome! You just extend it:
 MyCrudInterface extends CrudRepository<MyEntityClass, Long>   
and that's all. :)
Ok, I'll explain. MyEntityClass - this is class, annotated with JPA annotations:
 @Entity  
 MyEntityClass {  
   @Id  
   @GeneratedValue(strategy = GenerationType.AUTO)  
   private long id;  
   private String name;  
   private String category;  
   //....  
 }  
And second generic type in <T,U> is id type.
And Spring will "fill" this interface for you. Now awesome part: you can add methods to interface, that will do specialized query, based on its name:
 MyCrudInterface extends CrudRepository<MyEntityClass, Long> {  
   List<MyEntity> findAll();  
   List<MyEntity> findByNameAndCategory(String name, String category);  
   Long removeByName(String);  
 }  
Now you see? :) More than that, you can do paging and sorting. Cooool.

No comments:

Post a Comment