Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CrudRepository custom method implementation?

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?

like image 947
Nicky Avatar asked Jan 22 '17 20:01

Nicky


Video Answer


1 Answers

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

like image 90
Jet_C Avatar answered Sep 22 '22 02:09

Jet_C