Part 1 项目中JPA的使用

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;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值