Intellij-Idea-中进行-Mybatis逆向工程

开篇Mybatis有个实用的功能就是逆向工程,能根据表结构反向生成实体类,这样能避免手工生成出错。市面上的教程大多都很老了,大部分都是针对mysql5的,以下为我执行mysql8时的经验。 引入工程这里使用的是maven包管理工具,在pom.xml添加以下配置,以引入mybatis.generator <build> <finalName>SpringMVCBasic</finalName> <!-- 添加mybatis-generator-maven-plugin插件 --> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin> </plugins> </build>配置文件在maven项目下的src/main/resources 目录下新建generatorConfig.xml和generator.properties文件 generator.properties jdbc.driverLocation=F:\\maven-repository\\mysql\\mysql-connector-java\\8.0.16\\mysql-connector-java-8.0.16.jarjdbc.driverClass=com.mysql.cj.jdbc.Driverjdbc.connectionURL=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8jdbc.userId=testjdbc.password=test123注意:1,generator.properties里面的jdbc.driverLocation指向是你本地maven库对应mysql-connector地址2,与老版本不同,这里driversClass为com.mysql.cj.jdbc.Driver 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> <!--导入属性配置--> <properties resource="generator.properties"></properties> <!--指定特定数据库的jdbc驱动jar包的位置(绝对路径)--> <classPathEntry location="${jdbc.driverLocation}"/> <context id="default" targetRuntime="MyBatis3"> <!-- optional,旨在创建class时,对注释进行控制 --> <commentGenerator> <!--是否去掉自动生成的注释 true:是--> <property name="suppressDate" value="true"/> <property name="suppressAllComments" value="true"/> </commentGenerator> <!--jdbc的数据库连接:驱动类、链接地址、用户名、密码--> <jdbcConnection driverClass="${jdbc.driverClass}" connectionURL="${jdbc.connectionURL}" userId="${jdbc.userId}" password="${jdbc.password}"> </jdbcConnection> <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制--> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类 targetPackage 指定生成的model生成所在的包名 targetProject 指定在该项目下所在的路径 --> <javaModelGenerator targetPackage="com.ifly.outsourcing.entity" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 --> <sqlMapGenerator targetPackage="mappers" targetProject="src/main/resources"> <property name="enableSubPackages" value="false"/> </sqlMapGenerator> <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码 type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.ifly.outsourcing.dao" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!-- 数据表进行生成操作 tableName:表名; domainObjectName:对应的DO --> <table tableName="user" domainObjectName="user" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> </table> </context></generatorConfiguration>注意:这里主要注意修改对应的javaModelGenerator ,sqlMapGenerator,javaClientGenerator 为自己的生成路径。以及添加自己的数据表。 ...

May 21, 2019 · 1 min · jiezi

由表生成代码mybatisgenerator入门

application.properties## mapper xml 文件地址mybatis.mapper-locations=classpath*:mapper/*Mapper.xml##数据库urlspring.datasource.url=jdbc:mysql://localhost:3306/shiro?characterEncoding=utf8&useSSL=false##数据库用户名spring.datasource.username=root##数据库密码spring.datasource.password=1234##数据库驱动spring.datasource.driver-class-name=com.mysql.jdbc.Driver#Mybatis Generator configuration#dao类和实体类的位置mybatis.project =src/main/java#mapper文件的位置mybatis.resources=src/main/resourcesgeneratorConfig.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> <!--执行generator插件生成文件的命令: call mvn mybatis-generator:generate -e --> <!-- 引入配置文件 --> <properties resource="application.properties"/> <!--classPathEntry:数据库的JDBC驱动,换成你自己的驱动位置 可选 --> <!--<classPathEntry location="D:\generator_mybatis\mysql-connector-java-5.1.24-bin.jar" /> --> <!-- 一个数据库一个context --> <!--defaultModelType="flat" 大数据字段,不分表 --> <context id="MysqlTables" targetRuntime="MyBatis3Simple" defaultModelType="flat"> <!-- 自动识别数据库关键字,默认false,如果设置为true,根据SqlReservedWords中定义的关键字列表; 一般保留默认值,遇到数据库关键字(Java关键字),使用columnOverride覆盖 --> <property name="autoDelimitKeywords" value="true" /> <!-- 生成的Java文件的编码 --> <property name="javaFileEncoding" value="utf-8" /> <!-- beginningDelimiter和endingDelimiter:指明数据库的用于标记数据库对象名的符号,比如ORACLE就是双引号,MYSQL默认是`反引号; --> <property name="beginningDelimiter" value="`" /> <property name="endingDelimiter" value="`" /> <!-- 格式化java代码 --> <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/> <!-- 格式化XML代码 --> <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/> <plugin type="org.mybatis.generator.plugins.SerializablePlugin" /> <plugin type="org.mybatis.generator.plugins.ToStringPlugin" /> <!-- 注释 --> <commentGenerator> <property name="suppressAllComments" value="true"/><!-- 是否取消注释 --> <property name="suppressDate" value="true" /> <!-- 是否生成注释代时间戳--> <!--<property name="addRemarkComments" value="true"/>--> </commentGenerator> <!-- jdbc连接 --> <jdbcConnection driverClass="${spring.datasource.driver-class-name}" connectionURL="${spring.datasource.url}" userId="${spring.datasource.username}" password="${spring.datasource.password}" /> <!-- 类型转换 --> <javaTypeResolver> <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) --> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 生成实体类地址 --> <javaModelGenerator targetPackage="cn.niit.entity" targetProject="${mybatis.project}" > <property name="enableSubPackages" value="false"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- 生成mapxml文件 --> <sqlMapGenerator targetPackage="mapper" targetProject="${mybatis.resources}" > <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <!-- 生成mapxml对应client,也就是接口dao --> <javaClientGenerator targetPackage="cn.niit.dao" targetProject="${mybatis.project}" type="XMLMAPPER" > <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!-- table可以有多个,每个数据库中的表都可以写一个table,tableName表示要匹配的数据库表,也可以在tableName属性中通过使用%通配符来匹配所有数据库表,只有匹配的表才会自动生成文件 --> <table tableName="%" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="true" enableSelectByExample="true" selectByExampleQueryId="true"> <property name="useActualColumnNames" value="false" /> <!-- 数据库表主键 --> <generatedKey column="id" sqlStatement="Mysql" identity="true" /> </table> </context></generatorConfiguration>pom.xml加入插件 <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <executions> <execution> <id>mybatis-generator</id> <phase>deploy</phase> <goals> <goal>generate</goal> </goals> </execution> </executions> <configuration> <!-- Mybatis-Generator 工具配置文件的位置 --> <configurationFile>src/main/resources/mybatis-generator/generatorConfig.xml</configurationFile> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.2</version> </dependency> </dependencies> </plugin>点击插件即可生成代码个人网站 ...

May 5, 2019 · 2 min · jiezi

MyBatis逆向工程

通过逆向工程生成mapper文件,大大提升了开发效率一、引入依赖 <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> </dependency>二、编写配置文件<?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=“DB2Tables” targetRuntime=“MyBatis3”> <commentGenerator> <property name=“suppressAllComments” value=“true” /> </commentGenerator> <jdbcConnection driverClass=“com.mysql.jdbc.Driver” connectionURL=“jdbc:mysql://localhost:3306/shortvideo?characterEncoding=utf-8&amp;serverTimezone=GMT%2B8” userId=“root” password=“123456”> </jdbcConnection> <javaTypeResolver > <property name=“forceBigDecimals” value=“false” /> </javaTypeResolver> <!– 指定javabean生成的位置 –> <javaModelGenerator targetPackage=“com.imooc.pojo” targetProject=”.\src\main\java"> <property name=“enableSubPackages” value=“true” /> <property name=“trimStrings” value=“true” /> </javaModelGenerator> <!– 指定mapper文件生成的位置 –> <sqlMapGenerator targetPackage=“mapper” targetProject=".\src\main\resources"> <property name=“enableSubPackages” value=“true” /> </sqlMapGenerator> <!– 指定mapper接口生成的位置 –> <javaClientGenerator type=“XMLMAPPER” targetPackage=“com.imooc.mapper” targetProject=".\src\main\java"> <property name=“enableSubPackages” value=“true” /> </javaClientGenerator> <table tableName=“vuser” domainObjectName=“Users”></table> <table tableName=“bgm”></table> <table tableName=“comments”></table> <table tableName=“search_records”></table> <table tableName=“users_fans”></table> <table tableName=“users_like_videos”></table> <table tableName=“users_report”></table> <table tableName=“videos”></table> </context></generatorConfiguration>三、编写启动类import org.mybatis.generator.api.MyBatisGenerator;import org.mybatis.generator.config.Configuration;import org.mybatis.generator.config.xml.ConfigurationParser;import org.mybatis.generator.exception.InvalidConfigurationException;import org.mybatis.generator.exception.XMLParserException;import org.mybatis.generator.internal.DefaultShellCallback;import java.io.File;import java.io.IOException;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;public class MybatisGenerator { public static void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException { List<String> warnings = new ArrayList<String>(); boolean overwrite = true; //指定配置文件的路径,相对或者绝对路径都可以 File configFile = new File(“E:\idea\short-video\src\main\java\com\imooc\utils\mybatisGenerator\mbg”); 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); }} ...

April 7, 2019 · 1 min · jiezi

Mybatis generator代码生成 introspectedTable.getRemarks() 是空字符串

现象运行时候发现introspectedTable.getRemarks()的值一直是空字符串修改方法修改 generatorConfig.xml文件jdbcConnection属性后可以取到值了<jdbcConnection driverClass=“com.mysql.jdbc.Driver” connectionURL=“jdbc:mysql://127.0.0.1:3306/thirties” userId=“thirties” password=“password”><!– 新增下面这个属性–> <property name=“useInformationSchema” value=“true” /> </jdbcConnection>

March 18, 2019 · 1 min · jiezi

SpringBoot 实战 (十三) | 整合 MyBatis (XML 版)

微信公众号:一个优秀的废人如有问题或建议,请后台留言,我会尽力解决你的问题。前言如题,今天介绍 SpringBoot 与 Mybatis 的整合以及 Mybatis 的使用,之前介绍过了 SpringBoot 整合MyBatis 注解版的使用,上一篇介绍过 MyBatis 的理论,今天这篇就不介绍 MyBatis 的理论了,有兴趣的跳转阅读:SpringBoot 实战 (十三) | 整合 MyBatis (注解版)准备工作SpringBoot 2.1.3IDEAJDK 8创建表CREATE TABLE student ( id int(32) NOT NULL AUTO_INCREMENT, student_id varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ‘学号’, name varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ‘姓名’, age int(11) NULL DEFAULT NULL COMMENT ‘年龄’, city varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ‘所在城市’, dormitory varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘宿舍’, major varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘专业’, PRIMARY KEY (id) USING BTREE)ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;引入依赖<dependencies> <!– jdbc 连接驱动 –> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!– web 启动类 –> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!– mybatis 依赖 –> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.0</version> </dependency> <!– druid 数据库连接池 –> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.14</version> </dependency> <!– Mysql 连接类 –> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> <scope>runtime</scope> </dependency> <!– 分页插件 –> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.5</version> </dependency> <!– test 依赖 –> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <!– springboot maven 插件 –> <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 generator 插件用于自动生成代码,pagehelper 插件用于物理分页。项目配置server: port: 8080spring: datasource: name: test url: jdbc:mysql://127.0.0.1:3306/test username: root password: 123456 #druid相关配置 type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver filters: stat maxActive: 20 initialSize: 1 maxWait: 60000 minIdle: 1 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select ‘x’ testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxOpenPreparedStatements: 20## 该配置节点为独立的节点,有很多同学容易将这个配置放在spring的节点下,导致配置无法被识别mybatis: mapper-locations: classpath:mapping/*.xml #注意:一定要对应mapper映射xml文件的所在路径 type-aliases-package: com.nasus.mybatisxml.model # 注意:对应实体类的路径#pagehelper分页插件pagehelper: helperDialect: mysql reasonable: true supportMethodsArguments: true params: count=countSqlmybatis generator 配置文件这里要注意,配置 pom.xml 中 generator 插件所对应的配置文件时,在 Pom.xml 加入这一句,说明 generator 插件所对应的配置文件所对应的配置文件路径。这里已经在 Pom 中配置了,请见上面的 Pom 配置。${basedir}/src/main/resources/generator/generatorConfig.xmlgeneratorConfig.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=“D:\repository\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.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/test” userId=“root” password=“123456”> </jdbcConnection> <javaTypeResolver> <property name=“forceBigDecimals” value=“false”/> </javaTypeResolver> <!– 生成模型的包名和位置–> <javaModelGenerator targetPackage=“com.nasus.mybatisxml.model” targetProject=“src/main/java”> <property name=“enableSubPackages” value=“true”/> <property name=“trimStrings” value=“true”/> </javaModelGenerator> <!– 生成映射文件的包名和位置–> <sqlMapGenerator targetPackage=“mapping” targetProject=“src/main/resources”> <property name=“enableSubPackages” value=“true”/> </sqlMapGenerator> <!– 生成DAO的包名和位置–> <javaClientGenerator type=“XMLMAPPER” targetPackage=“com.nasus.mybatisxml.mapper” targetProject=“src/main/java”> <property name=“enableSubPackages” value=“true”/> </javaClientGenerator> <!– 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名–> <table tableName=“student” domainObjectName=“Student” enableCountByExample=“false” enableUpdateByExample=“false” enableDeleteByExample=“false” enableSelectByExample=“false” selectByExampleQueryId=“false”></table> </context></generatorConfiguration>代码注释很详细,不多说。生成代码过程第一步:选择编辑配置第二步:选择添加 Maven 配置第三步:添加命令 mybatis-generator:generate -e 点击确定第四步:运行该配置,生成代码特别注意!!!同一张表一定不要运行多次,因为 mapper 的映射文件中会生成多次的代码,导致报错,切记。如要运行多次,请把上次生成的 mapper 映射文件代码删除再运行。第五步:检查生成结果遇到的问题请参照别人写好的遇到问题的解决方法,其中我就遇到数据库时区不对以及只生成 Insert 方法这两个问题。都是看以下这篇文章解决的:Mybatis Generator自动生成代码以及可能出现的问题生成的代码1、实体类:Student.javapackage com.nasus.mybatisxml.model;public class Student { private Long id; private Integer age; private String city; private String dormitory; private String major; private String name; private Long studentId; // 省略 get 和 set 方法}2、mapper 接口:StudentMapper.javapackage com.nasus.mybatisxml.mapper;import com.nasus.mybatisxml.model.Student;import java.util.List;import org.apache.ibatis.annotations.Mapper;@Mapperpublic interface StudentMapper { int deleteByPrimaryKey(Long id); int insert(Student record); int insertSelective(Student record); Student selectByPrimaryKey(Long id); // 我添加的方法,相应的要在映射文件中添加此方法 List<Student> selectStudents(); int updateByPrimaryKeySelective(Student record); int updateByPrimaryKey(Student record);}3、映射文件: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.nasus.mybatisxml.mapper.StudentMapper” > <resultMap id=“BaseResultMap” type=“com.nasus.mybatisxml.model.Student” > <id column=“id” property=“id” jdbcType=“BIGINT” /> <result column=“age” property=“age” jdbcType=“INTEGER” /> <result column=“city” property=“city” jdbcType=“VARCHAR” /> <result column=“dormitory” property=“dormitory” jdbcType=“VARCHAR” /> <result column=“major” property=“major” jdbcType=“VARCHAR” /> <result column=“name” property=“name” jdbcType=“VARCHAR” /> <result column=“student_id” property=“studentId” jdbcType=“BIGINT” /> </resultMap> <sql id=“Base_Column_List” > id, age, city, dormitory, major, name, student_id </sql> <select id=“selectByPrimaryKey” resultMap=“BaseResultMap” parameterType=“java.lang.Long” > select <include refid=“Base_Column_List” /> from student where id = #{id,jdbcType=BIGINT} </select> <delete id=“deleteByPrimaryKey” parameterType=“java.lang.Long” > delete from student where id = #{id,jdbcType=BIGINT} </delete> <insert id=“insert” parameterType=“com.nasus.mybatisxml.model.Student” > insert into student (id, age, city, dormitory, major, name, student_id) values (#{id,jdbcType=BIGINT}, #{age,jdbcType=INTEGER}, #{city,jdbcType=VARCHAR}, #{dormitory,jdbcType=VARCHAR}, #{major,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{studentId,jdbcType=BIGINT}) </insert> <insert id=“insertSelective” parameterType=“com.nasus.mybatisxml.model.Student” > insert into student <trim prefix=”(” suffix=")" suffixOverrides="," > <if test=“id != null” > id, </if> <if test=“age != null” > age, </if> <if test=“city != null” > city, </if> <if test=“dormitory != null” > dormitory, </if> <if test=“major != null” > major, </if> <if test=“name != null” > name, </if> <if test=“studentId != null” > student_id, </if> </trim> <trim prefix=“values (” suffix=")" suffixOverrides="," > <if test=“id != null” > #{id,jdbcType=BIGINT}, </if> <if test=“age != null” > #{age,jdbcType=INTEGER}, </if> <if test=“city != null” > #{city,jdbcType=VARCHAR}, </if> <if test=“dormitory != null” > #{dormitory,jdbcType=VARCHAR}, </if> <if test=“major != null” > #{major,jdbcType=VARCHAR}, </if> <if test=“name != null” > #{name,jdbcType=VARCHAR}, </if> <if test=“studentId != null” > #{studentId,jdbcType=BIGINT}, </if> </trim> </insert> <update id=“updateByPrimaryKeySelective” parameterType=“com.nasus.mybatisxml.model.Student” > update student <set > <if test=“age != null” > age = #{age,jdbcType=INTEGER}, </if> <if test=“city != null” > city = #{city,jdbcType=VARCHAR}, </if> <if test=“dormitory != null” > dormitory = #{dormitory,jdbcType=VARCHAR}, </if> <if test=“major != null” > major = #{major,jdbcType=VARCHAR}, </if> <if test=“name != null” > name = #{name,jdbcType=VARCHAR}, </if> <if test=“studentId != null” > student_id = #{studentId,jdbcType=BIGINT}, </if> </set> where id = #{id,jdbcType=BIGINT} </update> <update id=“updateByPrimaryKey” parameterType=“com.nasus.mybatisxml.model.Student” > update student set age = #{age,jdbcType=INTEGER}, city = #{city,jdbcType=VARCHAR}, dormitory = #{dormitory,jdbcType=VARCHAR}, major = #{major,jdbcType=VARCHAR}, name = #{name,jdbcType=VARCHAR}, student_id = #{studentId,jdbcType=BIGINT} where id = #{id,jdbcType=BIGINT} </update> <!– 我添加的方法 –> <select id=“selectStudents” resultMap=“BaseResultMap”> SELECT <include refid=“Base_Column_List” /> from student </select></mapper>serviec 层1、接口:public interface StudentService { int addStudent(Student student); Student findStudentById(Long id); PageInfo<Student> findAllStudent(int pageNum, int pageSize);}2、实现类@Servicepublic class StudentServiceImpl implements StudentService{ //会报错,不影响 @Resource private StudentMapper studentMapper; /** * 添加学生信息 * @param student * @return / @Override public int addStudent(Student student) { return studentMapper.insert(student); } /* * 根据 id 查询学生信息 * @param id * @return / @Override public Student findStudentById(Long id) { return studentMapper.selectByPrimaryKey(id); } /* * 查询所有学生信息并分页 * @param pageNum * @param pageSize * @return */ @Override public PageInfo<Student> findAllStudent(int pageNum, int pageSize) { //将参数传给这个方法就可以实现物理分页了,非常简单。 PageHelper.startPage(pageNum, pageSize); List<Student> studentList = studentMapper.selectStudents(); PageInfo result = new PageInfo(studentList); return result; }}controller 层@RestController@RequestMapping("/student")public class StudentController { @Autowired private StudentService studentService; @GetMapping("/{id}") public Student findStidentById(@PathVariable(“id”) Long id){ return studentService.findStudentById(id); } @PostMapping("/add") public int insertStudent(@RequestBody Student student){ return studentService.addStudent(student); } @GetMapping("/list") public PageInfo<Student> findStudentList(@RequestParam(name = “pageNum”, required = false, defaultValue = “1”) int pageNum, @RequestParam(name = “pageSize”, required = false, defaultValue = “10”) int pageSize){ return studentService.findAllStudent(pageNum,pageSize); }}启动类@SpringBootApplication@MapperScan(“com.nasus.mybatisxml.mapper”) // 扫描 mapper 接口,必须加上public class MybatisxmlApplication { public static void main(String[] args) { SpringApplication.run(MybatisxmlApplication.class, args); }}提一嘴,@MapperScan(“com.nasus.mybatisxml.mappe”) 这个注解非常的关键,这个对应了项目中 mapper(dao) 所对应的包路径,必须加上,否则会导致异常。Postman 测试1、插入方法:2、根据 id 查询方法:3、分页查询方法:源码下载https://github.com/turoDog/De…帮忙点个 star 可好?后语如果本文对你哪怕有一丁点帮助,请帮忙点好看。你的好看是我坚持写作的动力。另外,关注之后在发送 1024 可领取免费学习资料。资料内容详情请看这篇旧文:Python、C++、Java、Linux、Go、前端、算法资料分享 ...

March 1, 2019 · 5 min · jiezi

Spring Boot项目利用MyBatis Generator进行数据层代码自动生成

概 述MyBatis Generator (简称 MBG) 是一个用于 MyBatis和 iBATIS的代码生成器。它可以为 MyBatis的所有版本以及 2.2.0之后的 iBATIS版本自动生成 ORM层代码,典型地包括我们日常需要手写的 POJO、mapper xml 以及 mapper 接口等。MyBatis Generator 自动生成的 ORM层代码几乎可以应对大部分 CRUD 数据表操作场景,可谓是一个生产力工具啊!注: 本文首发于 My Personal Blog:CodeSheep·程序羊,欢迎光临 小站数据库准备与工程搭建首先我们准备一个 MySQL数据表 user_info用于下文实验里面插入了若干条数据:新建一个Spring Boot 工程引入 MyBatis Generator 依赖<dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.7</version> <scope>provided</scope></dependency>引入 MyBatis Generator Maven 插件<plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.7</version> <configuration> <configurationFile>src/main/resources/mybatis-generator.xml</configurationFile> <overwrite>true</overwrite> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.12</version> </dependency> </dependencies></plugin>MyBatis Generator Maven 插件引入以后,我们可以在 Spring Boot工程的 Maven插件工具栏中看到新增的插件选项,类似下图:准备 MyBatis Generator 配置文件MyBatis Generator 也需要一个 xml格式的配置文件,该文件的位置配在了上文 引入 MyBatis Generator Maven 插件的 xml配置里,即src/main/resources/mybatis-generator.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> <context id=“MySql” defaultModelType=“flat”> <plugin type=“org.mybatis.generator.plugins.SerializablePlugin” /> <jdbcConnection driverClass=“com.mysql.jdbc.Driver” connectionURL=“jdbc:mysql://121.196.123.245:3306/demo” userId=“root” password=“xxxxxx” /> <javaModelGenerator targetPackage=“cn.codesheep.springbt_mybatis_generator.entity” targetProject=“src/main/java”></javaModelGenerator> <sqlMapGenerator targetPackage=“mapper” targetProject=“src/main/resources”></sqlMapGenerator> <javaClientGenerator targetPackage=“cn.codesheep.springbt_mybatis_generator.mapper” targetProject=“src/main/java” type=“XMLMAPPER”></javaClientGenerator> <table tableName=“user_info”> <property name=“modelOnly” value=“false”/> </table> </context></generatorConfiguration>上面 xml中几个关键的配置简介如下:< jdbcConnection /> 数据库连接配置,至关重要<javaModelGenerator /> 指定自动生成的 POJO置于哪个包下<sqlMapGenerator /> 指定自动生成的 mapper.xml置于哪个包下<javaClientGenerator /> 指定自动生成的 DAO接口置于哪个包下<table /> 指定数据表名,可以使用_和%通配符更多关于 MyBatis Generator 配置的内容,可以移步 官方文档。运行 MyBatis Generator直接通过 IDEA的 Maven图形化插件来运行 MyBatis Generator,其自动生成的过程 和 生成的结果如下图所示:很明显,通过 MyBatis Generator,已经很方便的帮我们自动生成了 POJO、mapper xml 以及 mapper接口,接下来我们看看自动生成的代码怎么用!自动生成的代码如何使用我们发现通过 MyBatis Generator自动生成的代码中带有一个 Example文件,比如上文中的 UserInfoExample,其实 Example文件对于平时快速开发还是有很大好处的,它能节省很多写 sql语句的时间,举几个实际的例子吧:单条件模糊搜索 + 排序在我们的例子中,假如我想通过用户名 user_name来在 MySQL数据表 user_info中进行模糊搜索,并对结果进行排序,此时利用UserInfoExample可以方便快速的实现:@Autowiredprivate UserInfoMapper userInfoMapper;public List<UserInfo> searchUserByUserName( String userName ) { UserInfoExample userInfoExample = new UserInfoExample(); userInfoExample.createCriteria().andUserNameLike( ‘%’+ userName +’%’ ); // 设置模糊搜索的条件 String orderByClause = “user_name DESC”; userInfoExample.setOrderByClause( orderByClause ); // 设置通过某个字段排序的条件 return userInfoMapper.selectByExample( userInfoExample );}多条件精确搜索再比如,我们想通过电话号码 phone和用户名 user_name 两个字段来在数据表 user_info中实现精确搜索,则可以如下实现:public List<UserInfo> multiConditionsSearch( UserInfo userInfo ) { UserInfoExample userInfoExample = new UserInfoExample(); UserInfoExample.Criteria criteria = userInfoExample.createCriteria(); if( !”".equals(userInfo.getPhone()) ) criteria.andPhoneEqualTo( userInfo.getPhone() ); if( !"".equals(userInfo.getUserName()) ) criteria.andUserNameEqualTo( userInfo.getUserName() ); return userInfoMapper.selectByExample( userInfoExample );}很明显可以看出的是,我们是通过直接编写代码逻辑来取代编写 SQL语句,因此还是十分直观和容易理解的!后 记由于能力有限,若有错误或者不当之处,还请大家批评指正,一起学习交流!My Personal Blog:CodeSheep 程序羊 ...

February 14, 2019 · 2 min · jiezi