SpringBoot 整合 Mybatis

Spring Boot 更多干货 SpringBoot系列目录

项目目录结构,创建的model层就没放一起,以JAR形式引入

1、创建SQL表

CREATE TABLE t_user(
  id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  name CHAR(100) NOT NULL ,
  age INT NOT NULL 
) ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;

2、在springboot项目引入 自动构建 generator 依赖 , 其他基础 boot依赖就不列举出来了

<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			<!-- mybatis generator 自动生成代码插件 -->
			<plugin>
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.3.2</version>
				<configuration>
					<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
					<overwrite>true</overwrite>
					<verbose>true</verbose>
				</configuration>
			</plugin>
		</plugins>
	</build>

在使用项目中加入mybatis依赖

        <!-- spring-boot整合mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        
        <!-- mybatis的分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.8</version>
        </dependency>

在springboot项目的资源文件夹目录下创建generator目录,并新建 generatorConfig.xml 文件,内容如下:

<?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>
    <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
    <classPathEntry  location="C:\Users\Administrator\.m2\repository\mysql\mysql-connector-java\5.1.41\mysql-connector-java-5.1.41.jar"/>
    <context id="DB2Tables"  targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--数据库链接URL,用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/test" userId="root" password="123456">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成模型的包名和位置-->
        <javaModelGenerator targetPackage="com.leopard.model" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 生成映射文件的包名和位置-->
        <sqlMapGenerator targetPackage="com.leopard.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!-- 生成DAO的包名和位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.leopard.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
        <table tableName="t_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>


3、配置好自己的本地路径后,运行maven 命令

mybatis-generator:generate

随后可以看到自动生成好的 dao、service、mapper文件,这里我把文件移动到自己想存放的位置,不一定要跟生成的一样

4、配置项目的 application.properties , 内容如下。


server.name=leopard-admin
server.port=8081
server.tomcat.uri-encoding=utf-8
#session失效时间
server.session-timeout=30


#数据源
spring.datasource.driver-class-name= com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = 123456
spring.datasource.maxActive = 20
spring.datasource.initialSize = 1
spring.datasource.maxWait = 60000
spring.datasource.minIdle = 1
spring.datasource.timeBetweenEvictionRunsMillis = 60000
spring.datasource.minEvictableIdleTimeMillis = 300000
spring.datasource.validationQuery = select 1
spring.datasource.poolPreparedStatements = true
spring.datasource.maxOpenPreparedStatements = 20

## 该配置节点为独立的节点,容易将这个配置放在spring的节点下,导致配置无法被识别
#注意:一定要对应mapper映射xml文件的所在路径
mybatis.mapper-locations = classpath*:com/leopard/admin/mapper/*.xml
# 注意:对应实体类的路径
mybatis.type-aliases-package = com.leopard.model

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

现在可以查看下生成的 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.leopard.admin.dao.UserMapper" >
  <resultMap id="BaseResultMap" type="com.leopard.model.User" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="name" property="name" jdbcType="CHAR" />
    <result column="age" property="age" jdbcType="INTEGER" />
  </resultMap>
  <sql id="Base_Column_List" >
    id, name, age
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from t_user
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from t_user
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.leopard.model.User" >
    insert into t_user (id, name, age)
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=CHAR}, #{age,jdbcType=INTEGER})
  </insert>
  <insert id="insertSelective" parameterType="com.leopard.model.User" >
    insert into t_user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="name != null" >
        name,
      </if>
      <if test="age != null" >
        age,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="name != null" >
        #{name,jdbcType=CHAR},
      </if>
      <if test="age != null" >
        #{age,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.leopard.model.User" >
    update t_user
    <set >
      <if test="name != null" >
        name = #{name,jdbcType=CHAR},
      </if>
      <if test="age != null" >
        age = #{age,jdbcType=INTEGER},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.leopard.model.User" >
    update t_user
    set name = #{name,jdbcType=CHAR},
      age = #{age,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

生成的dao接口 , 注意 要加上 @Mapper

package com.leopard.admin.dao;

import org.apache.ibatis.annotations.Mapper;

import com.leopard.model.User;

@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);
}

手动新建接口 UserService 和实现类 UserServiceImpl

package com.leopard.admin.service;

public interface UserService {

	public long addUser(String name , int age);
}
package com.leopard.admin.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.leopard.admin.dao.UserMapper;
import com.leopard.admin.service.UserService;
import com.leopard.model.User;

@Service
public class UserServiceImpl implements UserService{
	
	@Autowired
	private UserMapper userMapper;

	@Override
	public long addUser(String name, int age) {
		
		User user = new User();
		user.setName(name);
		user.setAge(age);
		return userMapper.insertSelective(user);
	}

}

控制层 UserController 

package com.leopard.admin.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.leopard.admin.base.Message;
import com.leopard.admin.service.impl.UserServiceImpl;

@RestController
@RequestMapping(value="/user")
public class UserController {

	@Autowired
	private UserServiceImpl userServiceImpl;
	
	
	@RequestMapping(value = "/addUser")
	public Message addUser(String name , int age){
		
		long result = userServiceImpl.addUser(name, age);
		int code = (int) result;
		return new Message(code , "success");
	}
	
}

启动类 AdminApplication

package com.leopard.admin.application;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableAsync
@ComponentScan(basePackages = { "com.leopard.admin"})
@MapperScan(basePackages = { "com.leopard.admin.dao" })
public class AdminApplication extends SpringBootServletInitializer {

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

}

5、启动后,访问测试

http://localhost:8081/user/addUser?name="张三"&age=14

成功效果 

 

异常:

Invalid bound statement (not found): com.leopard.UserMapper.insertSelective

解决方案:  https://blog.csdn.net/qq_40212930/article/details/91356013

https://blog.csdn.net/CoderTnT/article/details/80593723

 

Cannot determine embedded database driver class for database type NONE

解决方案: https://blog.csdn.net/Master_Shifu_/article/details/80420099  网上找了,这个真的很有效 尚未理解

<dependency>
        <groupId>com.h2database</groupId> 
        <artifactId>h2</artifactId>
        <scope>runtime</scope> 
</dependency>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值