12

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.

Sample:

@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?

asked Jan 22, 2017 at 20:01
1
  • 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. Commented Jan 22, 2017 at 20:24

2 Answers 2

7

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/

answered Jan 23, 2017 at 4:39
Sign up to request clarification or add additional context in comments.

Comments

5

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....();"

answered Apr 26, 2017 at 14:47

2 Comments

How to implement the method YourCustomRepository.findByName()?
You don't implement them yourself. Spring automatically implements them for you and executes the query. All you need to do is call the method: User user = repo.findByName(name); NOTE: That the UserDoa repo reference is @Autowired

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.