MyBatis 简单入门案例
项目目录结构
项目依赖
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>xyz.cglzwz</groupId>
<artifactId>mybatis-demo1</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>mybatis-demo1 Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
</dependencies>
<build>
<finalName>mybatis-demo1</finalName>
</build>
</project>
mybatis-config.xml
<?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文件 -->
<properties resource="jdbc.properties"/>
<!-- alias别名 -->
<typeAliases>
<typeAlias alias="role" type="xyz.cglzwz.mybatis.demo1.pojo.Role"/>
</typeAliases>
<!-- 数据库环境 -->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理 -->
<transactionManager type="JDBC"/>
<!-- 数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="${database.driver}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
</dataSource>
</environment>
</environments>
<!-- 映射文件 -->
<mappers>
<mapper resource="xyz/cglzwz/mybatis/demo1/mapper/RoleMapper.xml"/>
</mappers>
</configuration>
jdbc.properties和log4j.properties配置文件
database.driver=com.mysql.cj.jdbc.Driver
database.url=jdbc:mysql:///mybatis_demo1?serverTimezone=UTC&characterEncoding=UTF-8&useSSL=false
database.username=root
database.password=mima
log4j.rootLogger=DEBUG , stdout
log4j.logger.org.mybatis=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p %d %c: %m%n
pojo类Role.java
package xyz.cglzwz.mybatis.demo1.pojo;
/**
* @author chgl16
* @Date 2018.9.26
*/
public class Role {
private Long id;
private String roleName;
private String note;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Role() {
}
public Role(Long id, String roleName, String note) {
super();
this.id = id;
this.roleName = roleName;
this.note = note;
}
}
对应数据库数据表
DROP DATABASE IF EXISTS mybatis_demo1;
CREATE DATABASE mybatis_demo1 DEFAULT CHARACTER SET utf8;
USE mybatis_demo1;
CREATE TABLE t_role(
id BIGINT(18) NOT NULL AUTO_INCREMENT,
role_name VARCHAR(255) NOT NULL,
note VARCHAR(255),
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO t_role VALUES(1, '小明', '明日之前');
INSERT INTO t_role VALUES(2, '小米', '小米科技');
INSERT INTO t_role VALUES(3, '小红', '红色的火');
SqlSession对象获取的工具类,也是读取mybatis-config配置类
package xyz.cglzwz.mybatis.demo1.util;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/**
* @使用mybatis-conf.xml
* @通过SqlSessionFactoryBuilder来构建SqlSessionFactory
* @SqlSessionFactory应是单例模式,此处省略了单例锁代码
*
* @author chgl16
* @Date 2018.9.26
*/
public class SqlSessionFactoryUtil {
/** 声明为static */
public static SqlSession openSqlSession() throws Exception {
String sqlConfigXML = "mybatis-config.xml";
// 将资源文件输入到流
InputStream inputStream = Resources.getResourceAsStream(sqlConfigXML);
// SqlSessionFactoryBuilder对象调用build方法读取输入流
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(inputStream);
return build.openSession();
}
}
映射器(此处采用:由一个xml文件和java接口组成)
<?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">
<!-- namespace表示对应的接口类 -->
<mapper namespace="xyz.cglzwz.mybatis.demo1.mapper.RoleMapper">
<!-- role是使用了mybatis-config.xml里面的全局别名 -->
<insert id="insertRole" parameterType="role">
insert into t_role(role_name, note) values(#{roleName}, #{note})
</insert>
<delete id="deleteRole" parameterType="Long">
delete from t_role where id = #{id}
</delete>
<update id="updateRole" parameterType="role">
update t_role set role_name = #{roleName}, note = #{note} where id = #{id}
</update>
<!-- 此处包含sql到pojo的映射,所有字段和属性名要一致,故此处使用别名,也可以用resultMap结果集映射 -->
<select id="getRole" parameterType="Long" resultType="role">
select id, role_name as roleName, note from t_role where id = #{id}
</select>
<!-- 使用了sql匹配语法 -->
<select id="findRoles" parameterType="String" resultType="role">
select id, role_name as roleName, note from t_role
where role_name like concat('%', #{roleName}, '%')
</select>
</mapper>
package xyz.cglzwz.mybatis.demo1.mapper;
import java.util.List;
import xyz.cglzwz.mybatis.demo1.pojo.Role;;
/**
* @映射器的接口类
*
* @author chgl16
* @Date 2018.9.26
*/
public interface RoleMapper {
public int insertRole(Role role);
public int deleteRole(Long id);
public int updateRole(Role role);
public Role getRole(Long id);
public List<Role> findRoles(String roleName);
}
测试的主类
package xyz.cglzwz.mybatis.demo1.main;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import xyz.cglzwz.mybatis.demo1.pojo.Role;
import xyz.cglzwz.mybatis.demo1.mapper.RoleMapper;
import xyz.cglzwz.mybatis.demo1.util.SqlSessionFactoryUtil;
/**
* @主函数
*
* @author chgl16
* @Date 2018.9.26
*/
public class Main {
public static void main(String[] args) {
// 使用log4j打印日志
Logger log = Logger.getLogger(Main.class);
// 获取SqlSession对象
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionFactoryUtil.openSqlSession();
// 通过映射器(接口和mapper.xml文件组合)方式发送SQL
RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
// 操作打印
Role role1 = roleMapper.getRole(2L);
log.info(role1.getRoleName());
Role role2 = new Role();
role2.setRoleName("小绿");
role2.setNote("绿色出行");
int flag = roleMapper.insertRole(role2);
log.info(flag);
// 增删改需要提交处理
sqlSession.commit();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
// 在finally里面关闭资源,终结SqlSession对象的生命周期
if (sqlSession != null) {
sqlSession.close();
}
}
}
}
运行结果
DEBUG 2018-09-27 19:48:37,418 org.apache.ibatis.logging.LogFactory: Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG 2018-09-27 19:48:37,566 org.apache.ibatis.datasource.pooled.PooledDataSource: PooledDataSource forcefully closed/removed all connections.
DEBUG 2018-09-27 19:48:37,566 org.apache.ibatis.datasource.pooled.PooledDataSource: PooledDataSource forcefully closed/removed all connections.
DEBUG 2018-09-27 19:48:37,566 org.apache.ibatis.datasource.pooled.PooledDataSource: PooledDataSource forcefully closed/removed all connections.
DEBUG 2018-09-27 19:48:37,566 org.apache.ibatis.datasource.pooled.PooledDataSource: PooledDataSource forcefully closed/removed all connections.
DEBUG 2018-09-27 19:48:37,754 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Opening JDBC Connection
DEBUG 2018-09-27 19:48:38,008 org.apache.ibatis.datasource.pooled.PooledDataSource: Created connection 1418385211.
DEBUG 2018-09-27 19:48:38,008 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Setting autocommit to false on JDBC Connection [[email protected]]
DEBUG 2018-09-27 19:48:38,008 xyz.cglzwz.mybatis.demo1.mapper.RoleMapper.getRole: ==> Preparing: select id, role_name as roleName, note from t_role where id = ?
DEBUG 2018-09-27 19:48:38,055 xyz.cglzwz.mybatis.demo1.mapper.RoleMapper.getRole: ==> Parameters: 2(Long)
DEBUG 2018-09-27 19:48:38,102 xyz.cglzwz.mybatis.demo1.mapper.RoleMapper.getRole: <== Total: 1
INFO 2018-09-27 19:48:38,102 xyz.cglzwz.mybatis.demo1.main.Main: 小米
DEBUG 2018-09-27 19:48:38,102 xyz.cglzwz.mybatis.demo1.mapper.RoleMapper.insertRole: ==> Preparing: insert into t_role(role_name, note) values(?, ?)
DEBUG 2018-09-27 19:48:38,102 xyz.cglzwz.mybatis.demo1.mapper.RoleMapper.insertRole: ==> Parameters: 小绿(String), 绿色出行(String)
DEBUG 2018-09-27 19:48:38,102 xyz.cglzwz.mybatis.demo1.mapper.RoleMapper.insertRole: <== Updates: 1
INFO 2018-09-27 19:48:38,102 xyz.cglzwz.mybatis.demo1.main.Main: 1
DEBUG 2018-09-27 19:48:38,102 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Committing JDBC Connection [[email protected]]
DEBUG 2018-09-27 19:48:38,196 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Resetting autocommit to true on JDBC Connection [[email protected]]
DEBUG 2018-09-27 19:48:38,210 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Closing JDBC Connection [[email protected]]
DEBUG 2018-09-27 19:48:38,210 org.apache.ibatis.datasource.pooled.PooledDataSource: Returned connection 1418385211 to pool.
项目代码位置:https://github.com/chgl16/MyBatis-demo
Java编程代码规范:http://www.cglzwz.xyz/file/Java_manual.pdf