小白入门:mybatis超简单方便的增删改查操作(idea2019)
程序员文章站
2022-07-12 22:38:23
...
配置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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>MYBATIS</groupId>
<artifactId>MYBATIS</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
</dependencies>
<build>
<finalName>zsxt</finalName>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
配置资源 generator.properties
连接数据库:view->tool windows->database
选择所要连接的数据库类型
填写账号密码和数据库
建立generatorConfig.xml文件
目的是为了自动生成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>
</generatorConfiguration>
<?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 type="com.example.demo.channellable.CommentGenerator">
<!-- <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.example.demo.model"
targetProject="src/main/java">
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
<!-- 是否对model添加 构造函数 -->
<property name="constructorBased" value="true"/>
<!-- 是否对类CHAR类型的列的数据进行trim操作 -->
<property name="trimStrings" value="true"/>
<!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 -->
<property name="immutable" value="false"/>
</javaModelGenerator>
<!--在resources目录下的mapper文件,生成数据库的表对应的xml文件 -->
<sqlMapGenerator targetPackage="mapper"
targetProject="src/main/resources">
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- 生成dao层的java代码
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
targetPackage填写自己想要存放dao的路径,如果没有该路径会自动生成
-->
<javaClientGenerator targetPackage="com.example.demo.dao"
targetProject="src/main/java" type="XMLMAPPER">
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 数据表名及实体类名称 -->
<table tableName="t_user" domainObjectName="User"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
建立CommentGenerator,用于通过数据库注释生成实体类注释
package com.example.demo.channellable;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
/**
* @author wfr
* @description:
* @date 2019-10-12 15:04
* @parem CommentGenerator
*/
public class CommentGenerator extends DefaultCommentGenerator {
private Properties properties;
private Properties systemPro;
private boolean suppressDate;
private boolean suppressAllComments;
private String currentDateStr;
public CommentGenerator() {
super();
this.properties = new Properties();
this.systemPro = System.getProperties();
this.suppressDate = false;
this.suppressAllComments = false;
this.currentDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
}
public void addFieldComment(Field field, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
field.addJavaDocLine("/**");
sb.append(" * ");
sb.append(introspectedColumn.getRemarks());
sb.append("\n");
sb.append(" * 列名:" + introspectedColumn.getActualColumnName() + " 类型:" + introspectedColumn.getJdbcTypeName()
+ "(" + introspectedColumn.getLength() + ")" + " 允许空:" + introspectedColumn.isNullable() + " 缺省值:"
+ introspectedColumn.getDefaultValue());
field.addJavaDocLine(sb.toString());
field.addJavaDocLine(" */");
}
public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
}
public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append("/**");
sb.append("\n");
sb.append(" * ");
sb.append("\n");
sb.append(" * @author wfr" + "\n");//改为自己的名字
if (!suppressDate) {
sb.append(" * @date " + currentDateStr + "\n");
}
List<Parameter> parameters = method.getParameters();
for (Parameter parameter : parameters) {
sb.append(" * @param " + parameter.getName() + "\n");
}
sb.append(" * @return " + method.getReturnType());
sb.append("\n" + " */");
method.addJavaDocLine(sb.toString());
}
public void addGetterComment(Method method, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
}
public void addSetterComment(Method method, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
}
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
super.addClassComment(innerClass, introspectedTable, markAsDoNotDelete);
}
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
}
public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append("/**");
sb.append("\n");
sb.append("* ");
sb.append("\n");
sb.append("* @author wfr" + "\n");//改为自己的名字
if (!suppressDate) {
sb.append("* @date " + currentDateStr + "\n");
}
sb.append("* 数据表" + introspectedTable.getFullyQualifiedTableNameAtRuntime() + "映射bean,由Mybaits自动生成工具生成");
sb.append("\n" + "*/");
topLevelClass.addJavaDocLine(sb.toString());
}
}
建立MyBatisGeneratorRun类,用于运行generatorConfig.xml
package com.example.demo.channellable;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* @author wfr
* @description:
* @date 2019-10-12 15:49
* @parem MyBatisGeneratorRun
*/
public class MyBatisGeneratorRun {
public static void main(String[] args) throws Exception{
MyBatisGeneratorRun app = new MyBatisGeneratorRun();
System.out.println(app.getClass().getResource("/").getPath());
app.generator();
System.out.println(System.getProperty("user.dir"));
}
public void generator() throws Exception{
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(resourceAsStream);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
for(String warning:warnings){
System.out.println(warning);
}
}
}
配置mapper文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--导入属性配置-->
<properties resource="generator.properties"></properties>
<!--配置文件-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClass}"/>
<property name="url" value="${jdbc.connectionURL}"/>
<property name="username" value="${jdbc.userId}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--生成映射xml所在的目录,默认是在resource目录的mapper下-->
<mapper resource="mapper/CartMapper.xml"></mapper>
</mappers>
</configuration>
运行MyBatisGeneratorRun 后,前期准备就完成了
然后就可以通过测试来检查了
找到自动生成的mapper类右击,生成测试类
package com.example.demo.dao;
import com.example.demo.model.Cart;
import com.example.demo.model.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import static org.junit.Assert.*;
public class CartMapperTest {
@Test
public void deleteByPrimaryKey() throws Exception{
InputStream inputStream= Resources.getResourceAsStream("SqlMapConfig.xml");
//创建工厂
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
//通过工厂创建会话
SqlSession openSession=factory.openSession();
openSession.delete("com.example.demo.dao.CartMapper.deleteByPrimaryKey",10);
//提交事务
openSession.commit();//重点,如果没有openSession.commit();就插入数据库失败
openSession.close();
}
@Test
public void insert() throws Exception{
InputStream inputStream= Resources.getResourceAsStream("SqlMapConfig.xml");
//创建工厂
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
//通过工厂创建会话
SqlSession openSession=factory.openSession();
Cart cart= new Cart(null, 2, 1, 1, null);
//两种写法
openSession.insert("com.example.demo.dao.CartMapper.insert",cart);
// openSession.getMapper(CartMapper.class).insert(cart);
//提交事务
openSession.commit();//重点,如果没有openSession.commit();就插入数据库失败
openSession.close();
System.out.println(cart);
}
@Test
public void insertSelective() throws Exception{
}
@Test
public void selectByPrimaryKey() throws Exception{
InputStream inputStream= Resources.getResourceAsStream("SqlMapConfig.xml");
//创建工厂
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
//通过工厂创建会话
SqlSession openSession=factory.openSession();
//第一个参数:所调用的sql语句:namespace+‘.’+SqlID
//第二个参数:传入的参数
Cart cart=openSession.getMapper(CartMapper.class).selectByPrimaryKey(1);
System.out.println(cart);
openSession.close();
}
@Test
public void updateByPrimaryKeySelective() throws Exception{
}
@Test
public void updateByPrimaryKey() throws Exception{
InputStream inputStream= Resources.getResourceAsStream("SqlMapConfig.xml");
//创建工厂
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
//通过工厂创建会话
SqlSession openSession=factory.openSession();
Cart cart= new Cart(9, 2, 4, 1, null);
//两种写法
openSession.update("com.example.demo.dao.CartMapper.updateByPrimaryKey",cart);
openSession.commit();//重点,如果没有openSession.commit();就插入数据库失败
openSession.close();
System.out.println(cart);
}
}