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.使 ...
随机推荐
- mkdir: cannot create directory ‘/soft/hadoop-2.7.3/logs’: Permission denied问题
启动hadoop时,报错“mkdir: cannot create directory ‘/soft/hadoop-2.7.3/logs’: Permission denied” 注:/soft/ha ...
- 8.1 图像API
8.1 图像API Routine Description Drawing related functions GUI_AddRect() 调整矩形框的大小 GUI_GetClientRect() R ...
- Codeforces 743C - Vladik and fractions (构造)
Codeforces Round #384 (Div. 2) 题目链接:Vladik and fractions Vladik and Chloe decided to determine who o ...
- 【Java多线程系列随笔二】BlockingQueue
前言: 在新增的Concurrent包中,BlockingQueue很好的解决了多线程中,如何高效安全“传输”数据的问题.通过这些高效并且线程安全的队列类,为我们快速搭建高质量的多线程程序带来极大的便 ...
- JavaFX开发环境安装配置
JavaFX开发环境安装配置 从Java8开始,JDK(Java开发工具包)包括了JavaFX库. 因此,要运行JavaFX应用程序,您只需要在系统中安装Java8或更高版本. 除此之外,IDE(如E ...
- assignment of day four
目录 1.Numeric type (1)integer (2)float Usefulness Define How to use 2.string type Use Define How to u ...
- 5、如何快速找到多个字典中的公共键(key) 6 如何让字典保持有序 7 如何实现用户的历史记录功能(最多n条)
5.如何快速找到多个字典中的公共键(key) from random import randint,sample #随机取数 # a = sample("ABCDEF",randi ...
- Flyway - Version control for your database
Flyway 是什么? Flyway是个数据库版本管理工具.在开发过程中,数据库难免发生变更,例如数据变更,表结构变更.新建表或者视图等等. 在项目进行时无法保证一旦开发环境中的数据库内容变化候会去测 ...
- git的指令的一张很好的图
非常好的一张图
- 【学术篇】luogu3768 简单的数学题(纯口胡无代码)
真是一道"简单"的数学题呢~ 反演题, 化式子. \[ ans=\sum_{i=1}^n\sum_{j=1}^nijgcd(i,j) \\ =\sum_{i=1}^n\sum_{j ...