使用MyBatis生成器:
MyBatis Generator(MBG)由XML配置文件驱动。配置文件会告知 MBG:
如何连接数据库
哪些对象需要被生成,以及如何生成它们
哪些数据表需要被利用来生成对象
MBG可生成三种文件:
Java Model Objects(.java)--------POJO
SQL Map Files(.xml)--------数据库查询映射
Java Client Objects(.java)--------DAO
使用MyBatis插件创建Dao、Mapper、实体类:
首先在pom.xml中添加插件:
<!--mybatis代码自动生成插件--> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.6</version> <configuration> <!--配置文件的位置:在项目的根目录下,和src平级的--> <configurationFile>GeneratorMapper.xml</configurationFile> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin>
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.7.1</version>
- <relativePath/> <!-- lookup parent from repository -->
- </parent>
- <groupId>com.bjpowernode</groupId>
- <artifactId>019-springboot-transactional</artifactId>
- <version>0.0.1-SNAPSHOT</version>
-
- <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.mybatis.spring.boot</groupId>
- <artifactId>mybatis-spring-boot-starter</artifactId>
- <version>2.2.2</version>
- </dependency>
-
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <!--mybatis代码自动生成插件-->
- <plugin>
- <groupId>org.mybatis.generator</groupId>
- <artifactId>mybatis-generator-maven-plugin</artifactId>
- <version>1.3.6</version>
- <configuration>
- <!--配置文件的位置:在项目的根目录下,和src平级的-->
- <configurationFile>GeneratorMapper.xml</configurationFile>
- <verbose>true</verbose>
- <overwrite>true</overwrite>
- </configuration>
- </plugin>
-
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
-
- </project>
再把GeneratorMapper.xml复制到项目的根目录下,中来跟src同级:
- <?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="D:\softwares\tools\mysql-connector-java-8.0.22.jar"/>
-
- <!-- 配置table表信息内容体,targetRuntime指定采用MyBatis3的版本 -->
- <context id="tables" targetRuntime="MyBatis3">
-
- <!-- 抑制生成注释,由于生成的注释都是英文的,可以不让它生成 -->
- <commentGenerator>
- <property name="suppressAllComments" value="true" />
- </commentGenerator>
-
- <!-- 配置数据库连接信息 -->
- <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
- connectionURL="jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8"
- userId="root"
- password="123456">
- <property name="nullCatalogMeansCurrent" value="true"/>
- </jdbcConnection>
-
- <!-- 生成model类,targetPackage指定model类的包名, targetProject指定生成的model放在eclipse的哪个工程下面-->
- <javaModelGenerator targetPackage="com.bjpowernode.model"
- targetProject="E:\course\SpringBoot\019-springboot-transactional\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="mapper" targetProject="src/main/resources">
- <property name="enableSubPackages" value="false" />
- </sqlMapGenerator>
-
- <!-- 生成MyBatis的Mapper接口类文件,targetPackage指定Mapper接口类的包名, targetProject指定生成的Mapper接口放在eclipse的哪个工程下面 -->
- <javaClientGenerator type="XMLMAPPER" targetPackage="com.bjpowernode.dao" targetProject="src/main/java">
- <property name="enableSubPackages" value="false" />
- </javaClientGenerator>
-
- <!-- 数据库表名及对应的Java模型类名 -->
- <table tableName="student" domainObjectName="Student"
- enableCountByExample="false"
- enableUpdateByExample="false"
- enableDeleteByExample="false"
- enableSelectByExample="false"
- selectByExampleQueryId="false"/>
-
-
- </context>
-
- </generatorConfiguration>
进行修改插件所需的配置文件的内容GenetatorMapper.xml:
MyBatis Generator : Table Configuration scheme.table matched more than one table
[WARNING] Table Configuration student matched more than one table (springdb..student,studentinfo..student,user..student,mybatis..student)
注意:如果生成有问题!!!
在使用生成器生成代码的时候遇到了这个错误, 现象就是某个类中出来了数据库表里面没有的字段,非常奇怪.
解决方法是在生成器的配置文件里的数据库连接地址(就是jdbcUrl)中添加这个参数:
nullCatalogMeansCurrent=true
大概就是这个样子:
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/security"
userId="root"
password="root">
<!--MySQL 8.x 需要指定服务器的时区-->
<property name="serverTimezone" value="UTC"/>
<!--MySQL 不支持 schema 或者 catalog 所以需要添加这个-->
<!--参考 : http://www.mybatis.org/generator/usage/mysql.html-->
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
使用Maven中的:双击就自动生成了对应的内容:
以下是自动生成的代码:
StudentMapper接口:
- package com.bjpowernode.dao;
-
- import com.bjpowernode.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);
- }
Student类:
- package com.bjpowernode.model;
-
- public class Student {
- private Integer id;
-
- private String name;
-
- private Integer age;
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public Integer getAge() {
- return age;
- }
-
- public void setAge(Integer age) {
- this.age = age;
- }
- }
StudentMapper.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.bjpowernode.dao.StudentMapper">
- <resultMap id="BaseResultMap" type="com.bjpowernode.model.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 student
- where id = #{id,jdbcType=INTEGER}
- </select>
- <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
- delete from student
- where id = #{id,jdbcType=INTEGER}
- </delete>
- <insert id="insert" parameterType="com.bjpowernode.model.Student">
- insert into student (id, name, age
- )
- values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
- )
- </insert>
- <insert id="insertSelective" parameterType="com.bjpowernode.model.Student">
- insert into 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.bjpowernode.model.Student">
- update 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.bjpowernode.model.Student">
- update student
- set name = #{name,jdbcType=VARCHAR},
- age = #{age,jdbcType=INTEGER}
- where id = #{id,jdbcType=INTEGER}
- </update>
- </mapper>
配置文件application.properties:
- #设置端口
- server.port=9002
- #上下文
- server.servlet.context-path=/mytrans
-
-
- #设置连接数据库 mysql驱动新版的驱动类
- spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
- #连接数据库的url ?后是连接数据库提供的参数 useUnicode:表示用的是useUnicode编码 characterEncoding:表示字符集 serverTimezone:表示时区 GMT:标准时区 8:表示加8小时,我们的时区跟标准时区差8小时
- spring.datasource.url=jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
- #数据库连接名字
- spring.datasource.username=root
- #数据库连接密码
- spring.datasource.password=123456
-
- #指定mapper文件的位置
- mybatis.mapper-locations=classpath:mapper/*.xml
-
- #指定mybatis的日志 将这个日志输出到控制台上
- mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
创建StudentService:
- package com.bjpowernode.service;
-
- import com.bjpowernode.model.Student;
-
- public interface StudentService {
- int addStudent(Student student);
-
- }
创建实现类StudentServiceImpl:在这里抛出了一个异常,事务会回滚,不会插入数据库
- package com.bjpowernode.service.impl;
-
- import com.bjpowernode.dao.StudentMapper;
- import com.bjpowernode.model.Student;
- import com.bjpowernode.service.StudentService;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
-
- import javax.annotation.Resource;
-
- @Service
- public class StudentServiceImpl implements StudentService {
-
- @Resource
- private StudentMapper studentDao;
-
- /*@Transactional :表示方法有事务支持
- * 默认:使用库的隔离级别,REQUIRED-传播行为 超时时间- -1
- * */
- @Transactional
- @Override
- public int addStudent(Student student) {
- System.out.println("业务方法addStudent");
- int rows = studentDao.insert(student);
- System.out.println("执行sql语句");
-
- //抛出一个运行时异常,目的是回滚事务
- int m=10/0;
-
-
- return rows;
- }
- }
创建控制类:StudentController:
- package com.bjpowernode.controller;
-
- import com.bjpowernode.model.Student;
- import com.bjpowernode.service.StudentService;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
-
- import javax.annotation.Resource;
-
- @Controller
- public class StudentController {
- @Resource //注解进行注入
- private StudentService service;
-
- @RequestMapping("/addStudent")
- @ResponseBody
- public String addStudent(String name,Integer age){
- Student s1=new Student();
- s1.setName(name);
- s1.setAge(age);
-
- int rows = service.addStudent(s1);
- return "添加学生:"+rows;
- }
- }
主启动类Application:加dao的扫描注解,启动项目
- package com.bjpowernode;
-
- import org.mybatis.spring.annotation.MapperScan;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.transaction.annotation.EnableTransactionManagement;
- /*@EnableTransactionManagement:启用事务管理器
- * 这个注解可以不加,但是最好加上
- * */
- @EnableTransactionManagement
- @SpringBootApplication
- @MapperScan(basePackages = "com.bjpowernode.dao") //注解让他扫描到Dao
- public class Application {
-
- public static void main(String[] args) {
- SpringApplication.run(Application.class, args);
- }
-
- }
浏览器输入数据:
控制台抛出了异常
把StudentServiceImpl:中的运行时异常注释掉,重新启动项目
//抛出一个运行时异常,目的是回滚事务 int m=10/0;
正常添加进去,查看数据库:数据库也添加成功
张强的id为5,中间少一个4,正是刚才出错的,刚才已经在数据库添加了数据,报异常了回滚,这条数据的操作撤销了,主键字段是逐条增长的,用过4了,就不能再用了,所以在添加我变为5