This spring data query is not working

一曲冷凌霜 提交于 2019-12-13 21:22:54

问题


Here is my UserRepository and a find function

@Repository
public interface UserRepository extends CrudRepository<JPA_Users, Long> {

    List<JPA_Users> findByName(String Name);

}

then in one of the controller function i try to access this find function as follows

  @RequestMapping(value = "/jpadata1", method = RequestMethod.GET)
   public String jpadata1(ModelMap map) {        
        UserRepository repository;


        ApplicationContext context = new ClassPathXmlApplicationContext("beans1.xml"); 
        repository = context.getBean(UserRepository.class);


        Iterable usrs = repository.findByName("shahzad");

}

there is a column with named name in database and i have multiple records with values shahzad i was expecting that all those records will be return but this function returns nothing no records are return

Shahzad


回答1:


    ApplicationContext context = new ClassPathXmlApplicationContext("beans1.xml"); 
    repository = context.getBean(UserRepository.class);

You are creating a new context with each request, which is a really wrong strategy.

As a first correction, don't create a new Context in your Controller, you should use dependency injection.

@Autorwired
private UserRepository userRepository; 
@RequestMapping(value = "/jpadata1", method = RequestMethod.GET)
 public String jpadata1(ModelMap map) {        
    Iterable usrs = userRepository.findByName("shahzad");
}



回答2:


Go to JPA_Users class and if you are using eclipse as ide then type outline and check what is the getter value for the field name/Name what ever you have in pojo class.

In Repository layer try this below annotation also:

org.springframework.transaction.annotation.Transactional
@Transactional

As well as check yours pojo class primary id is of type Long or not.



来源:https://stackoverflow.com/questions/37859163/this-spring-data-query-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!