获得空值

时间:2020-05-16 02:34:46

标签: java spring spring-boot spring-data-jpa

如果我在Mysql中使用普通查询获取正确的值。

select c.user_id, c.user_name, f.current_address_id from user_master c join current_address_details f on c.current_address_id = f.current_address_id where user_name like '%Ravi%';

,但如果在Repository类中应用,则给出空值,则相同

    @Query(value = "select c.user_id, c.user_name, f.current_address_id" +
           " from user_master c join current_address_details f"+
           " on c.current_address_id = f.current_address_id where user_name like '%"+":userName"+"%'", nativeQuery = true)
    List<Object[]> searchUserDetailsByName(@Param("userName") String userName); 

我在存储库类中错过了什么?

谢谢

3 个答案:

答案 0 :(得分:2)

like子句删除为like %:userName%,不加任何引号或内容 ,将查询更新为这样:

    @Query(value = "select c.user_id, c.user_name, f.current_address_id" +
           " from user_master c join current_address_details f"+
           " on c.current_address_id = f.current_address_id where user_name like %:userName%", nativeQuery = true)
    List<Object[]> searchUserDetailsByName(@Param("userName") String userName); 

答案 1 :(得分:0)

您还可以在存储库中使用查询方法。要构造查询方法,它应以findBy或findAllBy开头,后跟您在模型类中声明的字段。例如,如果您有User类,则

@Entity
public Class User {
   ....
   private String username;
   .....
 }

@Repository
public interface UserRepository extends JpaRepository<User, Data type of your 
Identifier in User class example Long id then use Long)

List<User> findAllBy<userName>(String username);
User findBy<userName>(String username);

有关更多信息:

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.sample-app.finders.strategies

答案 2 :(得分:0)

串联部分是存在问题的地方。

尝试如下使用。

like %:userName%

请参阅下面的链接以获取详细说明。

注意:尽可能避免使用本机查询,而应使用JPQL。

Article