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("[email protected]");
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);
} }