文章目录:
1.3 GeneratorMapper.xml(配置MyBatis逆向工程核心文件)
1.3.2 StudentMapper、StudentMapper.xml
1.5 SpringBoot核心配置文件、SpringBoot项目启动入口类
2.使用@MapperScan注解集成MyBatis(将mapper接口和映射文件分开)
1.使用@Mapper注解集成MyBatis
1.1 前期准备工作
首先我们需要准备一个数据库、一张表,用作测试。
CREATE DATABASE springboot; USE springboot; DROP TABLE IF EXISTS t_student; CREATE TABLE t_student ( id int(10) NOT NULL AUTO_INCREMENT, name varchar(20) NULL , age int(10) NULL , PRIMARY KEY (id) )ENGINE = INNODB DEFAULT CHARSET = utf8; INSERT INTO t_student(name,age) VALUES ('zhangsan',25); INSERT INTO t_student(name,age) VALUES ('lisi',28); INSERT INTO t_student(name,age) VALUES ('wangwu',23); INSERT INTO t_student(name,age) VALUES ('Tom',21); INSERT INTO t_student(name,age) VALUES ('Jack',18); INSERT INTO t_student(name,age) VALUES ('Lucy',27); INSERT INTO t_student(name,age) VALUES ('xiaosong',21);
1.2 pom.xml
由于集成的是MyBatis,肯定要使用数据库,所以需要添加的两个依赖项就是 mysql驱动、mybatis集成springboot的起步依赖。
同时在 build 标签下,手动指定文件夹为resources,以及添加mybatis代码自动生成插件。
<dependencies> <!-- SpringBoot框架web项目起步依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MySQL驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- MyBatis整合SpringBoot框架的起步依赖 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency> </dependencies> <build> <!-- 手动指定文件夹为resources --> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> <plugins> <!--mybatis 代码自动生成插件--> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.7</version> <configuration> <!--配置文件的位置--> <configurationFile>GeneratorMapper.xml</configurationFile> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin> <!-- SpringBoot项目编译打包的插件 --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
1.3 GeneratorMapper.xml(配置MyBatis逆向工程核心文件)
由于在未来的真实项目开发过程中,可能会涉及到很多张表、很多的dao接口、dao接口对应的mapper文件,那么这些文件我们一一编写就会显得比较麻烦,而且写来写去没什么意义,所以这里我们采用 MyBatis逆向工程来直接生成对应的实体类、dao、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> <!-- 指定连接数据库的 JDBC 驱动包所在位置,指定到你本机的完整路径 --> <classPathEntry location="E:\mysql-connector-java-5.1.9.jar"/> <!-- 配置 table 表信息内容体,targetRuntime 指定采用 MyBatis3 的版本 --> <context id="tables" targetRuntime="MyBatis3"> <!-- 抑制生成注释,由于生成的注释都是英文的,可以不让它生成 --> <commentGenerator> <property name="suppressAllComments" value="true"/> </commentGenerator> <!-- 配置数据库连接信息 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/springboot" userId="root" password="12345678"> </jdbcConnection> <!-- 生成 entity 类,targetPackage 指定 entity 类的包名, targetProject指定生成的 entity 放在 IDEA 的哪个工程下面--> <javaModelGenerator targetPackage="com.songzihao.springboot.entity" targetProject="src\main\java"> <property name="enableSubPackages" value="false"/> <property name="trimStrings" value="false"/> </javaModelGenerator> <!-- 生成 MyBatis 的 Mapper.xml 文件,targetPackage 指定 mapper.xml 文件的包名, targetProject 指定生成的 mapper.xml 放在 IDEA 的哪个工程下面 --> <sqlMapGenerator targetPackage="com.songzihao.springboot.dao" targetProject="src/main/java"> <property name="enableSubPackages" value="false"/> </sqlMapGenerator> <!-- 生成 MyBatis 的 Mapper 接口类文件,targetPackage 指定 Mapper 接口类的包名, targetProject 指定生成的 Mapper 接口放在 IDEA 的哪个工程下面 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.songzihao.springboot.dao" targetProject="src/main/java"> <property name="enableSubPackages" value="false"/> </javaClientGenerator> <!-- 数据库表名及对应的 Java 模型类名 --> <table tableName="t_student" domainObjectName="Student" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"/> </context> </generatorConfiguration>
在当前项目的maven工程里,选择Plugins插件中的mybatis-generator:generate,即可生成entity包下的实体类、dao包下的接口、mapper文件。
1.3.1 Student实体类
package com.songzihao.springboot.entity; public class Student { private Integer id; private String name; private Integer age; //getter and setter }
1.3.2 StudentMapper、StudentMapper.xml
这两个文件中的代码并不是我们自己写的,而是通过mybatis逆向工程自动生成的!!!(真的强)
package com.songzihao.springboot.dao; import com.songzihao.springboot.entity.Student; import org.apache.ibatis.annotations.Mapper; //扫描dao接口到spring容器 @Mapper public interface StudentMapper { int deleteByPrimaryKey(Integer id); int insert(Student record); int insertSelective(Student record); Student selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Student record); int updateByPrimaryKey(Student record); }
<?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.songzihao.springboot.dao.StudentMapper"> <resultMap id="BaseResultMap" type="com.songzihao.springboot.entity.Student"> <id column="id" jdbcType="INTEGER" property="id" /> <result column="name" jdbcType="VARCHAR" property="name" /> <result column="age" jdbcType="INTEGER" property="age" /> </resultMap> <sql id="Base_Column_List"> id, name, age </sql> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from t_student where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from t_student where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.songzihao.springboot.entity.Student"> insert into t_student (id, name, age) values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}) </insert> <insert id="insertSelective" parameterType="com.songzihao.springboot.entity.Student"> insert into t_student <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=VARCHAR}, </if> <if test="age != null"> #{age,jdbcType=INTEGER}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.songzihao.springboot.entity.Student"> update t_student <set> <if test="name != null"> name = #{name,jdbcType=VARCHAR}, </if> <if test="age != null"> age = #{age,jdbcType=INTEGER}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.songzihao.springboot.entity.Student"> update t_student set name = #{name,jdbcType=VARCHAR},age = #{age,jdbcType=INTEGER} where id = #{id,jdbcType=INTEGER} </update> </mapper>
1.4 service、controller
编写一下业务逻辑层和界面层的代码,这里只对查询方法做一个测试。
package com.songzihao.springboot.service; import com.songzihao.springboot.entity.Student; import org.springframework.stereotype.Service; /** * */ public interface StudentService { Student queryStudentById(Integer id); }
package com.songzihao.springboot.service.impl; import com.songzihao.springboot.dao.StudentMapper; import com.songzihao.springboot.entity.Student; import com.songzihao.springboot.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * */ @Service public class StudentServiceImpl implements StudentService { @Autowired private StudentMapper studentMapper; @Override public Student queryStudentById(Integer id) { return studentMapper.selectByPrimaryKey(id); } }
package com.songzihao.springboot.controller; import com.songzihao.springboot.entity.Student; import com.songzihao.springboot.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * */ @Controller public class StudentController { @Autowired private StudentService studentService; @RequestMapping(value = "/student") public @ResponseBody Object student(Integer id) { Student student=studentService.queryStudentById(id); return student; } }
1.5 SpringBoot核心配置文件、SpringBoot项目启动入口类
#配置内嵌Tomcat端口号 server.port=9090 #配置项目上下文根 server.servlet.context-path=/springboot #设置连接数据库的配置信息 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8 spring.datasource.username=root spring.datasource.password=12345678
package com.songzihao.springboot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
2.使用@MapperScan注解集成MyBatis(将mapper接口和映射文件分开)
其中数据库表、pom文件、逆向工程文件、实体类、service、controller 和上面第一个案例是一样的,这里就不再给出代码了。
不一样的地方是下面这些:👇👇👇
2.1 mapper接口、对应的mapper映射文件
注释掉之前的@Mapper注解,因为后面我们会在入口类中使用@MapperScan注解。
package com.songzihao.springboot.mapper; import com.songzihao.springboot.entity.Student; import org.apache.ibatis.annotations.Mapper; //@Mapper public interface StudentMapper { int deleteByPrimaryKey(Integer id); int insert(Student record); int insertSelective(Student record); Student selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Student record); int updateByPrimaryKey(Student record); }
因为 SpringBoot 不能自动编译接口映射的 xml 文件,还需要手动在 pom 文件中指定,所以有的公司直接将映射文件直接放到 resources 目录下.在 resources 目录下新建目录 mapper 存放映射文件,将StudentMapper.xml 文件移到 resources/mapper 目录下
这里的mapper映射文件和上面的案例虽然一样,但它存放的位置却改变了。
<?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.songzihao.springboot.mapper.StudentMapper"> <resultMap id="BaseResultMap" type="com.songzihao.springboot.entity.Student"> <id column="id" jdbcType="INTEGER" property="id" /> <result column="name" jdbcType="VARCHAR" property="name" /> <result column="age" jdbcType="INTEGER" property="age" /> </resultMap> <sql id="Base_Column_List"> id, name, age </sql> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from t_student where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from t_student where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.songzihao.springboot.entity.Student"> insert into t_student (id, name, age ) values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER} ) </insert> <insert id="insertSelective" parameterType="com.songzihao.springboot.entity.Student"> insert into t_student <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=VARCHAR}, </if> <if test="age != null"> #{age,jdbcType=INTEGER}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.songzihao.springboot.entity.Student"> update t_student <set> <if test="name != null"> name = #{name,jdbcType=VARCHAR}, </if> <if test="age != null"> age = #{age,jdbcType=INTEGER}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.songzihao.springboot.entity.Student"> update t_student set name = #{name,jdbcType=VARCHAR}, age = #{age,jdbcType=INTEGER} where id = #{id,jdbcType=INTEGER} </update> </mapper>
在 application.properties 配置文件中指定映射文件的位置,这个配置只有接口和映射文件不在同一个包的情况下,才需要指定。
#配置内嵌Tomcat端口号 server.port=9090 #配置项目上下文根 server.servlet.context-path=/springboot #设置连接数据库的配置信息 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8 spring.datasource.username=root spring.datasource.password=12345678 #指定MyBatis映射文件的路径 mybatis.mapper-locations=classpath:mapper/*.xml
2.2 启动入口类测试
在入口类的上方添加了@MapperScan注解,开启扫描mapper接口的包以及子目录。
package com.songzihao.springboot; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication //开启扫描mapper接口的包以及子目录 @MapperScan(basePackages = "com.songzihao.springboot.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }