JPARepository findAllByUsername返回null,但是数据存在

时间:2019-02-13 15:57:32

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

我有一个简单的系统(Controller,Service,Repository),但是即使数据库中存在数据,该服务也会返回空值

数据

mysql> select * from customer;
+----+---------------+
| id | username      |
+----+---------------+
|  4 | liparistudios |
+----+---------------+

@Data
@Entity
@Table(name = "customer")
public class Customer implements Serializable {
    private static final long serialVersionUID = 201811031445L;

    @Id
    @GeneratedValue( strategy = GenerationType.SEQUENCE )
    private Long id;

    private String username;

控制器

Customer c = customerService.searchCustomerByUsername( usernameToFind );

服务

@Service
public class CustomerService {

    @Autowired
    private CustomerRepo repo;

    public Customer searchCustomerByUsername( String username ) {
        return repo.findAllByUsername( username );
    }

存储库

@Repository
@Transactional
public interface CustomerRepo extends JpaRepository<Customer, Long> {
    @Query(
        value = "SELECT * FROM Customer c WHERE username = ':username' ORDER BY username ASC LIMIT 1",
        nativeQuery = true
    )
    public Customer findAllByUsername(@Param("username") String username );

1 个答案:

答案 0 :(得分:2)

绑定参数不应包含在引号中。确保删除:username周围的单引号。

正确的查询应为SELECT * FROM Customer c WHERE username = :username ORDER BY username ASC LIMIT 1