javaEE核心框架之 Mybatis ( 二 )

MvBatls 核心对象的生命周期与封装

        SqlSessionFactoryBuilder 对象创建了SqlSessionFactory 后, SqlSessionFactoryBuilder类就不需要存在了,也就是不需要保持此对象的状态,可以随意的任由JVM 销毁,也就是说可以在方法内部声明SqlSessionFactoryBuilder对象来创建SqlSessionFactory 对象。

        SqlSessionFactory该实例应该在应用程序执行期间都存在,不需要在每一次操作数据库时都重新创建它,所以应用它的最佳方式就是写一个单例模式,或使用Spring框架来实现单例模式.

        SqlSession 对象 ,每个线程都应该有它自己的SqlSession 实例。SqlSession 的实例不能共享使用,因为它是线程不安全的,关闭SqlSession 很重要,你应该确保使用finally 来关闭它,

 
public class insertUserinfo extends HttpServlet {
    public void doGet { HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        SqlSession sqlSession = GetSqlSession.getSqlSession();
        try {
            //sqlSession curd code
            sqlSession.commit ();
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
        ) finally {
            sqlSession.close ();}
        }
    }
}

创建GetSqlSessionFactory类
    

使用单例设计模式来取得SqlSessionFactory 对象。

import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class GetSqlSessionFactory {

	private static SqlSessionFactory sqlSessionFactory;

	private GetSqlSessionFactory() {
	}

	synchronized public static SqlSessionFactory getSqlSessionFactory(){
		try {
			if (sqlSessionFactory == null) {
				String configFile = "mybatis-config.xml";
				InputStream configStream = Resources.getResourceAsStream(configFile);
				SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
				sqlSessionFactory = builder.build(configStream);
			}	
		}catch (IOException e){
			e.printStackTrace();
		}
		return sqlSessionFactory;
	}
}

创建GetSqlSession 类

public class GetSqlSession {

	private static ThreadLocal<SqlSession> tl = new ThreadLocal<>();

	public static SqlSession getSqlSession() throws IOException {
		SqlSession sqlSession = tl.get();
		if (sqlSession == null) {
			sqlSession = GetSqlSessionFactory.getSqlSessionFactory().openSession();
			tl.set(sqlSession);
		} 
		return sqlSession;
	}

	public static void commit() {
		if (tl.get() != null) {
			tl.get().commit();
			tl.get().close();
			tl.set(null);
		}
	}

	public static void rollback() {
		if (tl.get() != null) {
			tl.get().rollback();
			tl.get().close();
			tl.set(null);
		}
	}
}

创建DBOperate类

所有CURD 的参数值都用Map 对象进行封装

public class DBOperate {

	public void save(String sqlId, Map map) throws IOException {
		GetSqlSession.getSqlSession().insert(sqlId, map);
	}

	public void delete(String sqlId, Map map) throws IOException {
		GetSqlSession.getSqlSession().delete(sqlId, map);
	}

	public void update(String sqlId, Map map) throws IOException {
		GetSqlSession.getSqlSession().update(sqlId, map);
	}

	public List select(String sqlId, Map map) throws IOException {
		return GetSqlSession.getSqlSession().selectList(sqlId, map);
	}

}

userinfoMapping.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">
<mapper namespace="userinfo">
	<insert id="insertUserinfo" parameterType="map"
		useGeneratedKeys="true" keyProperty="id">
		insert into userinfo(username,password,age,createTime)
		values(#{username},#{password},#{age},#{createTime})
	</insert>

	<select id="selectAll" resultType="map">
		select * from userinfo order
		by id asc
	</select>

	<select id="selectById" parameterType="map" resultType="map">
		select *
		from userinfo where id=#{userId}
	</select>

	<select id="deleteById" parameterType="map">
		delete from userinfo where
		id=#{userId}
	</select>

	<update id="updateById" parameterType="map">
		update userinfo set username=#{username},
		password=#{password},
		age=#{age},
		createTime=#{createTime}
		where id=#{id}
	</update>

</mapper>

创建名称为test 的Servlet 对象

    测试在1 个请求中多次获取SqlSession 对象是不是1个

public class TestSqlSession {
	public static void main(String[] args) throws IOException {
		System.out.println(GetSqlSession.getSqlSession().hashCode());
		System.out.println(GetSqlSession.getSqlSession().hashCode());
		System.out.println(GetSqlSession.getSqlSession().hashCode());
		System.out.println(GetSqlSession.getSqlSession().hashCode());
		System.out.println(GetSqlSession.getSqlSession().hashCode());
		System.out.println(GetSqlSession.getSqlSession().hashCode());
		System.out.println(GetSqlSession.getSqlSession().hashCode());
	}
}


添加记录及异常回滚的测试

InsertUserinfo

public class InsertUserinfo {
	public static void main(String[] args) throws IOException {
		try {
			Map map = new HashMap();
			map.put("username", "渡西湖测试2");
			map.put("password", "duxihuceshi2");
			map.put("age", 666);
			map.put("createTime", new Date());

			DBOperate dbo = new DBOperate();
			dbo.save("insertUserinfo", map);
		} catch (Exception e) {
			e.printStackTrace();
			GetSqlSession.rollback();
		} finally {
			GetSqlSession.commit();
		}
	}
}

数据添加成功!


    InsertUserinfo2 执行发现两条数据都没有插入成功。

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import dbtools.DBOperate;
import dbtools.GetSqlSession;

public class InsertUserinfo2 {
	public static void main(String[] args) throws IOException {
		try {
			Map map1 = new HashMap();
			map1.put("username", "渡西湖测试1");
			map1.put("password", "duxihuceshi1");
			map1.put("age", 666);
			map1.put("createTime", new Date());

			Map map2 = new HashMap();
			map2.put("username", "渡西湖测试2");
			map2.put("password","duxihuceshi2duxihuceshi2duxihuceshi2duxihuceshi2" +
					"		     duxihuceshi2duxihuceshi2duxihuceshi2duxihuceshi2" +
					"			 duxihuceshi2duxihuceshi2duxihuceshi2duxihuceshi2");
			map2.put("age", 666);
			map2.put("createTime", new Date());

			DBOperate dbo = new DBOperate();
			dbo.save("insertUserinfo", map1);
			dbo.save("insertUserinfo", map2);

		} catch (Exception e) {
			e.printStackTrace();
			GetSqlSession.rollback();
		} finally {
			GetSqlSession.commit();
		}
	}
}

根据id删除

public class DeleteById {
	public static void main(String[] args) throws IOException {
		try {
			Map queryMap = new HashMap();
			queryMap.put("userId", 1L);

			DBOperate dbo = new DBOperate();
			dbo.delete("deleteById", queryMap);
		} catch (Exception e) {
			e.printStackTrace();
			GetSqlSession.rollback();
		} finally {
			GetSqlSession.commit();
		}
	}
}

查看所有列表

public class SelectAll {
	public static void main(String[] args) throws IOException {
		try {
			DBOperate dbo = new DBOperate();
			List<Map> listMap = dbo.select("selectAll", null);
			for (int i = 0; i < listMap.size(); i++) {
				Map map = listMap.get(i);
				System.out.println(map.get("ID") + " " + map.get("USERNAME") + " " + map.get("PASSWORD") + " "
						+ map.get("AGE") + " " + map.get("createTime"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			GetSqlSession.rollback();
		} finally {
			GetSqlSession.commit();
		}
	}
}

根据id查询

public class SelectById {
	public static void main(String[] args) throws IOException {
		try {
			Map queryMap = new HashMap();
			queryMap.put("userId", 1L);

			DBOperate dbo = new DBOperate();
			List<Map> listMap = dbo.select("selectById", queryMap);
			for (int i = 0; i < listMap.size(); i++) {
				Map map = listMap.get(i);
				System.out.println(map.get("ID") + " " + map.get("USERNAME") + " " + map.get("PASSWORD") + " "
						+ map.get("AGE") + " " + map.get("createTime"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			GetSqlSession.rollback();
		} finally {
			GetSqlSession.commit();
		}
	}
}

根据id更新

public class UpdateById {
	public static void main(String[] args) throws IOException {
		try {
			Map queryMap = new HashMap();
			queryMap.put("userId", 1L);

			DBOperate dbo = new DBOperate();
			List<Map> listMap = dbo.select("selectById", queryMap);
			if (listMap.size() == 1) {
				Map findMap = listMap.get(0);
				findMap.put("username", "渡西湖更新");
				findMap.put("password", "duxihugengxin");
				findMap.put("age", 8);
				findMap.put("createTime", new Date());
				findMap.put("id", findMap.get("ID"));

				dbo.update("updateById", findMap);
			}
		} catch (Exception e) {
			e.printStackTrace();
			GetSqlSession.rollback();
		} finally {
			GetSqlSession.commit();
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值