当前位置: 首页 > news >正文

springboot 系列教程六:springboot mybatis集成

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

首先引入 mybatis-spring-boot-starter 的 pom 文件

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>

好了下来分别介绍两种开发模式。

无配置文件注解版

就是一切使用注解搞定。

1.application.properties 添加相关配置

mybatis.type-aliases-package=com.zmj.web.entity
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.username = root
spring.datasource.password = 1234

springboot 会自动加载spring.datasource.*相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory 会自动注入到 Mapper 中,对了你一切都不用管了,直接拿起来使用就行了。

2.在启动类中添加对 mapper 包扫描@MapperScan

@SpringBootApplication
@MapperScan("com.zmj.web.mapper")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

或者直接在 Mapper 类上面添加注解@Mapper,建议使用@MapperScan

3.开发Mapper

public interface UserMapper {

    @Select("SELECT * FROM users")
    @Results({
        @Result(property = "userSex",  column = "user_sex", javaType = UserSexEnum.class),
        @Result(property = "nickName", column = "nick_name")
    })
    List<UserEntity> getAll();

    @Select("SELECT * FROM users WHERE id = #{id}")
    @Results({
        @Result(property = "userSex",  column = "user_sex", javaType = UserSexEnum.class),
        @Result(property = "nickName", column = "nick_name")
    })
    UserEntity getOne(Long id);

    @Insert("INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName}, #{passWord}, #{userSex})")
    void insert(UserEntity user);

    @Update("UPDATE users SET userName=#{userName},nick_name=#{nickName} WHERE id =#{id}")
    void update(UserEntity user);

    @Delete("DELETE FROM users WHERE id =#{id}")
    void delete(Long id);
}

为了更接近生产我特地将user_sex、nick_name两个属性在数据库加了下划线和实体类属性名不一致,另外user_sex使用了枚举。

  • @Select 是查询类的注解,所有的查询均使用这个
  • @Result 修饰返回的结果集,关联实体类属性和数据库字段一一对应,如果实体类属性和数据库属性名保持一致,就不需要这个属性来修饰。
  • @Insert 插入数据库使用,直接传入实体类会自动解析属性到对应的值
  • @Update 负责修改,也可以直接传入对象
  • @Delete 负责删除

4.使用 上面三步就基本完成了相关dao层开发,使用的时候当作普通的类注入进入就可以了。

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {

    @Autowired
    private UserMapper UserMapper;

    @Test
    public void testInsert() throws Exception {
        UserMapper.insert(new UserEntity("张三", "1234", UserSexEnum.MAN));
        UserMapper.insert(new UserEntity("李四", "1234", UserSexEnum.WOMAN));
        UserMapper.insert(new UserEntity("王五", "1234", UserSexEnum.WOMAN));
    }

    @Test
    public void testQuery() throws Exception {
        List<UserEntity> users = UserMapper.getAll();
        System.out.println(users.toString());
    }

    @Test
    public void testUpdate() throws Exception {
        UserEntity user = UserMapper.getOne(1);
        System.out.println(user.toString());
        user.setNickName("马六");
        UserMapper.update(user);
    }
}

xml版本

xml版本保持映射文件的老传统,优化主要体现在不需要实现dao的是实现层,系统会自动根据方法名在映射文件中找对应的sql

1.配置 pom文件和上个版本一样,只是application.properties新增以下配置。

mybatis.config-locations=classpath:mybatis-config.xml
mybatis.mapper-locations=classpath:com/zmj/web/mapper/*.xml

指定了mybatis基础配置文件和实体类映射文件的地址。 mybatis-config.xml 配置。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <typeAliases>
        <package name="com.zmj.web.entity"/>
    </typeAliases>
</configuration>

这里也可以添加一些mybatis基础的配置

2.添加User的映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.zmj.web.api.UserDao">
    <select id="selectById" parameterType="int" resultType="user">
        select * from t_user where uid = #{uid}
    </select>
    <insert id="insert" parameterType="user">
        insert into t_user values(#{uid},#{uname},#{age})
    </insert>
</mapper>

3.编写Dao层的代码

public interface UserMapper {
    User selectById(String uid);
    void insert(User user);
}

4.使用

使用方式和之前一样

如何选择

两种模式各有特点,注解版适合简单快速的模式,其实像现在流行的这种微服务模式,一个微服务就会对应一个自已的数据库,多表连接查询的需求会大大的降低,会越来越适合这种模式。传统模式比较适合大型项目,可以灵活的使用SQL。

转载于:https://my.oschina.net/zhoumj/blog/3036543

相关文章:

  • windows添加开机启动项
  • 关于Docker文件系统
  • XP和Win 7双系统安装说明和注意事项
  • jQuery之getAll()和cleanData()
  • 利用pig分析cdn访问日志内指定时间段的url访问次数
  • 6本Python好书上新,来撩~
  • cursor:hand与cursor:pointer的区别介绍
  • 【AC自动机】AC自动机
  • Java 生成 exe 文件
  • 大数据分析工具如何摆脱样子工程?
  • 学习Android怎么在未来站稳脚跟
  • 预测《权游》角色生死,AI算法魔力何在?
  • R语言学习笔记:因子
  • 转:开源3D引擎介绍
  • 1. 容器化部署一套云服务 第一讲 Jenkins(Docker + Jenkins + Yii2 + 云服务器))
  • 【编码】-360实习笔试编程题(二)-2016.03.29
  • 002-读书笔记-JavaScript高级程序设计 在HTML中使用JavaScript
  • Consul Config 使用Git做版本控制的实现
  • flutter的key在widget list的作用以及必要性
  • Git同步原始仓库到Fork仓库中
  • Laravel 菜鸟晋级之路
  • niucms就是以城市为分割单位,在上面 小区/乡村/同城论坛+58+团购
  • opencv python Meanshift 和 Camshift
  • Spark in action on Kubernetes - Playground搭建与架构浅析
  • Spring Boot MyBatis配置多种数据库
  • 测试开发系类之接口自动化测试
  • 前端技术周刊 2019-01-14:客户端存储
  • 强力优化Rancher k8s中国区的使用体验
  • 如何利用MongoDB打造TOP榜小程序
  • 入门级的git使用指北
  • 使用 Node.js 的 nodemailer 模块发送邮件(支持 QQ、163 等、支持附件)
  • 使用阿里云发布分布式网站,开发时候应该注意什么?
  • 移动端解决方案学习记录
  • ionic异常记录
  • 策略 : 一文教你成为人工智能(AI)领域专家
  • ​520就是要宠粉,你的心头书我买单
  • #pragma multi_compile #pragma shader_feature
  • #vue3 实现前端下载excel文件模板功能
  • (14)学习笔记:动手深度学习(Pytorch神经网络基础)
  • (8)Linux使用C语言读取proc/stat等cpu使用数据
  • (三)docker:Dockerfile构建容器运行jar包
  • (转)真正的中国天气api接口xml,json(求加精) ...
  • **Java有哪些悲观锁的实现_乐观锁、悲观锁、Redis分布式锁和Zookeeper分布式锁的实现以及流程原理...
  • .bat批处理(九):替换带有等号=的字符串的子串
  • .NET 5.0正式发布,有什么功能特性(翻译)
  • .NET CORE 3.1 集成JWT鉴权和授权2
  • .net core 6 集成和使用 mongodb
  • .net FrameWork简介,数组,枚举
  • .NET MVC第五章、模型绑定获取表单数据
  • .net 调用php,php 调用.net com组件 --
  • .NET 同步与异步 之 原子操作和自旋锁(Interlocked、SpinLock)(九)
  • .net 无限分类
  • .Net8 Blazor 尝鲜
  • .net连接MySQL的方法
  • /3GB和/USERVA开关