java CrudRepository 自定义方法实现?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41795544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CrudRepository custom method implementation?
提问by Nicky
I was reading about Crudrepository which is an interface for generic CRUD operations on a repository for a specific type.
我正在阅读有关 Crudrepository 的信息,它是用于特定类型存储库上的通用 CRUD 操作的接口。
But we can create our custom interface and extend CrudRepository.
但是我们可以创建我们的自定义接口并扩展 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?
参数是否必须与列名称或方法名称(如“findBy”+ columnName)同名?
采纳答案by user3817206
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/
Spring 提供这些接口的动态实现并注入它们。您可以使用 Spring 定义的命名标准定义自己的方法,它会自动实现它们并执行查询。这是完整的参考文档。 https://docs.spring.io/spring-data/jpa/docs/current/reference/html/
回答by Jet_C
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
YourCustomRepository.java
public interface YourCustomRepository<T, S>{
public User findByName(String name);
}
You can then use the method for example:
然后您可以使用该方法,例如:
YourControllerClass.java
你的控制器类.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....();"
并注意自定义方法的命名约定是“findBy....();”
回答by Pankaj Kumar
For implementation you will basically autowire this repository and use its method... These methods has internal implementation so you can use them directly
对于实现,您将基本上自动装配此存储库并使用其方法...这些方法具有内部实现,因此您可以直接使用它们
@Service
class ImplClass{
@Autowired
UserDao userDao;
public void method(){
----
userDao.findByEmail([email protected]);
}
}