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的更多相关文章

  1. mybatis开发dao的方式

    mybatis基于传统dao的开发方式 第一步:开发接口 public interface UserDao { public User getUserById(int id) throws Excep ...

  2. 通过Mybatis原始Dao来实现curd操作

    环境的配置见我上一篇博客. 首先,在上一篇博客中,我们知道,SqlSession中封装了对数据库的curd操作,通过sqlSessionFactory可以创建SqlSession,而SqlSessio ...

  3. Mybatis使用Mapper方式CURD

    Mybatis 使用Dao代码方式进行增.删.改.查和分页查询. 1.Maven的pom.xml 2.配置文件 2.1.db.properties 2.2.mybatis.xml <?xml v ...

  4. mybatis源码学习--spring+mybatis注解方式为什么mybatis的dao接口不需要实现类

    相信大家在刚开始学习mybatis注解方式,或者spring+mybatis注解方式的时候,一定会有一个疑问,为什么mybatis的dao接口只需要一个接口,不需要实现类,就可以正常使用,笔者最开始的 ...

  5. Mybatis的dao层实现 接口代理方式实现规范+plugins-PageHelper

    Mybatis的dao层实现 接口代理方式实现规范 Mapper接口实现时的相关规范: Mapper接口开发只需要程序员编写Mapper接口而不用具体实现其代码(相当于我们写的Imp实现类) Mapp ...

  6. MyBatis开发Dao层的两种方式(原始Dao层开发)

    本文将介绍使用框架mybatis开发原始Dao层来对一个对数据库进行增删改查的案例. Mapper动态代理开发Dao层请阅读我的下一篇博客:MyBatis开发Dao层的两种方式(Mapper动态代理方 ...

  7. MyBatis开发Dao层的两种方式(Mapper动态代理方式)

    MyBatis开发原始Dao层请阅读我的上一篇博客:MyBatis开发Dao层的两种方式(原始Dao层开发) 接上一篇博客继续介绍MyBatis开发Dao层的第二种方式:Mapper动态代理方式 Ma ...

  8. 阶段3 1.Mybatis_06.使用Mybatis完成DAO层的开发_1 Mybatis中编写dao实现类的使用方式-查询列表

    就是自己写实现类的方式来开发 直接finish 把之前写的CRUD的代码复制到过来. 在把之前pom.xml里面的包的依赖也复制过来 复制到当前的pom.xml内 允许自动导入 以上步骤就是复制了一个 ...

  9. MyBatis最原始的实现curd的操作

    关于jdbc的缺点: 1.数据库链接创建释放频繁造成系统资源浪费从而影响系统性能.如果使用数据库连接池可以解决此问题. 2.sql语句在代码中硬编码,不利于维护,sql变动需要改变java代码 3.使 ...

随机推荐

  1. springboot入门级笔记

    springboot亮点:不用配置tomcat springboot不支持jsp 准备:配置jdk 配置maven 访问https://start.spring.io/ 并生成自己的springboo ...

  2. 剑指offer——74求1+2+3+n

    题目描述 求1+2+3+...+n,要求不能使用乘除法.for.while.if.else.switch.case等关键字及条件判断语句(A?B:C).   题解: 利用类的构造和析构 //利用类的构 ...

  3. JAVA 实现数据导入Phoenix

    需要导入的jar 包有: 实现代码: package cn.test; import java.sql.Connection; import java.sql.DriverManager; impor ...

  4. EF 线程内唯一对象

    ef 做了很多修改后一起提交 增 删 改查 也就是相应的操作后不提交最后一起提交 在Dal层创建一个 EF上下文工厂 public class DBContextFactory { public st ...

  5. 最长递增子序列nlogn的做法

    费了好大劲写完的  用线段树维护的 nlogn的做法再看了一下 大神们写的 nlogn  额差的好远我写的又多又慢  大神们写的又少又快时间  空间  代码量 哪个都赶不上大佬们的代码 //这是我写的 ...

  6. WAMP中的mysql设置密码(默认密码为空)及phpmyadmin的配置

    来自:  http://wenku.baidu.com/link?url=J4K28e1kt-_ykJLsOtS1b5T6hKj5IzL5hXSKIiB133AvPCUXLlxGKScsBsxi0mA ...

  7. 22-1-sort

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  8. ttytype - 终端设备映射的默认终端类型

    DESCRIPTION(描述) /etc/ttytype 文件把termcap/terminfo中的终端类型名与tty行关联起来.每行包括一种终端类型,后面跟着空格,然后是tty名(不带 /dev/ ...

  9. 笔记:TCP/IP基础知识

    TCP/IP是指利用IP进行通信时必须用到的协议群的统称. 互联网层(网络层) IP IP是跨越网络传送数据包,使整个网络都能收到数据的协议.IP地址在发送数据的时候作为主机的标识. ICMP 用来诊 ...

  10. 加载ubuntu的时候卡在‘SMBus Host Controller not enabled'错误

    实验系统:ubuntu-16.04.6-server-amd64 我在VMware安装完这个系统后进入发现卡在了’SMBus Host Controller not enabled‘里,后来查过网络发 ...