Mybatis是一个Java持久化框架,它通过XML描述符或注解把对象与存储过程或SQL语句关联起来。
大题两种方式,以XML配置sql语句或者以mapper的方式进行注入
本文针对XML方式,总结自己踩的坑,供学习使用。mapper方式推荐 Mybatis中配置Mapper的方法
1.新建maven工程,其结构图,如下。MybatisUtil包含一些工具类,StudentBean与数据库表对应的类,TestMain是主程序入口
db.properties数据库配置文件,mybatis.xml是配置mybatis文件,sql.xml是sql操作文件
2. 看看几个资源文件
[ 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>com</groupId>
<artifactId>sogou</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>7</source>
<target>7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
</dependencies>
</project>
[ db.properties ] // 自行修改
mysql.driver = com.mysql.jdbc.Driver
mysql.url = jdbc:mysql://xxx:3306/xxx?characterEncoding=utf-8
mysql.username = xxx
mysql.password = *********
[ sql.xml ] // 自行修改,注解写得很详细,几点注意事项
- 使用得时候需要注意区分 resultMap 和 resultType,前者表示返回一个自定义的对象list,后者是返回值类型,可以直接指定成java.lang.String等类型
- 批量处理的时候,foreach的属性 别乱使用 open 和 close属性,否则会因为sql语句不对产生mybatis Cause: java.sql.SQLException: Operand should contain 1 column(s) 错误
<?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命名空间,必须与创建maven groupId + artifactId组成
否则,在配置文件mybatis.xml中无法找到映射文件
-->
<mapper namespace="com.xzy">
<!-- resultMap标签:映射实体类与数据库表
type属性:表示实体类名
id属性:为实体类与数据库表映射的唯一名字
-->
<resultMap type="StudentBean" id="stu">
<!-- id标签:映射主键属性;result标签:映射非主键属性
property属性:实体bean类属性名
column属性:数据库表的字段名
顺序无关,字段需对应
-->
<id property="studentID" column="studentID"/>
<result property="age" column="age"/>
<result property="name" column="name"/>
</resultMap>
<insert id="Insert" parameterType="StudentBean">
INSERT INTO student (name, age, studentID) VALUES (#{name},#{age},#{studentID});
<!--
批量插入格式,末尾没有;号。使用foreach在不懂的情况别乱改。个人属知道的
separator可以改成自己想要的分割符,这只是多个多个values之间用什么隔开。
比如打印;号分割结果类似如下
insert into student(name, studentID, age) values (("xzy", "1", 18);("xzy2", "2", 17))
其他foreach属性,本人没测过,尚不明确是否可自定义,可自行搜索
-->
</insert>
<insert id="InsertBatch" parameterType="java.util.List">
INSERT INTO student(name, studentID, age) VALUES
<foreach collection="list" item="item" index="index" separator="," >
(#{item.name},
#{item.studentID},
#{item.age})
</foreach>
</insert>
<!--条件查询,注意部分字符需转义,如小于,<![CDATA[ < ]]>
resultMap为上诉建立的实体对象
-->
<select id="findByCondition" parameterType="int" resultMap="stu">
select * from student where age <![CDATA[ < ]]>#{age};
</select>
<select id="selectStuName" parameterType="java.lang.String" resultType="java.lang.String">
select name from student where studentID=#{studentID};
</select>
</mapper>
[ mybatis.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 resource="db.properties"/>
<!-- 可设置多个连接环境信息 -->
<environments default="mysql_developer">
<!-- 连接环境信息,取一个任意唯一的名字 -->
<environment id="mysql_developer">
<!-- mybatis使用jdbc事务管理方式 -->
<transactionManager type="jdbc"/>
<!-- mybatis使用连接池方式来获取连接 -->
<dataSource type="pooled">
<!-- 配置与数据库链接信息 -->
<property name="driver" value="${mysql.driver}"/>
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--映射sql操作的文件 -->
<mapper resource="sql.xml"/>
</mappers>
</configuration>
3. 看看几个 类 代码,啥都在代码里,去找你的颜如玉吧
[ TestMain.java]
import java.sql.Connection;
import java.util.List;
public class TestMain {
public static void main(String[] args) {
Connection conn = MybatisUtil.getSqlSession().getConnection();
System.out.println(conn!=null?"连接成功":"连接失败");
StudentBean bean = new StudentBean("小李子", "20180809005", 21);
MybatisUtil.insert(bean);
List<StudentBean> studentList = MybatisUtil.selectByConf(23);
if (studentList != null){
for (StudentBean student : studentList){
System.out.println(student.toString());
}
}
MybatisUtil.insertBatch(studentList);
}
}
[ StudentBean.java]
public class StudentBean {
private String name;
private String studentID;
private int age;
/**
* 构造函数参数的顺序必须和数据库字段的顺序一致,否则在执行查询时
* 返回的对象无法转成该对象,从而报类似No constructor found in StudentBean matching [java.lang.String, java.lang.String, java.lang.Integer]
* 异常
* **/
public StudentBean(String name, String studentID, int age) {
this.name = name;
this.age = age;
this.studentID = studentID;
}
@Override
public String toString() {
return "StudentBean{" +
"name='" + name + '\'' +
", studentID='" + studentID + '\'' +
", age=" + age +
'}';
}
}
[MybatisUtil.java]
import java.io.IOException;
import java.io.Reader;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/**
* 工具类
* @author AdminTC
*/
public class MybatisUtil {
private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();
private static SqlSessionFactory sqlSessionFactory;
/**
* 加载位于src/mybatis.xml配置文件
*/
static{
try {
Reader reader = Resources.getResourceAsReader("mybatis.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 禁止外界通过new方法创建
*/
private MybatisUtil(){}
/**
* 获取SqlSession
*/
public static SqlSession getSqlSession(){
//从当前线程中获取SqlSession对象
SqlSession sqlSession = threadLocal.get();
//如果SqlSession对象为空
if(sqlSession == null){
//在SqlSessionFactory非空的情况下,获取SqlSession对象
sqlSession = sqlSessionFactory.openSession();
//将SqlSession对象与当前线程绑定在一起
threadLocal.set(sqlSession);
}
//返回SqlSession对象
return sqlSession;
}
/**
* 关闭SqlSession与当前线程分开
*/
public static void closeSqlSession(){
//从当前线程中获取SqlSession对象
SqlSession sqlSession = threadLocal.get();
//如果SqlSession对象非空
if(sqlSession != null){
//关闭SqlSession对象
sqlSession.close();
//分开当前线程与SqlSession对象的关系,目的是让GC尽早回收
threadLocal.remove();
}
}
public static void insert(StudentBean student){
//得到连接对象
SqlSession sqlSession = MybatisUtil.getSqlSession();
try{
sqlSession.insert("com.xzy.Insert", student);
sqlSession.commit();
//映射文件的命名空间.SQL片段的ID,就可以调用对应的映射文件中的SQL
}catch(Exception e){
e.printStackTrace();
sqlSession.rollback();
}finally{
MybatisUtil.closeSqlSession();
}
}
public static void insertBatch(List<StudentBean> applist) {
SqlSession sqlSession = MybatisUtil.getSqlSession();
MybatisUtil.closeSqlSession();
try{
sqlSession.insert("com.xzy.InsertBatch", applist);
sqlSession.commit();
}catch(Exception e){
e.printStackTrace();
sqlSession.rollback();
}finally{
MybatisUtil.closeSqlSession();
}
}
public static List<StudentBean> selectByConf(int conf){
SqlSession sqlSession = MybatisUtil.getSqlSession();
List list = null;
try{
list = sqlSession.selectList("com.xzy.findByCondition", conf);
}catch(Exception e){
e.printStackTrace();
sqlSession.rollback();
}finally{
MybatisUtil.closeSqlSession();
}
return list;
}
}