package loaderman; import java.io.IOException; import java.io.Reader; import java.sql.Connection; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; /** * 工具类 */ 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?"连接成功":"连接失败"); } }
package loaderman; /** * 学生 */ public class Student { private Integer id;//编号 private String name;//姓名 private Double sal;//薪水 public Student(){} public Student(Integer id, String name, Double sal) { this.id = id; this.name = name; this.sal = sal; } public Integer getId() { System.out.println("getId()"); return id; } public void setId(Integer id) { this.id = id; } public String getName() { System.out.println("getName()"); return name; } public void setName(String name) { this.name = name; } public Double getSal() { System.out.println("getSal()"); return sal; } public void setSal(Double sal) { this.sal = sal; } }
package loaderman; import java.util.List; import org.apache.ibatis.session.SqlSession; /** * 持久层 * @author AdminTC */ public class StudentDao1 { /** * 增加学生 */ public void add(Student student) throws Exception{ SqlSession sqlSession = null; try{ sqlSession = MybatisUtil.getSqlSession(); sqlSession.insert("loaderman.Student.add",student); sqlSession.commit(); }catch(Exception e){ e.printStackTrace(); sqlSession.rollback(); throw e; }finally{ MybatisUtil.closeSqlSession(); } } /** * 根据ID查询学生 */ public Student findById(int id) throws Exception{ SqlSession sqlSession = null; try{ sqlSession = MybatisUtil.getSqlSession(); Student student = sqlSession.selectOne("loaderman.Student.findById",id); sqlSession.commit(); return student; }catch(Exception e){ e.printStackTrace(); sqlSession.rollback(); throw e; }finally{ MybatisUtil.closeSqlSession(); } } /** * 查询所有学生 */ public List<Student> findAll() throws Exception{ SqlSession sqlSession = null; try{ sqlSession = MybatisUtil.getSqlSession(); return sqlSession.selectList("loaderman.Student.findAll"); }catch(Exception e){ e.printStackTrace(); throw e; }finally{ MybatisUtil.closeSqlSession(); } } /** * 更新学生 */ public void update(Student student) throws Exception{ SqlSession sqlSession = null; try{ sqlSession = MybatisUtil.getSqlSession(); sqlSession.update("loaderman.Student.update",student); sqlSession.commit(); }catch(Exception e){ e.printStackTrace(); sqlSession.rollback(); throw e; }finally{ MybatisUtil.closeSqlSession(); } } /** * 删除学生 */ public void delete(Student student) throws Exception{ SqlSession sqlSession = null; try{ sqlSession = MybatisUtil.getSqlSession(); sqlSession.delete(Student.class.getName()+".delete",student); sqlSession.commit(); }catch(Exception e){ e.printStackTrace(); sqlSession.rollback(); throw e; }finally{ MybatisUtil.closeSqlSession(); } } public static void main(String[] args) throws Exception{ StudentDao1 dao = new StudentDao1(); // dao.add(new Student(1,"哈哈",7000D)); // dao.add(new Student(2,"呵呵",8000D)); // dao.add(new Student(3,"班长",9000D)); // dao.add(new Student(4,"键状高",10000D)); // Student student = dao.findById(4); List<Student> studentList = dao.findAll(); for(Student student : studentList){ System.out.print(student.getId()+":"+student.getName()+":"+student.getSal()); System.out.println(); } //Student student = dao.findById(3); //student.setName("靓班长"); //dao.update(student); // Student student = dao.findById(3); // System.out.print(student.getId()+":"+student.getName()+":"+student.getSal()); //dao.delete(student); } }
package loaderman; import org.apache.ibatis.session.SqlSession; /** * 持久层 */ public class StudentDao2 { /** * 增加学生 */ public void add(Student student) throws Exception{ SqlSession sqlSession = null; try{ sqlSession = MybatisUtil.getSqlSession(); sqlSession.insert("loaderman.Student.add",student); sqlSession.commit(); }catch(Exception e){ e.printStackTrace(); sqlSession.rollback(); throw e; }finally{ MybatisUtil.closeSqlSession(); } } /** * 根据ID查询学生 */ public Student findById(int id) throws Exception{ SqlSession sqlSession = null; try{ sqlSession = MybatisUtil.getSqlSession(); Student student = sqlSession.selectOne("loaderman.Student.findById",id); sqlSession.commit(); return student; }catch(Exception e){ e.printStackTrace(); sqlSession.rollback(); throw e; }finally{ MybatisUtil.closeSqlSession(); } } public static void main(String[] args) throws Exception{ StudentDao2 dao = new StudentDao2(); //dao.add(new Student(1,"班长",7000D)); Student student = dao.findById(1); if(student == null){ System.out.println("YES"); } System.out.println(student.getId()+":"+student.getName()+":"+student.getSal()); } }
<?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="loaderman.Student"> <resultMap type="loaderman.Student" id="studentMap"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="sal" column="sal"/> </resultMap> <!-- 增加学生 --> <insert id="add" parameterType="loaderman.Student"> insert into students(id,name,sal) values(#{id},#{name},#{sal}) </insert> <!-- 根据ID查询学生 如果参数不是一个实体的话,只是一个普通变量,例如:int,double,String 这里的#{中间的变量名可以随便写},不过提倡就用方法的形参 --> <select id="findById" parameterType="int" resultType="loaderman.Student"> select id,name,sal from students where id = #{id} </select> <!-- 查询所有学生 理论上resultType要写List<Student> 但这里只需书写List中的类型即可,即只需书写Student的全路径名 --> <select id="findAll" resultType="loaderman.Student"> select id,name,sal from students </select> <!-- 更新学生 --> <update id="update" parameterType="loaderman.Student"> update students set name=#{name},sal=#{sal} where id=#{id} </update> <!-- 删除学生 --> <delete id="delete" parameterType="loaderman.Student"> delete from students where id = #{id} </delete> <!-- <insert id="delete" parameterType="cn.loaderman.javaee.mybatis.app.Student"> delete from students where id = #{id} </insert> --> <!-- 注意:这个insert/update/delete标签只是一个模板,在做操作时,其实是以SQL语句为核心的 即在做增/删/时,insert/update/delete标签可通用, 但做查询时只能用select标签 我们提倡什么操作就用什么标签 --> </mapper>
<?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="studentNamespace"> <!-- 当实体属性与表字段名不相同的时候,必须书写以下代码 当实体属性与表字段名相同的时候,以下代码可选 --> <resultMap type="loaderman.Student" id="studentMap"> <id property="id" column="students_id"/> <result property="name" column="students_name"/> <result property="sal" column="students_sal"/> </resultMap> <!-- 增加学生 --> <insert id="add" parameterType="loaderman.Student"> insert into students(students_id,students_name,students_sal) values(#{id},#{name},#{sal}) </insert> <!-- 根据ID查询学生 mybatis会将查询出来的表记录和studentMap这个id所对应的映射结果相互匹配 --> <select id="findById" parameterType="int" resultMap="studentMap"> select students_id,students_name,students_sal from students where students_id = #{xxxxxxxxxxxxxxxxxx} </select> </mapper>
db.properties
mysql.driver=com.mysql.jdbc.Driver mysql.url=jdbc:mysql://127.0.0.1:3306/loaderman mysql.username=root mysql.password=root oracle.driver=oracle.jdbc.driver.OracleDriver oracle.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl oracle.username=scott oracle.password=tiger
<?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"/>
<!-- 设置类型别名 -->
<typeAliases>
<typeAlias type="loaderman.Student" alias="student"/>
</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>
<!-- 连接环境信息,取一个任意唯一的名字 -->
<environment id="oracle_developer">
<!-- mybatis使用jdbc事务管理方式 -->
<transactionManager type="jdbc"/>
<!-- mybatis使用连接池方式来获取连接 -->
<dataSource type="pooled">
<!-- 配置与数据库交互的4个必要属性 -->
<property name="driver" value="${oracle.driver}"/>
<property name="url" value="${oracle.url}"/>
<property name="username" value="${oracle.username}"/>
<property name="password" value="${oracle.password}"/>
</dataSource>
</environment>
</environments>
<!-- 加载映射文件-->
<mappers>
<mapper resource="loaderman/StudentMapper.xml"/>
</mappers>
</configuration>