MyBatis系列:基于MyBatisUtils工具类完成CRUD操作
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis系列:基于MyBatisUtils工具类完成CRUD操作相关的知识,希望对你有一定的参考价值。
Emp.java
package com.rk.entity; public class Emp { private Integer id; private String name; private Double sal; public Emp(){} public Emp(Integer id, String name, Double sal) { this.id = id; this.name = name; this.sal = sal; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getSal() { return sal; } public void setSal(Double sal) { this.sal = sal; } }
EmpMapper.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="mynamespace"> <insert id="add" parameterType="com.rk.entity.Emp"> insert into emp(id,name,sal) values(#{id},#{name},#{sal}) </insert> <update id="update" parameterType="com.rk.entity.Emp"> update emp set name=#{name},sal=#{sal} where id=#{id} </update> <select id="findById" resultType="com.rk.entity.Emp"> select id,name,sal from emp where id=#{anything123} </select> <select id="findAll" resultType="com.rk.entity.Emp"> select id,name,sal from emp </select> <delete id="delete" parameterType="com.rk.entity.Emp"> delete from emp where id=#{id} </delete> </mapper>
findById也可以这样写
<!-- 根据ID查询 如果参数不是一个实体的话,只是一个普通变量,例如:int,double,String 这里的#{中间的变量名可以随便写},不过提倡就用方法的形参 --> <select id="findById" parameterType="int" resultType="com.rk.entity.Emp"> select id,name,sal from students where id = #{id} </select>
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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/testdb"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/rk/entity/EmpMapper.xml"/> </mappers> </configuration>
MyBatisUtils.java
package com.rk.utils; 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 MyBatisUtils { private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>(); private static SqlSessionFactory sqlSessionFactory; static{ try { Reader reader = Resources.getResourceAsReader("mybatis.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } } private MyBatisUtils() {} public static SqlSession getSqlSession(){ SqlSession sqlSession = threadLocal.get(); if(sqlSession == null){ sqlSession = sqlSessionFactory.openSession(); threadLocal.set(sqlSession); } return sqlSession; } public static void closeSqlSession(){ SqlSession sqlSession = threadLocal.get(); if(sqlSession != null){ sqlSession.close(); threadLocal.remove(); } } public static void main(String[] args) { Connection conn = MyBatisUtils.getSqlSession().getConnection(); System.out.println(conn!=null ? "连接成功" : "连接失败"); } }
EmpDao.java
package com.rk.dao; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import com.rk.entity.Emp; import com.rk.utils.MyBatisUtils; public class EmpDao { @Test public void add(){ Emp emp = new Emp(3, "小刚", 300D); SqlSession sqlSession = null; try { sqlSession = MyBatisUtils.getSqlSession(); int i = sqlSession.insert("mynamespace.add", emp); System.out.println("本次操作影响"+i+"行数据"); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); sqlSession.rollback(); } finally{ MyBatisUtils.closeSqlSession(); } } @Test public void update(){ Emp emp = new Emp(3, "Tomcat", 400D); SqlSession sqlSession = null; try { sqlSession = MyBatisUtils.getSqlSession(); int i = sqlSession.update("mynamespace.update", emp); System.out.println("本次操作影响"+i+"行数据"); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); sqlSession.rollback(); } finally{ MyBatisUtils.closeSqlSession(); } } @Test public void findById(){ SqlSession sqlSession = null; try { sqlSession = MyBatisUtils.getSqlSession(); Emp emp = sqlSession.selectOne("mynamespace.findById", 3); System.out.println( emp.getName() + ":"+emp.getSal()); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); sqlSession.rollback(); } finally{ MyBatisUtils.closeSqlSession(); } } @Test public void findAll(){ SqlSession sqlSession = null; try { sqlSession = MyBatisUtils.getSqlSession(); List<Emp> list = sqlSession.selectList("mynamespace.findAll"); if(list != null && list.size()>0){ for(Emp emp : list){ System.out.println( emp.getName() + ":"+emp.getSal()); } } sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); sqlSession.rollback(); } finally{ MyBatisUtils.closeSqlSession(); } } @Test public void delete(){ SqlSession sqlSession = null; try { sqlSession = MyBatisUtils.getSqlSession(); Emp emp = new Emp(3, "", 0D); sqlSession.delete("mynamespace.delete", emp); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); sqlSession.rollback(); } finally{ MyBatisUtils.closeSqlSession(); } } }
以上是关于MyBatis系列:基于MyBatisUtils工具类完成CRUD操作的主要内容,如果未能解决你的问题,请参考以下文章
SSM-MyBatis-10:Mybatis中SqlSession的getMapper()和简单的工具类MyBatisUtils
Java之SSM框架整合-案例IDEA版(一篇文章精通系列)Spring+SpringMVC+MyBatis(整合源代码)
Java之SSM框架整合-案例IDEA版(一篇文章精通系列)Spring+SpringMVC+MyBatis(整合源代码)