Mybatis使用Mapper方式CURD
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的更多相关文章
- mybatis入门--mapper代理方式开发
不使用代理开发 之前,我们说了如何搭建mybatis框架以及我们使用mybatis进行简单的增删改查.现在,我们一起来构建一个dao层的完整代码.并用@test来模拟service层对dao层进行一下 ...
- mybatis使用Dao和Mapper方式
1.配置jdcp.properties数据库连接文件 #mysql database setting jdbc.type=mysql jdbc.driver=com.mysql.jdbc.Driver ...
- MyBatis的Mapper文件的foreach标签详解
MyBatis的Mapper文件的foreach标签用来迭代用户传递过来的Lise或者Array,让后根据迭代来拼凑或者批量处理数据.如:使用foreach来拼接in子语句. 在学习MyBatis M ...
- Spring+SpringMVC+Mybatis大整合(SpringMVC采用REST风格、mybatis采用Mapper代理)
整体目录结构: 其中包下全部是采用mybatis自动生成工具生成. mybatis自动生成文件 <?xml version="1.0" encoding="UTF- ...
- Spring Boot MyBatis 通用Mapper插件集成
Mybatis在使用过程中需要三个东西,每张表对应一个XXMapper.java接口文件,每张表对应一个XXMapper.xml文件,每张表对应一个Entity的Java文件. 其中XXMappe ...
- 关于使用mybatis中mapper instrances,通过session另一种操作方式
String resource = "mybatis-config.xml"; InputStream inputStream = null; try { // 获取SqlSess ...
- Mybatis通用Mapper
极其方便的使用Mybatis单表的增删改查 项目地址:http://git.oschina.net/free/Mapper 优点? 不客气的说,使用这个通用Mapper甚至能改变你对Mybatis单表 ...
- Spring Boot入门教程2-1、使用Spring Boot+MyBatis访问数据库(CURD)注解版
一.前言 什么是MyBatis?MyBatis是目前Java平台最为流行的ORM框架https://baike.baidu.com/item/MyBatis/2824918 本篇开发环境1.操作系统: ...
- mybatis的mapper接口代理使用的三个规范
1.什么是mapper代理接口方式? MyBatis之mapper代理方式.mapper代理使用的是JDK的动态代理策略 2.使用mapper代理方式有什么好处 使用这种方式可以不用写接口的实现类,免 ...
随机推荐
- 使用VS2015制作安装包( 含相关的下载链接)
补充: 在看下面的教程过程中,如果在下面的步聚1中没有 " Visual Studio Installer", 则需要通过下面的链接进行安装 Visual Studio Insta ...
- git: 使用submodule进行托管
问题描述: 当一个prj.git项目里引用了另外一个moduleA.git项目作为其一个子模块,由于该模块未完善后续可能将继续升级,也就是需要两套git分别管理prj.git与moduleA.git, ...
- 46-Ubuntu-系统信息-1-date和cal查看系统时间
序号 命令 作用 01 date 查看系统时间 02 cal calendar查看日历,-y选项可以查看一年的日历
- poj 1905 图形推算+二分
参考博客: 题意: 一根两端固定在两面墙上的杆 受热弯曲后变弯曲 求前后两个状态的杆的中点位置的距离 分析:见博客 代码: #include<stdio.h> #include<io ...
- 随笔-ansible-6
Ansible中的变量引用有时候需要双引号,有时候不需要双引号,这是因为Ansible是多人协作的作品,所以没有统一. 一切以官网说明为主,同时自己也要实践. 这是一个example.yml文件,我们 ...
- sqlserver 如何瞬间执行上万条数据
核心的内容是:使用自定义表类型 第一步:创建存储过程P_T1DeclareInfo_Upload_new 参数: T1DeclareInfo_UploadPNSN_Param 类型 T1Declar ...
- git基础1
git: 团队协作开发 版本管理 创建项目的文档 初始化 编写项目 把文件add到git仓库,其实是放到了git的代码暂存区 工作区有一个隐藏目录 .gi ...
- 移动端布局 + iscroll + 滚动事件
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name ...
- python 获取年月日时分秒 获取当前时间 datetime函数
import datetime#取当前时间print(datetime.datetime.now())#取年print(datetime.datetime.now().year)#取月print(da ...
- NX二次开发-UFUN求两个对象最短距离UF_MODL_ask_minimum_dist
NX9+VS2012 #include <uf.h> #include <uf_modl.h> #include <uf_ui.h> UF_initialize() ...