您当前的位置: 首页 >  mybatis

SpringBoot2 综合案例(07):集成 JPA 和 MyBatis 持久层框架

蔚1 发布时间:2019-09-06 23:30:57 ,浏览量:2

Spring Boot 2 基础案例篇

包含:入门、日志管理、定时器、事务、AOP、数据库、缓存、NoSQL、监控、打包。

Spring Boot 2 高级案例篇

包含:整合常用中间件:分库分表、权限管理、Redis 集群、Dubbo、消息队列、定时器、搜索引擎、文件管理、邮件等

JAP 框架简介

JPA(Java Persistence API)意即 Java 持久化 API,是 Sun 官方在 JDK5.0 后提出的 Java 持久化规范。主要是为了简化持久层开发以及整合 ORM 技术,结束 Hibernate、TopLink、JDO 等 ORM 框架各自为营的局面。JPA 是在吸收现有 ORM 框架的基础上发展而来,易于使用,伸缩性强。

与 SpringBoot2 整合 核心依赖
    org.springframework.boot    spring-boot-starter-data-jpa
配置文件
spring:  application:    name: node09-boot-jpa  datasource:    url: jdbc:mysql://localhost:3306/data_jpa?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true    username: root    password: root    driver-class-name: com.mysql.jdbc.Driver  jpa:    hibernate:      ddl-auto: update    show-sql: true

ddl-auto 几种配置说明1)create

每次加载 hibernate 时都删除上一次的生成的表,然后根据 bean 类重新来生成新表,容易导致数据丢失,(建议首次创建时使用)。

2)create-drop

每次加载 hibernate 时根据 bean 类生成表,但是 sessionFactory 一关闭,表就自动删除。

3)update

第一次加载 hibernate 时根据 bean 类会自动建立起表的结构,以后加载 hibernate 时根据 bean 类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。

4)validate

每次加载 hibernate 时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。

实体类对象

就是根据这个对象生成的表结构。

@Table(name = "t_user")@Entitypublic class User {    @Id    @GeneratedValue    private Integer id;    @Column    private String name;    @Column    private Integer age;    // 省略 GET SET}
JPA 框架的用法

定义对象的操作的接口,继承 JpaRepository 核心接口。

import com.boot.jpa.entity.User;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.data.jpa.repository.Query;import org.springframework.data.repository.query.Param;import org.springframework.stereotype.Repository;@Repositorypublic interface UserRepository extends JpaRepository {    // 但条件查询    User findByAge(Integer age);    // 多条件查询    User findByNameAndAge(String name, Integer age);    // 自定义查询    @Query("from User u where u.name=:name")    User findSql(@Param("name") String name);}
封装一个服务层逻辑
import com.boot.jpa.entity.User;import com.boot.jpa.repository.UserRepository;import org.springframework.stereotype.Service;import javax.annotation.Resource;@Servicepublic class UserService {    @Resource    private UserRepository userRepository ;    // 保存    public void addUser (User user){        userRepository.save(user) ;    }    // 根据年龄查询    public User findByAge (Integer age){        return userRepository.findByAge(age) ;    }    // 多条件查询    public User findByNameAndAge (String name, Integer age){        return userRepository.findByNameAndAge(name,age) ;    }    // 自定义 SQL 查询    public User findSql (String name){        return userRepository.findSql(name) ;    }    // 根据 ID 修改    public void update (User user){        userRepository.save(user) ;    }    //根据 id 删除一条数据    public void deleteStudentById(Integer id){        userRepository.deleteById(id);    }}
测试代码块
import com.boot.jpa.JpaApplication;import com.boot.jpa.entity.User;import com.boot.jpa.service.UserService;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import javax.annotation.Resource;@RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes = JpaApplication.class)public class UserJpaTest {    @Resource    private UserService userService ;    @Test    public void addUser (){        User user = new User() ;        user.setName("知了一笑");        user.setAge(22);        userService.addUser(user);        User user1 = new User() ;        user1.setName("cicada");        user1.setAge(23);        userService.addUser(user1);    }    @Test    public void findByAge (){        Integer age = 22 ;        // User{id=3, name='知了一笑', age=22}        System.out.println(userService.findByAge(age));    }    @Test    public void findByNameAndAge (){        System.out.println(userService.findByNameAndAge("cicada",23));    }    @Test    public void findSql (){        // User{id=4, name='cicada', age=23}        System.out.println(userService.findSql("cicada"));    }    @Test    public void update (){        User user = new User() ;        // 如果这个主键不存在,会以主键自增的方式新增入库        user.setId(3);        user.setName("哈哈一笑");        user.setAge(25);        userService.update(user) ;    }    @Test    public void deleteStudentById (){        userService.deleteStudentById(5) ;    }}
Mybatis 框架 mybatis 简介

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

mybatis 特点
1)sql 语句与代码分离,存放于 xml 配置文件中,方便管理2)用逻辑标签控制动态 SQL 的拼接,灵活方便3)查询的结果集与 java 对象自动映射4)编写原生态 SQL,接近 JDBC5)简单的持久化框架,框架不臃肿简单易学
适用场景

MyBatis 专注于 SQL 本身,是一个足够灵活的 DAO 层解决方案。 对性能的要求很高,或者需求变化较多的项目,MyBatis 将是不错的选择。

与 SpringBoot2 整合 项目结构图

采用 druid 连接池,该连接池。

核心依赖
    org.mybatis.spring.boot    mybatis-spring-boot-starter    1.3.2    com.github.pagehelper    pagehelper    4.1.6
核心配置
mybatis:  # mybatis 配置文件所在路径  config-location: classpath:mybatis.cfg.xml  type-aliases-package: com.boot.mybatis.entity  # mapper 映射文件  mapper-locations: classpath:mapper/*.xml
逆向工程生成的文件

在这里插入图片描述这里就不贴代码了。

编写基础测试接口
// 增加int insert(ImgInfo record);// 组合查询List selectByExample(ImgInfoExample example);// 修改int updateByPrimaryKeySelective(ImgInfo record);// 删除int deleteByPrimaryKey(Integer imgId);
编写接口实现
@Servicepublic class ImgInfoServiceImpl implements ImgInfoService {    @Resource    private ImgInfoMapper imgInfoMapper ;    @Override    public int insert(ImgInfo record) {        return imgInfoMapper.insert(record);    }    @Override    public List selectByExample(ImgInfoExample example) {        return imgInfoMapper.selectByExample(example);    }    @Override    public int updateByPrimaryKeySelective(ImgInfo record) {        return imgInfoMapper.updateByPrimaryKeySelective(record);    }    @Override    public int deleteByPrimaryKey(Integer imgId) {        return imgInfoMapper.deleteByPrimaryKey(imgId);    }}
控制层测试类
@RestControllerpublic class ImgInfoController {    @Resource    private ImgInfoService imgInfoService ;    // 增加    @RequestMapping("/insert")    public int insert(){        ImgInfo record = new ImgInfo() ;        record.setUploadUserId("A123");        record.setImgTitle("博文图片");        record.setSystemType(1) ;        record.setImgType(2);        record.setImgUrl("https://avatars0.githubusercontent.com/u/50793885?s=460&v=4");        record.setLinkUrl("https://avatars0.githubusercontent.com/u/50793885?s=460&v=4");        record.setShowState(1);        record.setCreateDate(new Date());        record.setUpdateDate(record.getCreateDate());        record.setRemark("知了");        record.setbEnable("1");        return imgInfoService.insert(record) ;    }    // 组合查询    @RequestMapping("/selectByExample")    public List selectByExample(){        ImgInfoExample example = new ImgInfoExample() ;        example.createCriteria().andRemarkEqualTo("知了") ;        return imgInfoService.selectByExample(example);    }    // 修改    @RequestMapping("/updateByPrimaryKeySelective")    public int updateByPrimaryKeySelective(){        ImgInfo record = new ImgInfo() ;        record.setImgId(11);        record.setRemark("知了一笑");        return imgInfoService.updateByPrimaryKeySelective(record);    }    // 删除    @RequestMapping("/deleteByPrimaryKey")    public int deleteByPrimaryKey() {        Integer imgId = 11 ;        return imgInfoService.deleteByPrimaryKey(imgId);    }}
测试顺序
http://localhost:8010/inserthttp://localhost:8010/selectByExamplehttp://localhost:8010/updateByPrimaryKeySelectivehttp://localhost:8010/deleteByPrimaryKey
集成分页插件 mybatis 配置文件
                                            
分页实现代码
@Overridepublic PageInfo queryPage(int page,int pageSize) {    PageHelper.startPage(page,pageSize) ;    ImgInfoExample example = new ImgInfoExample() ;    // 查询条件    example.createCriteria().andBEnableEqualTo("1").andShowStateEqualTo(1);    // 排序条件    example.setOrderByClause("create_date DESC,img_id ASC");    List imgInfoList = imgInfoMapper.selectByExample(example) ;    PageInfo pageInfo = new PageInfo(imgInfoList) ;    return pageInfo ;}
测试接口
http://localhost:8010/queryPage
源代码地址
GitHub 地址:知了一笑https://github.com/cicadasmile/spring-boot-base码云地址:知了一笑https://gitee.com/cicadasmile/spring-boot-base

本文首发于 GitChat,未经授权不得转载,转载需与 GitChat 联系。

阅读全文: http://gitbook.cn/gitchat/activity/5d712eac1bd0a05562ee5b3b

您还可以下载 CSDN 旗下精品原创内容社区 GitChat App ,阅读更多 GitChat 专享技术内容哦。

FtooAtPSkEJwnW-9xkCLqSTRpBKX

关注
打赏
1688896170
查看更多评论

蔚1

暂无认证

  • 2浏览

    0关注

    4645博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.1169s