I was reading about Crudrepository which is an interface for generic CRUD operations on a repository for a specific type.
But we can create our custom interface and extend CrudRepository.
I have looked at the example online and saw that they have not provided implentation anywhere.
@Transactional
public interface UserDao extends CrudRepository<User, Long> {
/**
* Return the user having the passed email or null if no user is found.
*
* @param email the user email.
*/
public User findByEmail(String email);
}
Does the argument have to be the same name as the column name or the method name like "findBy" + columnName?
-
yes. but a correction that it should be field name which is annotated with that db column name. for eg you could have db column name as work_email but in java entity class the field mapped could be email. In that case method name should be findByEmail and not findByWorkEmail.prem kumar– prem kumar2017年01月22日 20:24:06 +00:00Commented Jan 22, 2017 at 20:24
2 Answers 2
Spring provides the Dynamic implementation of these interfaces and inject them. you can define your own methods using naming standards defined by Spring and it will automatically implements them and executes the query. Here is the complete reference documentation. https://docs.spring.io/spring-data/jpa/docs/current/reference/html/
Comments
You can have your interface extend a custom repository interface like so:
UserDao.java
public interface UserDao extends CrudRepository<User, Long>, YourCustomRepository<User, String> {
}
YourCustomRepository.java
public interface YourCustomRepository<T, S>{
public User findByName(String name);
}
You can then use the method for example:
YourControllerClass.java
@Autowired
private UserDao repo;
//An example method:
@RequestMapping("/getbyName/{name}")
public User getUserByName(@PathVariable("name") String name){
User user = repo.findByName(name); //your custom method called here
return user;
}
And note the naming convention for custom methods is "findBy....();"