mybatis的工作流程
- 通过Reader对象读取src目录下的mybatis.xml配置文件(该文本的位置和名字可任意)
- 通过SqlSessionFactoryBuilder对象创建SqlSessionFactory对象
- 从当前线程中获取SqlSession对象
- 事务开始
- 通过SqlSession对象读取StudentMapper.xml映射文件中的操作编号,从而读取sql语句
- 事务提交,必写
- 关闭SqlSession对象,并且分开当前线程与SqlSession对象,让GC尽早回收
接下来以user对象为例子,看看如何利用mybatis实现单表的增删改查
在resources目录下增加文件
db.propreties(连接数据库所需参数配置文件)
log4j.properties(日志配置文件),
mybatis.xml(mybatis核心配置文件,设置数据库连接和加载实体映射文件)
db.properties
mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://127.0.0.1:3306/mybatis
mysql.username=root
mysql.password=123456
log4j.properties
log4j.rootLogger=debug,stdout,logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
mybatis.xml
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 加载类路径下的属性文件 -->
<properties resource="db.properties"/>
<!-- 设置类型别名 -->
<typeAliases>
</typeAliases>
<!-- 设置一个默认的连接环境信息 -->
<environments default="mysql_developer">
<!-- 连接环境信息,取一个任意唯一的名字 -->
<environment id="mysql_developer">
<!-- mybatis使用jdbc事务管理方式 -->
<transactionManager type="jdbc"/>
<!-- mybatis使用连接池方式来获取连接 -->
<dataSource type="pooled">
<!-- 配置与数据库交互的4个必要属性 -->
<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>
<!--<mapper resource="com/lianwei/entity/StudentsMapper.xml"/>-->
</mappers>
</configuration>
java目录下新建三个包
com.lianwei.dao
com.lianwei.entity
com.lianwei.util
建表
新建数据库mybatis,新建表user
CREATE TABLE `user` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(255) default NULL,
`sex` varchar(255) default NULL,
`password` varchar(255) default NULL,
`age` varchar(255) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8
建好表后,马上新增实体类User
User.java
/**
* Created by Tired on 2019/8/6.
*/
public class User {
private int id;
private String name;
private String password;
private String sex;
private String age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
entity包下新建UserMapper.xml实体映射文件(增删改查sql配置及实体映射配置)
UserMapper.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">
<!-- namespace属性是名称空间,必须唯一 -->
<mapper namespace="com.lianwei.entity.User">
<resultMap id="userMap" type="user">
<id property="id" column="id"/>
<result property="name" column="name"></result>
<result property="password" column="password"></result>
<result property="sex" column="sex"></result>
<result property="age" column="age"></result>
</resultMap>
<!-- 增加-->
<insert id="addUser" parameterType="user" >
INSERT into user (id,name,password,sex,age)
values(#{id},#{name},#{password},#{sex},#{age})
</insert>
<!--删除-->
<delete id="deleteById" parameterType="int" >
delete from user where id=#{id}
</delete>
<!-- 修改-->
<update id="update" parameterType="user">
update user set name=#{name}, password=#{password},sex=#{sex},age=#{age}
where id=#{id}
</update>
<!-- 根据id查询一条-->
<select id="findById" parameterType="int" resultType="com.lianwei.entity.User">
select id, name, password,sex,age from user where id=#{id}
</select>
<!--查询所有-->
<select id="findAll" resultMap="userMap">
select id, name, password,sex,age from user
</select>
<!-- 查询n条-->
<select id="findAllWithPage" parameterType="map" resultMap="userMap">
select id, name, password,sex,age from user limit #{pstart}, #{psize};
</select>
<!--根据名字模糊查询n条-->
<select id="findByNameWithPage" parameterType="map" resultMap="userMap">
select id, name, password,sex,age from user where name like #{name} limit #{pstart}, #{psize}
</select>
<!--拼接sql语句-->
<select id="findByDynaSql" parameterType="map" resultMap="userMap">
select id, name, password,sex,age from user
<where>
<if test="pname!=null">
and name=#{pname}
</if>
<if test="psex!=null">
or sex=#{sex}
</if>
</where>
</select>
</mapper>
util包下新建MybatisUtil(工具类,加载mybatis核心配置文件,获取数据库连接,得到sqlSession ,关闭sqlSession )
MybatisUtil.java
package com.lianwei.util;
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 java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
/**
* 工具类
* @author AdminTC
*/
public class MybatisUtil {
private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
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 main(String[] args) {
Connection conn = MybatisUtil.getSqlSession().getConnection();
System.out.println(conn!=null?"连接成功":"连接失败");
}
}
dao包下新建UserTest测试类
package com.lianwei.dao;
import com.lianwei.entity.User;
import com.lianwei.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Tired on 2019/8/6.
*/
public class UserTest {
public static void main(String[] args) {
//增加
User user = new User();
user.setId(6);
user.setName("张三");
user.setPassword("123");
user.setSex("男");
user.setAge("23");
addUser(user);
//删除
//deleteById(2);
//修改
//update(user);
/*根据id查询一条*/
/*User user =findById(1);
System.out.println(user);*/
//查询所有
/*List<User> list1 = findAll();
for(User c:list1) System.out.println(c);*/
//查询n条
/*List<User> list2 = findAllWithPage();
for(User c:list2) System.out.println(c);*/
//根据名字模糊查询n条
/* List<User> list3 = findByNameWithPage();
for(User c:list3) System.out.println(c);*/
//拼接sql语句
//List<User> list = findByDynaSql();
//for(User c:list) System.out.println(c);
}
private static List<User> findByDynaSql(){
Map<String, Object> map = new HashMap<String, Object>();
map.put("pname","上大号");
map.put("psex","男");
SqlSession sqlSession = MybatisUtil.getSqlSession();
List<User> list = sqlSession.selectList(User.class.getName()+".findByDynaSql", map);
sqlSession.commit();
MybatisUtil.closeSqlSession();
return list;
}
private static List<User> findByNameWithPage() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("name","%大%");
map.put("pstart", 2);
map.put("psize", 5);
SqlSession sqlSession = MybatisUtil.getSqlSession();
List<User> list = sqlSession.selectList(User.class.getName()+".findByNameWithPage", map);
sqlSession.commit();
MybatisUtil.closeSqlSession();
return list;
}
private static List<User> findAllWithPage() {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("pstart", 0);
map.put("psize", 3);
SqlSession sqlSession = MybatisUtil.getSqlSession();
List<User> list = sqlSession.selectList(User.class.getName()+".findAllWithPage", map);
sqlSession.commit();
MybatisUtil.closeSqlSession();
return list;
}
public static List<User> findAll(){
List<User> list =null;
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtil.getSqlSession();
list = sqlSession.selectList(User.class.getName()+".findAll");
sqlSession.commit();
}catch (Exception e){
e.printStackTrace();
sqlSession.rollback();
}finally {
MybatisUtil.closeSqlSession();
}
return list;
}
public static User findById(int id){
User user =null;
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtil.getSqlSession();
user = sqlSession.selectOne(User.class.getName()+".findById",id);
sqlSession.commit();
}catch (Exception e){
e.printStackTrace();
sqlSession.rollback();
}finally {
MybatisUtil.closeSqlSession();
}
return user;
}
public static void addUser(User user){
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtil.getSqlSession();
int i = sqlSession.insert(User.class.getName()+".addUser",user);
sqlSession.commit();
if(i>0) System.out.println("保存成功");
}catch (Exception e){
e.printStackTrace();
sqlSession.rollback();
}finally {
MybatisUtil.closeSqlSession();
}
}
private static void deleteById(int id) {
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtil.getSqlSession();
int i = sqlSession.delete(User.class.getName() + ".deleteById", id);
sqlSession.commit();
if (i > 0) System.out.println("根据id删除成功!");
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
} finally {
MybatisUtil.closeSqlSession();
}
}
private static void update(User user) {
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtil.getSqlSession();
int i = sqlSession.update(User.class.getName() + ".update", user);
sqlSession.commit();
if (i > 0) System.out.println("修改成功!");
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
} finally {
MybatisUtil.closeSqlSession();
}
}
}
最后,在核心配置文件中
- 设置实体类型别名,因为在实体映射文件中我们的paramType写的是user,这里的user其实是指com.lianwei.entity.User完整的路径
<!-- 设置类型别名 -->
<typeAliases>
<typeAlias type="com.lianwei.entity.User" alias="user"/>
</typeAliases>
- 加载映射文件(框架启动时先加载mybatis核心配置文件,在此文件中加载实体映射文件)
<!-- 加载映射文件-->
<mappers>
<mapper resource="com/lianwei/entity/UserMapper.xml"/>
</mappers>
测试--Run UserTest.java