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. 使用linkedhashmap实现LRU(最近最少使用缓存算法)

    import java.util.LinkedHashMap; import java.util.Map; public class LRUCache<K, V> extends Link ...

  2. (转)C#中String跟string的“区别”

    string是c#中的类,String是.net Framework的类(在C# IDE中不会显示蓝色) C# string映射为.net Framework的String 如果用string,编译器 ...

  3. linux get current thread count and system threads limit

    get current thread count grep -s '^Threads' /proc/[0-9]*/status | awk '{ sum += $2; } END { print su ...

  4. HDU 6659 Acesrc and Good Numbers (数学 思维)

    2019 杭电多校 8 1003 题目链接:HDU 6659 比赛链接:2019 Multi-University Training Contest 8 Problem Description Ace ...

  5. Java全栈,MySQL搞透,架构手到擒来,还有面试官搞不定?

    五月最后一天啦,时间过得真快,做技术的难免做了几年就感觉很迷茫,那就需要多读点书,多学点技术才能有安全感. 栈长之前推荐过不少极客时间的课程,几乎每周都推荐一个,很多朋友评论说,课程太多学不过来,今天 ...

  6. 监控数据库SqlServer

    监控数据库的连接数select COUNT( * ) from master.dbo.sysprocesses select COUNT( * ) from master.dbo.sysprocess ...

  7. to meet you 常用类库与技巧

    1.Java的异常体系 2.从概念角度解析Java的异常处理机制 3.从责任角度看Java的异常体系 checked exception 必须try catch 或者继续向上抛出异常,否则编译不能通过 ...

  8. Javascript原型对象中的toString

    <script> //tostring function Person(name,age,gender){ this.name=name; this.age=age; this.gende ...

  9. projects

    layout title project 开源项目 本文记录我收藏的开源项目

  10. Oracle之视图联合查询加排序问题

    在公司修改bug,有这样的需求:需要从两张视图中查出相同字段的数据,按照导师姓名先排序,再按照学号排序 union联合两张表,SELECT * from((SELECT DS_ID,PYLX_ID,Y ...