Mybatis 使用Dao代码方式进行增、删、改、查和分页查询。

1、Maven的pom.xml


2、配置文件

2.1、db.properties

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>
<!-- 自动加载包下的所有映射文件 -->
<package name="com.mcs.mapper"/>
</mappers> </configuration>

2.3、log4j.xml

3、MybatisUtil工具类

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="com.mcs.mapper.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
id,name, sex, birthday, email, telephone, cellphone, address, department_id
from t_employee
where id = #{id}
</select> <select id="findAll" resultMap="employeeResultMap">
select
id,name, sex, birthday, email, telephone, cellphone, address, department_id
from t_employee
</select> <!-- 分页无条件查询所有员工信息 -->
<select id="findAllWithPage" parameterType="map" resultMap="employeeResultMap">
select
id,name, sex, birthday, email, telephone, cellphone, address, department_id
from t_employee
limit #{pstart}, #{psize}
</select> </mapper>

5、Mapper映射文件对应的接口文件

 package com.mcs.mapper;

 import java.util.List;
import java.util.Map; import com.mcs.entity.Employee; public interface EmployeeMapper { public void add(Employee employee) throws Exception;
public void updateById(Employee employee) throws Exception;
public void deleteById(Integer id) throws Exception;
public Employee findById(Integer id) throws Exception;
public List<Employee> findAll() throws Exception;
public List<Employee> findAllWithPage(Map<String, Object> pageMap) throws Exception; }

此文件应与Mapper在同一命名空间下

6、测试代码

 package com.mcs.test;

 import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map; import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; import com.mcs.entity.Employee;
import com.mcs.mapper.EmployeeMapper;
import com.mcs.util.MybatisUtil; public class TestEmployeeMapper {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(TestEmployeeMapper.class); private EmployeeMapper employeeMapper;
private SqlSession sqlSession = null; @Before
public void init() {
sqlSession = MybatisUtil.getSqlSession();
employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
} @After
public void destory() {
MybatisUtil.closeSqlSession();
} @Test
public void testFindById() throws Exception {
Employee employee = employeeMapper.findById();
logger.debug(employee);
} @Test
public void testFindAll() throws Exception {
List<Employee> employees = employeeMapper.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");
try {
employeeMapper.add(employee);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
throw e;
} logger.debug(employee);
} @Test
public void testEditById() throws Exception {
Employee employee = employeeMapper.findById();
employee.setDepartmentId();
employee.setAddress("天津"); try {
employeeMapper.updateById(employee);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
throw e;
} logger.debug(employee);
} @Test
public void testDeleteById() throws Exception {
Employee employee = employeeMapper.findById();
logger.debug(employee);
try {
employeeMapper.deleteById();
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
throw e;
} logger.debug("已成功删除员工:" + employee.getName());
} @Test
public void testFindAllWithPage()throws Exception {
Map<String, Object> pageMap = new LinkedHashMap<String, Object>();
Integer start = ;
Integer size = ;
pageMap.put("pstart", start);
pageMap.put("psize", size); List<Employee> employees = employeeMapper.findAllWithPage(pageMap); logger.debug(employees);
} }

Mybatis使用Mapper方式CURD的更多相关文章

  1. mybatis入门--mapper代理方式开发

    不使用代理开发 之前,我们说了如何搭建mybatis框架以及我们使用mybatis进行简单的增删改查.现在,我们一起来构建一个dao层的完整代码.并用@test来模拟service层对dao层进行一下 ...

  2. mybatis使用Dao和Mapper方式

    1.配置jdcp.properties数据库连接文件 #mysql database setting jdbc.type=mysql jdbc.driver=com.mysql.jdbc.Driver ...

  3. MyBatis的Mapper文件的foreach标签详解

    MyBatis的Mapper文件的foreach标签用来迭代用户传递过来的Lise或者Array,让后根据迭代来拼凑或者批量处理数据.如:使用foreach来拼接in子语句. 在学习MyBatis M ...

  4. Spring+SpringMVC+Mybatis大整合(SpringMVC采用REST风格、mybatis采用Mapper代理)

    整体目录结构: 其中包下全部是采用mybatis自动生成工具生成. mybatis自动生成文件 <?xml version="1.0" encoding="UTF- ...

  5. Spring Boot MyBatis 通用Mapper插件集成

    Mybatis在使用过程中需要三个东西,每张表对应一个XXMapper.java接口文件,每张表对应一个XXMapper.xml文件,每张表对应一个Entity的Java文件.   其中XXMappe ...

  6. 关于使用mybatis中mapper instrances,通过session另一种操作方式

    String resource = "mybatis-config.xml"; InputStream inputStream = null; try { // 获取SqlSess ...

  7. Mybatis通用Mapper

    极其方便的使用Mybatis单表的增删改查 项目地址:http://git.oschina.net/free/Mapper 优点? 不客气的说,使用这个通用Mapper甚至能改变你对Mybatis单表 ...

  8. Spring Boot入门教程2-1、使用Spring Boot+MyBatis访问数据库(CURD)注解版

    一.前言 什么是MyBatis?MyBatis是目前Java平台最为流行的ORM框架https://baike.baidu.com/item/MyBatis/2824918 本篇开发环境1.操作系统: ...

  9. mybatis的mapper接口代理使用的三个规范

    1.什么是mapper代理接口方式? MyBatis之mapper代理方式.mapper代理使用的是JDK的动态代理策略 2.使用mapper代理方式有什么好处 使用这种方式可以不用写接口的实现类,免 ...

随机推荐

  1. Hyperledger:常见加密算法分类列表

    算法原理查询:http://mathworld.wolfram.com   加密散列函数 (消息摘要算法,消息认证码,MD算法) Keyed-hash message authentication c ...

  2. 【Java多线程系列随笔一】浅析 Java Thread.join()

    一.在研究join的用法之前,先明确两件事情. 1.join方法定义在Thread类中,则调用者必须是一个线程, 例如: Thread t = new CustomThread(); //这里一般是自 ...

  3. Spring IOC源码分析(一):ApplicationContext体系结构设计之自底向上分析

    spring-context包1. ApplicationContext接口 public interface ApplicationContext extends EnvironmentCapabl ...

  4. 51-Ubuntu-打包压缩-1-打包压缩简介

    打包压缩是日常工作中备份文件的一种方式 在不同操作系统中,常用的打包压缩方式是不同的 Windows 常用 rar Mac 常用 zip Linux 常用 tar.gz

  5. hdu6319 Ascending Rating /// 单调队列

    题目大意: 给定n m k,p q r mod, 给出序列的前k项 之后的按公式 a[i]=(p×a[i-1]+q×i+r)%mod 递推 求序列中每个长度为m的连续区间的 该区间最大值与第一位的位置 ...

  6. Spark Streaming设计

  7. PD ZD

    PD TO ZD simple one without . SORT FIELDS,,PD,A,,,PD,A) OUTREC FIELDS,,PD,ZD,LENGTH, ,,PD,ZD,LENGTH, ...

  8. memset函数及其用法,C语言memset函数详解

    在前面不止一次说过,定义变量时一定要进行初始化,尤其是数组和结构体这种占用内存大的数据结构.在使用数组的时候经常因为没有初始化而产生“烫烫烫烫烫烫”这样的野值,俗称“乱码”. 每种类型的变量都有各自的 ...

  9. Vue for循环 例子

    demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf- ...

  10. ps去除元素的三种常用方法

    1.仿制图章工具,alt+鼠标左键进行选取复制区域,然后左键点击需要覆盖的区域. 2.套锁工具--选择区域--右键填充--内容识别.     3.修补工具,选中区域--拖动适配.     附带另一份较 ...