2 JPA 使用
2.1 导入jar包
org.springframework.boot
spring-boot-starter-data-jpa
mysql
mysql-connector-java
org.projectlombok
lombok
1.18.8
provided
2.2 配置文件
spring:
application:
name: boot-user
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.85.198:3306/tensquare_user?
characterEncoding=utf-8&&useSSL=false
username: root
password: 123456
jpa:
database: mysql
show-sql: true
generate-ddl: true
http:
encoding:
charset: utf-8
force: true
enabled: true
logging:
level:
org:
hibernate:
SQL: DEBUG
2.3 使用实例
package com.liu.user.dao;
import com.liu.user.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
/**
* Created by Administrator on 2019/8/15 0015.
*
* concat() 字符串拼接很好用。记得这个是mysql的函数
* 在param 导包的过程中,记得导包别倒错,要不然会查不到数据,或者报错
* 这里还支持原生的sql。视情况而选择相应技术类型
* 在使用原生的sql实例:
*
*
*/
public interface UserDao extends JpaRepository,JpaSpecificationExecutor {
// 这个是hibernate的方式
// @Query(value = " select u from User u where u.loginName like concat('%',:query,'%') or u.cardId like concat('%',:query,'%') ")
// 这种方式代表使用原生的sql查询方式
// @Query(value = "select u.* from boot_user u where u.login_name like concat('%',:query,'%') or u.card_id like concat('%',:query,'%')",nativeQuery = true)
// 占位符的使用
@Query(value = " select u from User u where u.loginName like concat('%',?1,'%') or u.cardId like concat('%',?1,'%') ")
Page findSearch(@Param("query") String query, Pageable pageable);
}
2.4 拓展service类
package com.liu.user.service;
import com.liu.common.entity.PageResult;
import com.liu.user.dao.UserDao;
import com.liu.user.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by Administrator on 2019/8/15 0015.
* @service 用来标准他是一个service层的实现类
* @Slf4j 用来生成一个log的内置对象,这样我们就可以使用log 来记录日志
*
*/
@Service
@Slf4j
public class UserService {
@Autowired
private RedisTemplate redisTemplate ;
@Autowired
private UserDao userDao;
public PageResult findAllByPage(int page, int rows, String query){
Pageable pageable= PageRequest.of(page-1,rows);
log.info("query:{}",query);
Page users = userDao.findSearch(query,pageable);
log.info("{}",users.getContent());
return new PageResult(users.getTotalElements(),users.getContent());
}
}
2.5 配套controller 类
package com.liu.user.controller;
import com.liu.common.entity.PageResult;
import com.liu.common.entity.Result;
import com.liu.user.entity.User;
import com.liu.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by Administrator on 2019/8/15 0015.
* @RestController 表示该控制器所有的返回均为josn格式的对象
* @RequestMapping("/user") 表示该控制器作用域为/user
* @Slf4j 生成log的内置对象,用于记录日志
*/
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
@Autowired
private UserService userService;
/**
* @GetMapping(value = "/{id}") 表示书写接口的风格为restful风格 ,调用的方式为get,同时,使用路径参数
* @param id
* @return
*/
@GetMapping(value = "/{id}")
public Result findById(@PathVariable("id") String id){
User user = userService.findById(id);
return new Result(true,1,"查询成功",user);
}
/**
* @GetMapping(value = "/{id}") 表示书写接口的风格为restful风格 ,调用的方式为get,同时,使用路径参数
* @param page rows query
* @return
*/
@GetMapping(value = "/{page}/{rows}/{query}")
public Result findByList(@PathVariable(value = "page" ,required = false) int page , @PathVariable("rows") int rows, @PathVariable("query") String query){
log.info(" page{}",page);
log.info("rows{}",rows);
log.info("query{}",query);
PageResult pageResult= userService.findAllByPage(page,rows,query);
return new Result(true,1,"查询成功",pageResult);
}
}
2.6 返回json对象格式
2.6.1 返回类型的封装
package com.liu.common.entity;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;
import lombok.Setter;
**
* 结果返回实体类
* @JsonInclude(JsonInclude.Include.NON_NULL)
* 对象中的属性如果为空,则该字段不进行转换
*
*
*/
@Getter
@Setter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Result {
private boolean flag;//是否成功
private Integer code;// 返回码
private String message;//返回信息
private Object data;// 返回数据
public Result() {
}
public Result(boolean flag, Integer code, String message, Object data) {
this.flag = flag;
this.code = code;
this.message = message;
this.data = data;
}
public Result(boolean flag, Integer code, String message) {
this.flag = flag;
this.code = code;
this.message = message;
}
}
2.6.2 返回page对象封装
package com.liu.common.entity;
import lombok.*;
import java.util.List;
/**
* 分页结果类
* @param
* 分页返回对象封装
* @AllArgsConstructor 生成全参数构造
@NoArgsConstructor 生成空参数构造
@Getter 自动生成get方法
@Setter 自动生成set方法
*/
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class PageResult {
private long total; // 结果集的总记录条数
private List rows; // 当前页返回的记录条数
}
2.6.3 返回的结果json格式
{
"flag": true,
"code": 1,
"message": "查询成功",
"data": {
"total": 2,
"rows": [
{
"id": "1",
"loginName": "1213",
"birth": "2019-08-14T16:00:00.000+0000",
"password": null,
"cardId": "13213132132131",
"state": 1
},
{
"id": "2",
"loginName": "1212",
"birth": "2019-08-08T16:00:00.000+0000",
"password": null,
"cardId": "4564645646456",
"state": 2
}
]
}
}