Part 1 项目中JPA的使用
1.搭建环境springboot+jpa
步骤:
1.创建父工程,添加common子工程,common_model子工程.
2.common工程下添加PageResult,Result,ResultCode.
3.创建springboot微服务,数据库Id采用IdWorker
4.配置实体类与数据库映射关系
2.完成单表的CRUD
1.controller
@Autowired
private JPAService jpaService;
@RequestMapping(value = "", method = RequestMethod.POST)
public Result add(@RequestBody Article article) {
jpaService.add(article);
return new Result(ResultCode.SUCCESS, null);
}
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public Result update(@RequestBody Article article, @PathVariable Integer id) {
//查询不到数据会抛出No value present异常.已自定义抛出
Article isArticle = jpaService.findById(id);
article.setAid(isArticle.getAid());
jpaService.update(article);
return new Result(ResultCode.SUCCESS, null);
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public Result delete(@PathVariable Integer id) {
jpaService.delete(id);
return new Result(ResultCode.SUCCESS, null);
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Result findById(@PathVariable Integer id) {
Article article = jpaService.findById(id);
return new Result(ResultCode.SUCCESS, article);
}
@RequestMapping(value = "/findPage", method = RequestMethod.GET)
public Result findPage(int page, int size) {
Page<Article> page1 = jpaService.findPage(page, size);
return new Result(ResultCode.SUCCESS, new PageResult<Article>(page1.getTotalElements(), page1.getContent()));
}
2.service
@Autowired
private JPADao jpaDao;
public void add(Article article) {
article.setCreateTimeTest(new Date());
jpaDao.save(article);
}
public void update(Article article) {
jpaDao.save(article);
}
public void delete(Integer id) {
jpaDao.deleteById(id);
}
public Article findById(Integer id) {
return jpaDao.findById(id).get();
}
public Page<Article> findPage(int page, int size) {
return jpaDao.findAll(PageRequest.of(page - 1, size));
}
3.使用Specifications动态查询并进行分页
1.controller
@RequestMapping(value = "/findPage2", method = RequestMethod.GET)
public Result findPage2(int page, int size,@RequestBody Article Article) {
Page<Article> page1 = jpaService.findPage2(page, size,Article);
return new Result(ResultCode.SUCCESS, new PageResult<Article>(page1.getTotalElements(), page1.getContent()));
}
2.service
public Page<Article> findPage2(int page, int size, Article article) {
Specification<Article> spect = new Specification() {
/**
*
* @param root 用于获取属性
* @param criteriaQuery 用于生成sql
* @param cb 用来追加sql
* @return
*/
@Override
public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder cb) {
ArrayList<Predicate> list = new ArrayList<>();
//and查询
if (!StringUtils.isEmpty(article.getTitle())) {
Predicate predicate = cb.equal(root.get("title").as(String.class), article.getTitle());
list.add(predicate);
}
//or查询
// if (!StringUtils.isEmpty(article.getTitle())) {
// Expression<String> exp = root.<String>get("title");
// list.add(exp.in(article.getTitle()));
// }
//in查询
if (!StringUtils.isEmpty(article.getAid())) {
Expression<String> exp = root.<String>get("aid");
list.add(exp.in(article.getAid().split(",")));
}
return cb.and(list.toArray(new Predicate[]{}));
}
};
return jpaDao.findAll(spect,PageRequest.of(page - 1, size));
}
4.全局抓取异常并自定义异常友好返回
1.创建exceprion包定义自定义异常
import com.jpa.entity.ResultCode;
import lombok.Getter;
@Getter
public class CommonException extends Exception{
private ResultCode resultCode;
public CommonException(ResultCode resultCode) {
this.resultCode = resultCode;
}
}
2.创建异常处理器
/**
* 自定义的公共异常处理器
* 1.声明异常处理器
* 2.对异常统一处理
*/
@ControllerAdvice
public class BaseExceptionHandler {
//NoSuchElementException
@ExceptionHandler(value = NoSuchElementException.class)
@ResponseBody
public Result noValuePresent(HttpServletRequest request, HttpServletResponse response, Exception e) {
if (e.getClass() == NoSuchElementException.class) {
return new Result(ResultCode.NO_VALUE_PRESENT);
} else {
Result result = new Result(ResultCode.SERVER_ERROR);
return result;
}
}
//EmptyResultDataAccessException
@ExceptionHandler(value = EmptyResultDataAccessException.class)
@ResponseBody
public Result noExitsts(HttpServletRequest request, HttpServletResponse response, Exception e) {
if (e.getClass() == EmptyResultDataAccessException.class) {
return new Result(ResultCode.No_Exitsts);
} else {
Result result = new Result(ResultCode.SERVER_ERROR);
return result;
}
}
}