8.mybatis与SpringBoot集成

本来想写一篇关于ssm集成方面的文章,但是考虑到现在基本上使用的是SpringBoot框架进行开发,因此直接写SpringBoot框架集成mybatis更好。

一、创建maven项目并导入相应的包

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.qiu</groupId>
    <artifactId>mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
    <!-- springboot 热部署插件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- springboot集成mybatis需要的包 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.26</version>
        </dependency>
        <!-- 分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.1.6</version>
        </dependency>
        <!-- alibaba的druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.0</version>
        </dependency>
        <!-- mybatis代码生成器相关的包 -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

        </plugins>
    </build>
</project>

二、mysql中创建数据表

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) DEFAULT NULL,
  `user_password` varchar(255) DEFAULT NULL,
  `user_email` varchar(255) DEFAULT NULL,
  `user_info` varchar(255) DEFAULT NULL,
  `head_img` varchar(255) DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

三、使用代码生成器自动生成相关的entity、xxxMapper和xxxMapper映射文件。

参照之前的mybatis代码生成器使用博客:https://www.jianshu.com/p/b6a0ac3ba17c

  • 在生成的xxxMapper接口上加上@Mapper注解,否则Springboot扫描不到该接口,会报错误。然后自定义一个方法
@Mapper
public interface UserMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
    //自定义一个方法
    List<User>findAllUser();
}
  • 生成的model类
public class User {
    private Integer id;
    private String userName;
    private String userPassword;
    private String userEmail;
    private String userInfo;
    private String headImg;
    private Date createTime;
    ...省略getter/setter
  • 把UserMapper.xml文件放在src/main/resource/mapper目录下面,然后在UserMapper.xml文件中添加自定义方法
<?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.qiu.mapper.UserMapper">
  <resultMap id="BaseResultMap" type="com.qiu.model.User">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="user_name" jdbcType="VARCHAR" property="userName" />
    <result column="user_password" jdbcType="VARCHAR" property="userPassword" />
    <result column="user_email" jdbcType="VARCHAR" property="userEmail" />
    <result column="user_info" jdbcType="VARCHAR" property="userInfo" />
    <result column="head_img" jdbcType="VARCHAR" property="headImg" />
    <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
  </resultMap>
  <sql id="Base_Column_List">
    id, user_name, user_password, user_email, user_info, head_img, create_time
  </sql>
   <!-- 增加自己增加的方法 -->
  <select id="findAllUser" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List"></include>
    from user
  </select>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from user
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from user
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.qiu.model.User">
    insert into user (id, user_name, user_password, 
      user_email, user_info, head_img, 
      create_time)
    values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{userPassword,jdbcType=VARCHAR}, 
      #{userEmail,jdbcType=VARCHAR}, #{userInfo,jdbcType=VARCHAR}, #{headImg,jdbcType=VARCHAR}, 
      #{createTime,jdbcType=TIMESTAMP})
  </insert>
  <insert id="insertSelective" parameterType="com.qiu.model.User">
    insert into user
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="userName != null">
        user_name,
      </if>
      <if test="userPassword != null">
        user_password,
      </if>
      <if test="userEmail != null">
        user_email,
      </if>
      <if test="userInfo != null">
        user_info,
      </if>
      <if test="headImg != null">
        head_img,
      </if>
      <if test="createTime != null">
        create_time,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
      <if test="userName != null">
        #{userName,jdbcType=VARCHAR},
      </if>
      <if test="userPassword != null">
        #{userPassword,jdbcType=VARCHAR},
      </if>
      <if test="userEmail != null">
        #{userEmail,jdbcType=VARCHAR},
      </if>
      <if test="userInfo != null">
        #{userInfo,jdbcType=VARCHAR},
      </if>
      <if test="headImg != null">
        #{headImg,jdbcType=VARCHAR},
      </if>
      <if test="createTime != null">
        #{createTime,jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.qiu.model.User">
    update user
    <set>
      <if test="userName != null">
        user_name = #{userName,jdbcType=VARCHAR},
      </if>
      <if test="userPassword != null">
        user_password = #{userPassword,jdbcType=VARCHAR},
      </if>
      <if test="userEmail != null">
        user_email = #{userEmail,jdbcType=VARCHAR},
      </if>
      <if test="userInfo != null">
        user_info = #{userInfo,jdbcType=VARCHAR},
      </if>
      <if test="headImg != null">
        head_img = #{headImg,jdbcType=VARCHAR},
      </if>
      <if test="createTime != null">
        create_time = #{createTime,jdbcType=TIMESTAMP},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.qiu.model.User">
    update user
    set user_name = #{userName,jdbcType=VARCHAR},
      user_password = #{userPassword,jdbcType=VARCHAR},
      user_email = #{userEmail,jdbcType=VARCHAR},
      user_info = #{userInfo,jdbcType=VARCHAR},
      head_img = #{headImg,jdbcType=VARCHAR},
      create_time = #{createTime,jdbcType=TIMESTAMP}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

四、创建一个配置类,并配置好分页插件

@Configuration
public class MybatisConfig {
    @Bean
    public PageHelper pageHelper() {
        PageHelper pageHelper=new PageHelper();
        Properties properties=new Properties();
//该参数默认为false ,设置为true时,会将RowBounds第一个参数offset当
//成pageNum页码使用,和startPage中的pageNum效果一样
        properties.setProperty("offsetAsPageNum","true");
//该参数默认为false,设置为true时,使用RowBounds分页会进行count查询 
        properties.setProperty("rowBoundsWithCount","true");
//分页参数合理化,默认false禁用
        properties.setProperty("reasonable","true");
//配置mysql数据库方言
        properties.setProperty("dialect","mysql");
        pageHelper.setProperties(properties);
        return pageHelper;
    }
}

五、创建UserService和UserServiceImp

  • UserService接口
public interface UserService {
    int addUser(User user);
    List<User> findAllUser(int pageNum, int pageSize);
}
  • UserServiceImp实现类
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public int addUser(User user) {
        return userMapper.insert(user);
    }
    @Override
    public List<User> findAllUser(int pageNum, int pageSize) {
        //进行分页,必须在mybatis从数据库获取数据之前
        PageHelper.startPage(pageNum, pageSize);
        List<User> findAllUser = userMapper.findAllUser();
        return findAllUser;
    }
}

六、创建controller,执行web相关操作

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/addUser")
    public String addUser() {
        User user=new User();
        user.setCreateTime(new Date());
        user.setUserEmail("111@qq.com");
        user.setUserInfo("hahah");
        user.setUserName("qiu");
        user.setUserPassword("1233");
        int addUser = userService.addUser(user);
        return addUser!=0?"插入成功":"插入失败";
    }
    @RequestMapping("/getUserByPage")
//默认pageNum为1,pageSize为1
    public String getUsersByPage(@RequestParam(value="pageNum",defaultValue="1")Integer pageNum,
     @RequestParam(value="pageSize",defaultValue="2")Integer pageSize) {
         List<User> list = userService.findAllUser(pageNum, pageSize);
         list.forEach(System.out::println);
         return list.toString();
    }

七、创建springboot启动类

@SpringBootApplication
public class SpringbootMybatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybatisApplication.class, args);
    }
}

八、在classpath目录下面创建SpringBoot配置文件application.properties

#tomcat端口
server.port=8082
#datasource
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

# 数据库访问配置
# 主数据源,默认的
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
# 配置获取连接等待超时的时间
spring.datasource.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 'x'
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters=stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.s
tat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
spring.datasource.useGlobalDataSourceStat=true

#mybatis相关
#别名
mybatis.type-aliases-package=com.qiu.model
#映射配置文件位置
mybatis.mapper-locations=classpath:mapper/*.xml

九、启动SpringBoot项目并进行访问

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,406评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,732评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,711评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,380评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,432评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,301评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,145评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,008评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,443评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,649评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,795评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,501评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,119评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,731评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,865评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,899评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,724评论 2 354

推荐阅读更多精彩内容

  • 1 Mybatis入门 1.1 单独使用jdbc编程问题总结 1.1.1 jdbc程序 上边使...
    哇哈哈E阅读 3,306评论 0 38
  • 开罗 午夜里,我独自在偌大的房间里辗转难眠。窗外稀稀疏疏的蛐蛐蝈蝈演奏曲,不间断地从白色的百叶窗的夹缝里钻进来。空...
    修墨68阅读 345评论 0 1
  • 前些天看了一篇谈论自由意志的公号文章,其中讲到了神经科学论的实验研究引发的对于是否存在自由意志的怀疑,并且用另一个...
    YousoBlind_9f1f阅读 537评论 0 1
  • “把金钱当做某种行为的外部奖励时,行为主体就失去了对这项活动的内在兴趣"奖励只能带来短期的爆发,就像是少量咖啡因只...
    榛果Latte阅读 215评论 0 1
  • 句子:“自己思考原本就是件很快乐的事情,而教别人思考则是学习思考,锻炼思考的最好方法。” “只有学会真正地思考,才...
    不加奶糖的咖啡阅读 275评论 2 1