mybatis 提供的逆向工程
生成实体bean,映射文件,DAO接口
1.项目根目录下创建GeneratorMapper.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>
<!-- 指定连接数据库的 JDBC 驱动包所在位置,指定到你本机的完整路径 -->
<classPathEntry location="F:\mysql-connector-java-5.1.32.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/mydb1"
userId="root"
password="1234">
</jdbcConnection>
<!-- 生成 model 类,targetPackage 指定 model 类的包名, targetProject 指定
生成的 model 放在 eclipse 的哪个工程下面-->
<javaModelGenerator targetPackage="com.example.model"
targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="false" />
</javaModelGenerator>
<!-- 生成 MyBatis 的 Mapper.xml 文件,targetPackage 指定 mapper.xml 文件的
包名, targetProject 指定生成的 mapper.xml 放在 eclipse 的哪个工程下面 -->
<sqlMapGenerator targetPackage="com.example.mapper"
targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 生成 MyBatis 的 Mapper 接口类文件,targetPackage 指定 Mapper 接口类的包
名, targetProject 指定生成的 Mapper 接口放在 eclipse 的哪个工程下面 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.example.mapper" 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>
2.在pom.xml下添加
<!--mybatis 代码自动生成插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.6</version>
<configuration>
<!--配置文件的位置-->
<configurationFile>GeneratorMapper.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
springboot集成mybatis
mapper
import com.example.model.Student;
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);
}
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.StudentMapper">
<!--定义的结果集对象-->
<resultMap id="BaseResultMap" type="com.example.model.Student">
<!--result:除了主键以外的字段-->
<!--id标签只能修饰主键字段-->
<!--
column数据库中的字段名称
property 映射对象的属性名称
jdbcType 列在数据库中字段的类型(可以省略不写)
-->
<!--resultMap的作用:
1.当数据库中的字段名称与实体类对象的属性名不一致时,可以进行转换
2.当前查询的结果没有对应一个表的时候,可以自动逸一个结果集-->
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="age" jdbcType="INTEGER" property="age" />
</resultMap>
<!--sql语句片段,将公共的部分抽取出来-->
<sql id="Base_Column_List">
id, name, age
</sql>
<!--下面的parameterType可写可不写-->
<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.example.model.Student">
insert into t_student (id, name, age
)
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
)
</insert>
<insert id="insertSelective" parameterType="com.example.model.Student">
/*suffixOverrides去除多余的字符(,)*/
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.example.model.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.example.model.Student">
update t_student
set name = #{name,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
service
package com.example.service;
import com.example.model.Student;
public interface StudentService {
Student queryStudentById(Integer id); //根据学生id查询信息
}
serviceImpl
package com.example.service.impl;
import com.example.mapper.StudentMapper;
import com.example.model.Student;
import com.example.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);
}
}
controller
package com.example.web;
import com.example.model.Student;
import com.example.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;
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>012-mybatis</artifactId>
<version>0.0.1</version>
<name>012-mybatis</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<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>
</dependency>
<!--MyBatis整合SpringBoot框架的起步依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.xmlunit</groupId>
<artifactId>xmlunit-core</artifactId>
</dependency>
</dependencies>
<build>
<!--手动指定文件夹为resources-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!--mybatis 代码自动生成插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.6</version>
<configuration>
<!--配置文件的位置-->
<configurationFile>GeneratorMapper.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
</project>
Application
package com.example;
import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication //开启spring的配置
@MapperScan(basePackages = "com.example.mapper")//开启扫描Mapper接口的包以及子目录(相当于一个一个添加)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
application.properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=//localhost:3306/mydb1?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=1234
SpringBoot支持事务
事务也叫做一个完整的业务
事务只跟DML语句有关系:增删改
在service层业务上面加上注解@Transactional
@Service
public class StudenrServiceImpl implements StudenrService {
@Autowired
private StudentMapper studentMapper;
@Transactional
@Override
public int updateStudentById(Student student) {
int a=studentMapper.updateByPrimaryKeySelective(student);
int i=10/0;
return 0;
}
}
可以在Application上加上@EnableTransactionManagement (可选项,之前会加,现在可以不加?)
注意
-
如果数据库中由多个单词构成,通过mybatis逆向工程生成的对象属性名会按照驼峰命名法规则生成属性名称
其中:数据库中字段名称由多个单词构成的时候必须使用_下划线分隔
user_name -> userName
product_type -> productType
username ->username
userName ->username
-
编译完成之后resources里面的文件会到类路径下
我的理解是:src就是类路径,src之下的java、resources文件夹里面文件被读取之后编译到target下的classes之下
除了java中的除了.java外的文件需要让idea知道位置,否则就找不到
所以在pom中指定resources也好,直接搬家到resources也好都是为了这个目的
就是说java文件夹里面的不是.java的都不会编译,但是resources里面的所有文件都会被编译到target
-
mybatis逆向工程生成的xml文件中sql语句中的if判断语句中不需要判断空值是因为用的是 包装类型
-
关于Mapper映射文件存放的位置的写法有以下两种:
-
1.将Mapper接口和Mapper映射文件存放到src/main/java的同一个目录下,还需要在pom文件中手动指定资源文件夹的路径resources
-
<!--手动指定文件夹为resources--> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources>
-
2.将Mapper接口(src/main/java)和Mapper映射文件(resources下)分开存放,在springboot核心配置文件(application.properties)中指定mapper映射文件存放的位置
-
# 指定Mybatis映射文件的路径 mybatis.mapper-locations=classpath:mapper/*.xml
-
-
@Mapper需要在每一个Mapper接口类上添加,作用扫描dao接口
@Mapper public interface StudentMapper { }
-
@MapperScan是在SpringBoot启动入口类上添加,它是扫描所有的包
@SpringBootApplication //开启spring的配置 @MapperScan(basePackages = "com.example.mapper")//开启扫描Mapper接口的包以及子目录(相当于一个一个添加) public class Application { }
放,在springboot核心配置文件(application.properties)中指定mapper映射文件存放的位置
-
# 指定Mybatis映射文件的路径 mybatis.mapper-locations=classpath:mapper/*.xml
-
@Mapper需要在每一个Mapper接口类上添加,作用扫描dao接口
@Mapper public interface StudentMapper { }
-
@MapperScan是在SpringBoot启动入口类上添加,它是扫描所有的包
@SpringBootApplication //开启spring的配置 @MapperScan(basePackages = "com.example.mapper")//开启扫描Mapper接口的包以及子目录(相当于一个一个添加) public class Application { }