My favorites | Sign in
Project Logo
                
Search
for
Updated Feb 07, 2009 by kuisong.tong
Finder  
Remove the delegation to DAO to find the entities from service.

Introduction

In artical Don't repeat the DAO!, Per Mellqvist introductions Spring AOP to add a typesafe interface to DAO for query execution. But we still need write boring code to delegate the invocation from Service to DAO when represent layer need find entities. Polyforms pull it up to Repository to reduce the delegation.

Details

In Basic CRUD for user, we know how to get the CRUD fuctions for entity User. Another part is find entity by criteria, eg. getByName, we call it finder.

@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public interface UserRepository extends EntityRepository<User, String> {
	@Finder
	User getByName(String name);
	
	@Finder
	List<User> findByCreator(User creator);
}

System can return list or single object base on method's return type.

And we add Named Query for this in entity User

@NamedQueries({
	@NamedQuery(name = "User.getByName", query = "select u from User u where u.name = :name"),
	@NamedQuery(name = "User.findByCreator", query = "select u from User u where u.creator = :creator"),
})
public class User {
   ...
}

The rule for mapping method with Named Query is [name of Named Query] = [name of Entity].[name of method]. you can specify the name of Named Query in @Finder as @Finder("findUserByName"). If there are several parameters in method, you need order it basing on the named parameters in Named Query, or right order when using non named parameters.

Now we can configure the bean userRepository in spring context file

<util:bean id="userRepository"
		interfaces="cn.muthos.polyforms.sample.repository.UserFinder" />

Then we can invoke getByName method in client class like this

userRepository.getByName("zeus");
or
userRepository.findByCreator(new User("zeus"));

If there has implementation of method annotated by @Finder, system will invoke the implemented method rather than the dynamic created one.


Sign in to add a comment
Hosted by Google Code