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 ]
4.0.0
com
sogou
1.0-SNAPSHOT
org.apache.maven.plugins
maven-compiler-plugin
7
org.mybatis
mybatis
3.4.6
mysql
mysql-connector-java
5.1.46
[ 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 ] // 自行修改,注解写得很详细,几点注意事项
INSERT INTO student (name, age, studentID) VALUES (#{name},#{age},#{studentID});
INSERT INTO student(name, studentID, age) VALUES
(#{item.name},
#{item.studentID},
#{item.age})
[ mybatis.xml ]
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 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 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 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 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;
}
}