springboot整合mybatis

本文详细介绍了如何在Spring Boot项目中集成MyBatis,包括依赖配置、数据源设置、逆向工程生成Mapper和POJO,以及使用PageHelper实现分页功能。此外,还讲解了如何利用MyBatis Generator自动化生成代码,以及事务管理的最佳实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对应的github地址https://github.com//abel533/Mybatis-Spring-boot
相关的依赖

<!-- java最好的数据库连接池,由阿里巴巴提供 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.10</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.1.10</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis.generator</groupId>
			<artifactId>mybatis-generator-core</artifactId>
			<version>1.3.5</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<!--mybatis -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.1</version>
		</dependency>
		<!--mapper -->
		<dependency>
			<groupId>tk.mybatis</groupId>
			<artifactId>mapper-spring-boot-starter</artifactId>
			<version>1.2.4</version>
		</dependency>
		<!--pagehelper -->
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper-spring-boot-starter</artifactId>
			<version>1.2.3</version>
		</dependency>

同时在配置加入如下

restart.include.mapper=/mapper-[\\w-\\.]+jar
restart.include.pagehelper=/pagehelper-[\\w-\\.]+jar

原因在于:
在这里插入图片描述
其他配置:

#mybatis
mybatis.type-aliases-package=com.example.pojo
mybatis.mapper-locations=classpath:mapper/*.xml

#mapper
#mappers 多个接口时逗号隔开
mapper.mappers=tk.mybatis.springboot.util.MyMapper
mapper.not-empty=false
mapper.identity=MYSQL

#分页插件的配置
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql

#配置数据源,使用阿里巴巴的druid数据源
spring.datasource.url=jdbc:mysql://localhost:3306/springboot
spring.datasource.username=root
spring.datasource.password=12345
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.initial-size=1
spring.datasource.druid.min-idle=1
spring.datasource.druid.max-active=20
spring.datasource.druid.test-on-borrow=true
spring.datasource.druid.stat-view-servlet.allow=true

使用generatorConfig生成mapper以及pojo(即逆向工程)
解释一下逆向工程就是通过配置文件根据数据库表的结构生成对应实体类跟跟对应的mapper
在项目出添加如下内容的配置文件
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <context id="MysqlContext" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>

        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/springboot"
                        userId="root"
                        password="12345">
        </jdbcConnection>

        <!-- 对于生成的pojo所在包 -->
        <javaModelGenerator targetPackage="com.example.pojo" targetProject="src/main/java"/>

		<!-- 对于生成的mapper所在目录 -->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/>

		<!-- 配置mapper对应的java映射 -->
        <javaClientGenerator targetPackage="com.example.mapper" targetProject="src/main/java"
                             type="XMLMAPPER"/>


		<table tableName="person"></table>
		 
    </context>
</generatorConfiguration>

在编写如下执行类

package com.example.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

public class GeneratorDisplay {

	public void generator() throws Exception{

		List<String> warnings = new ArrayList<String>();
		boolean overwrite = true;
		//指定 逆向工程配置文件
		File configFile = new File("generatorConfig.xml"); 
		ConfigurationParser cp = new ConfigurationParser(warnings);
		Configuration config = cp.parseConfiguration(configFile);
		DefaultShellCallback callback = new DefaultShellCallback(overwrite);
		MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
				callback, warnings);
		myBatisGenerator.generate(null);

	} 
	
	public static void main(String[] args) throws Exception {
		try {
			GeneratorDisplay generatorSqlmap = new GeneratorDisplay();
			generatorSqlmap.generator();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}

执行后结果:
首先看看数据库的表的结构
在这里插入图片描述
对应生产的实体类:

package com.example.pojo;

public class Person {
    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column person.name
     *
     * @mbg.generated Wed May 01 09:14:56 CST 2019
     */
    private String name;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column person.age
     *
     * @mbg.generated Wed May 01 09:14:56 CST 2019
     */
    private Integer age;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column person.sex
     *
     * @mbg.generated Wed May 01 09:14:56 CST 2019
     */
    private String sex;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column person.occupation
     *
     * @mbg.generated Wed May 01 09:14:56 CST 2019
     */
    private String occupation;

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column person.name
     *
     * @return the value of person.name
     *
     * @mbg.generated Wed May 01 09:14:56 CST 2019
     */
    public String getName() {
        return name;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column person.name
     *
     * @param name the value for person.name
     *
     * @mbg.generated Wed May 01 09:14:56 CST 2019
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column person.age
     *
     * @return the value of person.age
     *
     * @mbg.generated Wed May 01 09:14:56 CST 2019
     */
    public Integer getAge() {
        return age;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column person.age
     *
     * @param age the value for person.age
     *
     * @mbg.generated Wed May 01 09:14:56 CST 2019
     */
    public void setAge(Integer age) {
        this.age = age;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column person.sex
     *
     * @return the value of person.sex
     *
     * @mbg.generated Wed May 01 09:14:56 CST 2019
     */
    public String getSex() {
        return sex;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column person.sex
     *
     * @param sex the value for person.sex
     *
     * @mbg.generated Wed May 01 09:14:56 CST 2019
     */
    public void setSex(String sex) {
        this.sex = sex;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column person.occupation
     *
     * @return the value of person.occupation
     *
     * @mbg.generated Wed May 01 09:14:56 CST 2019
     */
    public String getOccupation() {
        return occupation;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column person.occupation
     *
     * @param occupation the value for person.occupation
     *
     * @mbg.generated Wed May 01 09:14:56 CST 2019
     */
    public void setOccupation(String occupation) {
        this.occupation = occupation;
    }
}

对应生产的Mapper

package com.example.mapper;

import com.example.pojo.Person;
import java.util.List;

public interface PersonMapper {
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table person
     *
     * @mbg.generated Wed May 01 09:14:56 CST 2019
     */
    int insert(Person record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table person
     *
     * @mbg.generated Wed May 01 09:14:56 CST 2019
     */
    List<Person> selectAll();
}

对应生产的mapper的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.example.mapper.PersonMapper">
  <resultMap id="BaseResultMap" type="com.example.pojo.Person">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Wed May 01 09:14:56 CST 2019.
    -->
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="age" jdbcType="INTEGER" property="age" />
    <result column="sex" jdbcType="VARCHAR" property="sex" />
    <result column="occupation" jdbcType="VARCHAR" property="occupation" />
  </resultMap>
  <insert id="insert" parameterType="com.example.pojo.Person">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Wed May 01 09:14:56 CST 2019.
    -->
    insert into person (name, age, sex, 
      occupation)
    values (#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, #{sex,jdbcType=VARCHAR}, 
      #{occupation,jdbcType=VARCHAR})
  </insert>
  <select id="selectAll" resultMap="BaseResultMap">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Wed May 01 09:14:56 CST 2019.
    -->
    select name, age, sex, occupation
    from person
  </select>
</mapper>

整合mybatis-pagehelper实现分页
这个分页插件简单暴力,只需要在select语句前面加上

// 第一个参数为开始页,第二个参数为一页显示多少内容
 PageHelper.startPage(startPage, showPageNumber)

数据库数据:
在这里插入图片描述
代码:

Page page = PageHelper.startPage(0, 3);
    	List<com.example.pojo.Person> list = pm.selectAll();
    	for(int i = 0,length = list.size() ; i < length ; i++) {
    		System.out.println(list.get(i).getName());
    	}
    	System.out.println(page);

结果
在这里插入图片描述
注意喽!不要被这个插件的page骗了,你看看如下代码:

  PageHelper.startPage(page, pageSize);
		List<SysUser> userList =  userMapperCustom.queryUser();
		System.out.println(userList);

然后结果呢:
在这里插入图片描述
是不是很奇怪!但是它又没有对应的get方法
在这里插入图片描述
再加入如下代码

for(int i = 0,length = userList.size();i < length ;i++) {
			System.out.println(userList.get(i));
		}

结果:
在这里插入图片描述
看看官方如何解释,在官方的demo中我发现
在这里插入图片描述
再看看page源码发现它继承了ArrayList且重写了toString方法
在这里插入图片描述
在这里插入图片描述
这也就是解释了上面原因。
如果需要获得分页信息可以

Page p =  PageHelper.startPage(page, pageSize);
Page p1 = (Page)userList;
// 推荐这个
PageInfo pi = new PageInfo(userList);

为什么推荐了PageInfo,因为我之前用了前面的在ajax遇到了坑。你可以看看如下例子:

public class B extends ArrayList{
    private int b1;

	public int getB1() {
		return b1;
	}

	public void setB1(int b1) {
		this.b1 = b1;
	}

	@Override
	public String toString() {
		return "B [b1=" + b1 + "]";
	}
}
public Map<String,Object> retrunAjax(){
		B b = new B();
	    b.add('a');
	    b.add('b');
		b.setB1(2);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("b",b);
		return map;

ajax访问代码:

$.ajax({
		url: "/mybatis/a",
		type: "POST",
		async: false,
		success: function(result) {
			console.log(result);
		},
		
	});

结果:
在这里插入图片描述
也就是说你不用pageInfo在ajax是得不到page的分页内容,只能获得page内的数据
事务的添加
只需要在需要的方法上加入即可
@Transactional(propagation = Propagation.REQUIRED)
一般增删改用REQUIRED就行了,对于查询一般使用support
REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。这是最常见的选择。
support:支持当前事务,如果当前没有事务,就以非事务方式执行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值