This spring data query is not working

2019-09-10 11:42发布

问题:

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.