ITeye博客

spring boot + jpa实现数据查询工作

duduli · 2018-08-28 12:38 · java · 编程语言 · Markdown

前期已经将mybatis和hibernate已经进行了掌握。 朋友介绍说jpa对数据查询进行了封装,也支持sql的查询方式。 今天就尝试使用jpa进行数据查询,并使用spring boot实现显示。 以下是基本内容,期间有些坑需要注意的。 数据库连接信息:

spring:
  jpa:
    database: mysql
  datasource:
    url: jdbc:mysql://localhost:3306/fixtime?characterEncoding=utf8&useSSL=false
    username: root
    password: test
    driver-class-name: com.mysql.jdbc.Driver

dao层,数据查询(有两点需要注意的。1,sql查询需要设置 nativeQuery = true;2,传参的时候需要使用Param进行注解):

@Component
public interface CRUD extends JpaRepository<User,Integer>{
    @Query(value = "select * from user where phone like %:phone%" , nativeQuery = true)
    public List<User> findByName(@Param("phone") String phone);


    public User findUserById(Integer id);
}

这里业务简单所以没有使用service层,这里直接在controller中直接调用dao层接口。如果需要使用占位符传参需要使用PathVariable。

    @Autowired
    private CRUD crud;

    @GetMapping(value = "/listuser")
    public List<User> listUser(@Param("phone") String phone){
        System.out.println(phone);
        return crud.findByName(phone);
//        return userService.listUserByPhone(phone);
    }

    @GetMapping(value = "/getuser/{id}")
    public User getUser(@PathVariable("id") Integer id){
        return crud.findUserById(id);
//        return userService.listUserByPhone(phone);
    }

启动之后查询: http://localhost:8080/listuser?phone=13 调用like查询 http://localhost:8080/getuser/4 调用单个查询

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。