Mybatis使用Dao代码方式CURD
Mybatis 使用Dao代码方式进行增、删、改、查。
1、Maven的pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.</modelVersion>
<groupId>com.mcs</groupId>
<artifactId>mybatis01</artifactId>
<version>0.0.-SNAPSHOT</version> <properties>
<!-- Generic properties -->
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-</project.reporting.outputEncoding>
<!-- Custom properties -->
<mybatis.version>3.3.</mybatis.version>
</properties> <dependencies>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
<!-- 数据库连接驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
</dependency> <!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.0.</version>
</dependency>
</dependencies> <dependencyManagement>
<dependencies>
<dependency>
<groupId>io.spring.platform</groupId>
<artifactId>platform-bom</artifactId>
<version>2.0..RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement> <build>
<finalName>mybatis</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
<configuration>
<!-- Maven 跳过运行 Test 代码的配置 -->
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</build> </project>
2、配置文件
2.1、db.properties
jdbc.driverClass = com.mysql.jdbc.Driver
jdbc.jdbcUrl = jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8
jdbc.user = root
jdbc.password = root
2.2、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> <!-- 配置属性,加载数据库配置参数 -->
<properties resource="db.properties"></properties> <!-- 使用别名 -->
<typeAliases>
<!-- 为包下的所有文件设置别名,别名为类名,不分大小写 -->
<package name="com.mcs.entity"/>
</typeAliases> <!-- 和Spring整合后environments配置将废除 -->
<environments default="mysql_developer">
<environment id="mysql_developer">
<!-- mybatis使用jdbc事务管理方式 -->
<transactionManager type="JDBC" />
<!-- mybatis使用连接池方式来获取连接 -->
<dataSource type="POOLED">
<!-- 配置与数据库交互的4个必要属性 -->
<property name="driver" value="${jdbc.driverClass}" />
<property name="url" value="${jdbc.jdbcUrl}" />
<property name="username" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments> <!-- 加载映射文件 -->
<mappers>
<mapper resource="com/mcs/mapper/EmployeeMapper.xml" />
<mapper resource="com/mcs/mapper/DepartmentMapper.xml" /> <!-- 自动加载包下的所有映射文件 -->
<package name="com.mcs.mapper"/>
</mappers> </configuration>
2.3、log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="debug" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>
3、MybatisUtil工具类
package com.mcs.util; 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; /**
* Mybatis 工具类
*/
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?"连接成功":"连接失败");
}
}
4、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="EmployeeMapper">
<resultMap id="employeeResultMap" type="com.mcs.entity.Employee">
<id column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="sex" property="sex" jdbcType="VARCHAR" />
<result column="birthday" property="birthday" jdbcType="DATE" />
<result column="email" property="email" jdbcType="VARCHAR" />
<result column="telephone" property="telephone" jdbcType="VARCHAR" />
<result column="cellphone" property="cellphone" jdbcType="VARCHAR" />
<result column="address" property="address" jdbcType="VARCHAR" />
<result column="department_id" property="departmentId" jdbcType="INTEGER" />
</resultMap> <!-- 新增职员,并返回插入后的ID值 -->
<insert id="add" keyColumn="id" keyProperty="id" useGeneratedKeys="true" parameterType="Employee">
insert into t_employee
( name, sex, birthday, email, telephone, cellphone, address, department_id )
values
( #{name}, #{sex}, #{birthday}, #{email}, #{telephone}, #{cellphone}, #{address}, #{departmentId} )
</insert> <update id="updateById" parameterType="Employee">
update t_employee
set name = #{name,jdbcType=VARCHAR},
sex = #{sex,jdbcType=VARCHAR},
birthday = #{birthday,jdbcType=DATE},
email = #{email,jdbcType=VARCHAR},
telephone = #{telephone,jdbcType=VARCHAR},
cellphone = #{cellphone,jdbcType=VARCHAR},
address = #{address,jdbcType=VARCHAR},
department_id = #{departmentId,jdbcType=INTEGER}
where id = #{id,jdbcType=INTEGER}
</update> <delete id="deleteById" parameterType="Integer" >
delete from t_employee
where id = #{id}
</delete> <select id="findById" parameterType="Integer" resultMap="employeeResultMap">
select *
from t_employee
where id = #{id}
</select> <select id="findAll" resultMap="employeeResultMap">
select *
from t_employee
</select> </mapper>
5、Dao层接口
package com.mcs.dao; import java.util.List; import com.mcs.entity.Employee; public interface EmployeeDao { public Employee add(Employee employee) throws Exception;
public void edit(Employee employee) throws Exception;
public void deleteById(Integer id) throws Exception;
public Employee findById(Integer id) throws Exception;
public List<Employee> findAll() throws Exception; }
6、Dao层实现类
package com.mcs.dao.impl; import java.util.ArrayList;
import java.util.List; import org.apache.ibatis.session.SqlSession; import com.mcs.dao.EmployeeDao;
import com.mcs.entity.Employee;
import com.mcs.util.MybatisUtil; public class EmployeeDaoImpl implements EmployeeDao { public Employee add(Employee employee) throws Exception {
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtil.getSqlSession();
sqlSession.insert("EmployeeMapper.add", employee);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
throw e;
} finally {
MybatisUtil.closeSqlSession();
}
return employee;
} public void edit(Employee employee) throws Exception {
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtil.getSqlSession();
sqlSession.insert("EmployeeMapper.updateById", employee);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
throw e;
} finally {
MybatisUtil.closeSqlSession();
}
} public void deleteById(Integer id) throws Exception {
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtil.getSqlSession();
sqlSession.insert("EmployeeMapper.deleteById", id);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
throw e;
} finally {
MybatisUtil.closeSqlSession();
}
} public Employee findById(Integer id) throws Exception {
SqlSession sqlSession = null;
Employee employee = new Employee();
try {
sqlSession = MybatisUtil.getSqlSession();
employee = sqlSession.selectOne("EmployeeMapper.findById", id);
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
MybatisUtil.closeSqlSession();
}
return employee;
} public List<Employee> findAll() throws Exception {
SqlSession sqlSession = null;
List<Employee> employees = new ArrayList<Employee>();
try {
sqlSession = MybatisUtil.getSqlSession();
employees = sqlSession.selectList("EmployeeMapper.findAll");
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
MybatisUtil.closeSqlSession();
}
return employees;
} }
7、测试代码
package com.mcs.test; import java.util.Date;
import java.util.List; import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test; import com.mcs.dao.EmployeeDao;
import com.mcs.dao.impl.EmployeeDaoImpl;
import com.mcs.entity.Employee; public class TestEmployeeDao {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(TestEmployeeDao.class); private EmployeeDao employeeDao; @Before
public void init() {
employeeDao = new EmployeeDaoImpl();
} @Test
public void testFindById() throws Exception {
Employee employee = employeeDao.findById();
logger.debug(employee);
} @Test
public void testFindAll() throws Exception {
List<Employee> employees = employeeDao.findAll();
logger.debug(employees);
} @Test
public void testAdd() throws Exception {
Employee employee = new Employee();
employee.setName("赵小凤");
employee.setSex("female");
employee.setBirthday(new Date());
employee.setEmail("xiaofeng@126.com"); employee = employeeDao.add(employee); logger.debug(employee);
} @Test
public void testEditById() throws Exception {
Employee employee = employeeDao.findById();
employee.setDepartmentId();
employee.setAddress("天津"); employeeDao.edit(employee); logger.debug(employee);
} @Test
public void testDeleteById() throws Exception {
Employee employee = employeeDao.findById(); employeeDao.deleteById(); logger.debug("已成功删除员工:" + employee.getName());
} }
Mybatis使用Dao代码方式CURD的更多相关文章
- mybatis开发dao的方式
mybatis基于传统dao的开发方式 第一步:开发接口 public interface UserDao { public User getUserById(int id) throws Excep ...
- 通过Mybatis原始Dao来实现curd操作
环境的配置见我上一篇博客. 首先,在上一篇博客中,我们知道,SqlSession中封装了对数据库的curd操作,通过sqlSessionFactory可以创建SqlSession,而SqlSessio ...
- Mybatis使用Mapper方式CURD
Mybatis 使用Dao代码方式进行增.删.改.查和分页查询. 1.Maven的pom.xml 2.配置文件 2.1.db.properties 2.2.mybatis.xml <?xml v ...
- mybatis源码学习--spring+mybatis注解方式为什么mybatis的dao接口不需要实现类
相信大家在刚开始学习mybatis注解方式,或者spring+mybatis注解方式的时候,一定会有一个疑问,为什么mybatis的dao接口只需要一个接口,不需要实现类,就可以正常使用,笔者最开始的 ...
- Mybatis的dao层实现 接口代理方式实现规范+plugins-PageHelper
Mybatis的dao层实现 接口代理方式实现规范 Mapper接口实现时的相关规范: Mapper接口开发只需要程序员编写Mapper接口而不用具体实现其代码(相当于我们写的Imp实现类) Mapp ...
- MyBatis开发Dao层的两种方式(原始Dao层开发)
本文将介绍使用框架mybatis开发原始Dao层来对一个对数据库进行增删改查的案例. Mapper动态代理开发Dao层请阅读我的下一篇博客:MyBatis开发Dao层的两种方式(Mapper动态代理方 ...
- MyBatis开发Dao层的两种方式(Mapper动态代理方式)
MyBatis开发原始Dao层请阅读我的上一篇博客:MyBatis开发Dao层的两种方式(原始Dao层开发) 接上一篇博客继续介绍MyBatis开发Dao层的第二种方式:Mapper动态代理方式 Ma ...
- 阶段3 1.Mybatis_06.使用Mybatis完成DAO层的开发_1 Mybatis中编写dao实现类的使用方式-查询列表
就是自己写实现类的方式来开发 直接finish 把之前写的CRUD的代码复制到过来. 在把之前pom.xml里面的包的依赖也复制过来 复制到当前的pom.xml内 允许自动导入 以上步骤就是复制了一个 ...
- MyBatis最原始的实现curd的操作
关于jdbc的缺点: 1.数据库链接创建释放频繁造成系统资源浪费从而影响系统性能.如果使用数据库连接池可以解决此问题. 2.sql语句在代码中硬编码,不利于维护,sql变动需要改变java代码 3.使 ...
随机推荐
- python3使用requests和requests_toolbelt上传文件
https://blog.csdn.net/summerpowerz/article/details/80293235 https://blog.csdn.net/lhh08hasee/article ...
- linux进阶之路(二):linux文件目录
Linux的目录结构: Linux文件系统采用级层式的目录结构,最上层是根目录"/",在此目录下再创建其他目录. 树状的文件目录.再Linux世界,一切皆文件. /etc 所有系统 ...
- pair的用法
如何定义?(初始化) 1. pair<int,int>p; 2.定义即初始化,也可以这个样子 pair<,); 里面的类型还可以是string,double等. 3.还可以这样子初始 ...
- HCW 19 Team Round (ICPC format) H Houston, Are You There?(极角排序)
题目链接:http://codeforces.com/gym/102279/problem/H 大致题意: 你在一个定点,你有个长度为R的钩子,有n个东西在其他点处,问你能勾到的东西的数量是多少? 思 ...
- HBase启动错误提示别的机器60000已经存在
已经用cm 安装好了cdh,需要在上面添加HBase,并且做一个HBase故障转移功能,现在需要配置2个HMaster 在不同的机器上. 启动出现异常信息: 2015-12-23 14:44:38, ...
- 并发新构件之Exchanger:交换器
Exchanger:JDK描述:可以在对中对元素进行配对和交换的线程的同步点.每个线程将条目上的某个方法呈现给 exchange 方法,与伙伴线程进行匹配,并且在返回时接收其伙伴的对象.Exchang ...
- layui 封装自定义模块
转自:https://lianghongbo.cn/blog/430585105a35948c layui是国人开发的一款非常简洁的UI框架,使用了模块化加载方式,因此在使用过程中我们难免需要添加自己 ...
- Spark Streaming与Storm的对比
- 【学术篇】51nod 1238 最小公倍数之和
这是一道杜教筛的入(du)门(liu)题目... 题目大意 求 \[ \sum_{i=1}^n\sum_{j=1}^nlcm(i,j) \] 一看就是辣鸡反演一类的题目, 那就化式子呗.. \[ \s ...
- Tomcat服务器优化(内存,并发连接数,缓存)
a) 内存优化:主要是对Tomcat启动参数进行优化,我们可以在Tomcat启动脚本中修改它的最大内存数等等.b) 线程数优化:Tomcat的并发连接参数,主要在Tomcat配置文件中server.x ...