mybatis3学习笔记之Mapper编程
来源:互联网 发布:php 爬虫代码 编辑:程序博客网 时间:2024/06/06 12:51
参考源:
http://java.itcast.cn/news/20150512/13543033211.shtml 这是传智播客的燕青老师讲的 讲的很好 强烈推荐
- /**
- * Mapper接口
- * Mapper编程相比于自己编写Dao实现
- * 1、提取了Dao实现大量的模板代码
- * 2、避免了statement的硬编码
- * 3、避免了参数的传递为Object,在编译时即能检测出类型不正确
- * 4、传出参数的自动转换
- *
- * Mapper的Mapper接口文件与Mapper的配置文件遵循规则
- * 1、Mapper的配置文件的namespace值与Mapper接口文件的包一致
- * 2、Mapper配置文件的statement的编号与Mapper接口文件的方法名一致
- * 3、Mapper配置文件的statement的parameterType的类型与Mapper接口文件的方法的入参类型一致
- * 4、Mapper配置文件的statement的resultType的类型与Mapper接口文件的方法的返回值类型一致
- * @author u1
- *
- */
相应的地方都加了必要的注释 以单元测试检验功能
单例获取SqlSessionFactory 工具类
- package com.undergrowth.mybatis.util;
- import java.io.IOException;
- import java.io.InputStream;
- import org.apache.ibatis.io.Resources;
- import org.apache.ibatis.session.SqlSessionFactory;
- import org.apache.ibatis.session.SqlSessionFactoryBuilder;
- public class SqlSessionUtil {
- private static SqlSessionFactory sqlSessionFactory;
- /**
- * 单利获取SqlSessionFactory
- *
- * @param fileName
- * mybatis配置的文件名
- * @return SqlSessionFactory
- * @throws IOException
- */
- public static SqlSessionFactory getSqlSessionFactory(String fileName)
- throws IOException {
- if (sqlSessionFactory == null) {
- synchronized (SqlSessionUtil.class) {
- if (sqlSessionFactory == null) {
- InputStream inputStream = Resources
- .getResourceAsStream(fileName);
- sqlSessionFactory = new SqlSessionFactoryBuilder()
- .build(inputStream);
- }
- }
- }
- return sqlSessionFactory;
- }
- }
Mapper接口
- package com.undergrowth.mybatis.mapper;
- import java.util.List;
- import java.util.Map;
- import com.undergrowth.mybatis.po.City;
- import com.undergrowth.mybatis.po.CityQueryVo;
- /**
- * Mapper接口
- * Mapper编程相比于自己编写Dao实现
- * 1、提取了Dao实现大量的模板代码
- * 2、避免了statement的硬编码
- * 3、避免了参数的传递为Object,在编译时即能检测出类型不正确
- * 4、传出参数的自动转换
- *
- * Mapper的Mapper接口文件与Mapper的配置文件遵循规则
- * 1、Mapper的配置文件的namespace值与Mapper接口文件的包一致
- * 2、Mapper配置文件的statement的编号与Mapper接口文件的方法名一致
- * 3、Mapper配置文件的statement的parameterType的类型与Mapper接口文件的方法的入参类型一致
- * 4、Mapper配置文件的statement的resultType的类型与Mapper接口文件的方法的返回值类型一致
- * @author u1
- *
- */
- public interface CityMapper {
- public City fetchByCityById(int id);
- public List<City> findCityByName(String name);
- public void removeCityById(int id);
- public void insertCity(City city);
- public void insertCityAfter(City city);
- public void updateCity(City city);
- public int findCityCount(CityQueryVo vo);
- public int findCityCountByIds(CityQueryVo vo);
- public City findCityByHashmap(Map<String, Object> hashmap);
- }
相应的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的值与mapper的接口包 -->
- <mapper namespace="com.undergrowth.mybatis.mapper.CityMapper">
- <!-- #{}-表示占位符,对于简单类型、pojo、hashmap 简单类型使用#{value}或者其他名称都可 pojo使用ognl获取值
- 属性名.属性名.. ${}-表示拼接符 ,会导致sql注入 简单类型只能使用${value} pojo使用ognl获取值 -->
- <!-- sql片段 可重用 不用使用where -->
- <sql id="queryByName">
- <if test="city!=null">
- <if test="city.name!=null and city.name!=''">
- and city.name like '%${city.name}%'
- </if>
- </if>
- </sql>
- <!-- sql片段 -->
- <sql id="queryByIds">
- <if test="ids!=null">
- <!-- 集合遍历 合成效果 and id in(1,2,34,7) -->
- <foreach collection="ids" item="user_id" open="and id in("
- close=")" separator=",">
- #{user_id}
- </foreach>
- </if>
- </sql>
- <select id="fetchByCityById" resultType="com.undergrowth.mybatis.po.City"
- parameterType="int">
- select * from city where
- id = #{id}
- </select>
- <!-- 结果集映射 将表的列与pojo的属性进行映射 -->
- <resultMap type="City" id="queryIdNameCity">
- <result column="_id" property="id"></result>
- <result column="_name" property="name"></result>
- </resultMap>
- <select id="findCityByName" parameterType="string" resultMap="queryIdNameCity">
- select id _id,name _name from city where name like '%${value}%'
- </select>
- <select id="findCityCount" parameterType="com.undergrowth.mybatis.po.CityQueryVo"
- resultType="int">
- select count(1) from city
- <where>
- <!-- where 会自动去掉第一个and include引用之前定义的sql片段 -->
- <include refid="queryByName"></include>
- <!-- <if test="city!=null"> <if test="city.name!=null and city.name!=''">
- and city.name like '%${city.name}%' </if> </if> -->
- </where>
- </select>
- <select id="findCityCountByIds" parameterType="com.undergrowth.mybatis.po.CityQueryVo"
- resultType="int">
- select count(1) from city
- <where>
- <include refid="queryByIds"></include>
- </where>
- </select>
- <!-- resultType中返回单个pojo和列表pojo的区别在于 Mapper代理对象会根据Mapper接口的方法返回值 来选择使用selectOne还是selectList -->
- <select id="findCityByHashmap" parameterType="hashmap"
- resultType="City">
- select * from city where id=#{id} and name like '%${name}%'
- </select>
- <!-- 插入语句 -->
- <insert id="insertCity" parameterType="City" useGeneratedKeys="true"
- keyProperty="id">INSERT INTO city
- (
- Name,
- CountryCode,
- District,
- Population)
- VALUES
- (
- #{name},
- #{countryCode},
- #{district},
- #{population})
- </insert>
- <!-- 插入语句 获取自增的主键编号 -->
- <insert id="insertCityAfter" parameterType="City">
- <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
- select
- last_insert_id()
- </selectKey>
- INSERT INTO city
- (
- Name,
- CountryCode,
- District,
- Population)
- VALUES
- (
- #{name},
- #{countryCode},
- #{district},
- #{population})
- </insert>
- <!-- 更新 -->
- <update id="updateCity" parameterType="City">
- update city set
- population=#{population} where id=#{id}
- </update>
- <!-- 删除 -->
- <delete id="removeCityById">
- delete from city where id=#{id}
- </delete>
- </mapper>
mybatis的配置文件
- <?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/url元素的值 最后是parameterType传递的参数值 -->
- <properties resource="db.properties"></properties>
- <!-- mybatis运行时全局参数配置 -->
- <settings>
- <setting name="cacheEnabled" value="true"></setting>
- </settings>
- <!-- 类型别名 -->
- <typeAliases>
- <!-- <typeAlias type="com.undergrowth.mybatis.po.City" alias="City"></typeAlias> -->
- <!-- 批量定义别名 别名与类名一致 大小写均可以 -->
- <package name="com.undergrowth.mybatis.po" />
- </typeAliases>
- <!-- typeHandlers用于jdbc类型和java类型的转化 -->
- <typeHandlers></typeHandlers>
- <!-- 数据源和事务管理 -->
- <environments default="development">
- <environment id="development">
- <transactionManager type="JDBC" />
- <dataSource type="POOLED">
- <property name="driver" value="${jdbc.driver}" />
- <property name="url" value="${jdbc.url}" />
- <property name="username" value="${jdbc.username}" />
- <property name="password" value="${jdbc.password}" />
- </dataSource>
- </environment>
- </environments>
- <!-- sql映射 -->
- <mappers>
- <mapper resource="sqlmapper/CityMapper.xml" />
- <!-- 使用此种方式 需要Mapper接口文件与Mapper配置文件同名且位于同一目录 <mapper class=""/> -->
- </mappers>
- </configuration>
db.properties配置文件
- jdbc.driver=com.mysql.jdbc.Driver
- jdbc.url=jdbc\:mysql\://localhost\:3306/world
- jdbc.username=under
- jdbc.password=under
log4j.prroperties
- # Global logging configuration
- #\u5728\u5f00\u53d1\u73af\u5883\u4e0b\u65e5\u5fd7\u7ea7\u522b\u8981\u8bbe\u7f6e\u6210DEBUG\uff0c\u751f\u4ea7\u73af\u5883\u8bbe\u7f6e\u6210info\u6216error
- log4j.rootLogger=DEBUG, stdout
- # Console output...
- log4j.appender.stdout=org.apache.log4j.ConsoleAppender
- log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
- log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
两个pojo
- package com.undergrowth.mybatis.po;
- public class City {
- private int id;
- private String name;
- private String countryCode;
- private String district;
- private int population;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getCountryCode() {
- return countryCode;
- }
- public void setCountryCode(String countryCode) {
- this.countryCode = countryCode;
- }
- public String getDistrict() {
- return district;
- }
- public void setDistrict(String district) {
- this.district = district;
- }
- public int getPopulation() {
- return population;
- }
- public void setPopulation(int population) {
- this.population = population;
- }
- @Override
- public String toString() {
- return "City [id=" + id + ", name=" + name + ", countryCode="
- + countryCode + ", district=" + district + ", population="
- + population + "]";
- }
- }
- package com.undergrowth.mybatis.po;
- import java.util.List;
- /**
- * 包装用户查询的条件
- * @author u1
- *
- */
- public class CityQueryVo {
- private City city;
- private List<Integer> ids;
- public City getCity() {
- return city;
- }
- public void setCity(City city) {
- this.city = city;
- }
- public List<Integer> getIds() {
- return ids;
- }
- public void setIds(List<Integer> ids) {
- this.ids = ids;
- }
- }
最终的单元测试
- package com.undergrowth.mybatis.dao;
- import java.util.Arrays;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import org.apache.ibatis.session.SqlSession;
- import org.junit.Test;
- import com.undergrowth.mybatis.mapper.CityMapper;
- import com.undergrowth.mybatis.po.City;
- import com.undergrowth.mybatis.po.CityQueryVo;
- import com.undergrowth.mybatis.util.SqlSessionUtil;
- /**
- * Dao的测试类
- *
- * @author u1
- *
- */
- public class CityDao {
- /**
- * 通过ID查找对象
- */
- @Test
- public void fetchByCityById() {
- SqlSession sqlSession = null;
- City city = null;
- try {
- sqlSession = SqlSessionUtil
- .getSqlSessionFactory("mybatis-conf.xml").openSession();
- CityMapper cityMapper = sqlSession.getMapper(CityMapper.class);
- city = cityMapper.fetchByCityById(3);
- System.out.println(city);
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- } finally {
- if (sqlSession != null)
- sqlSession.close();
- }
- }
- /**
- * 通过模糊查询
- */
- @Test
- public void findCityByName() {
- SqlSession sqlSession = null;
- City city = null;
- try {
- sqlSession = SqlSessionUtil
- .getSqlSessionFactory("mybatis-conf.xml").openSession();
- // 使用Mapper进行查询 使用接口更加清晰 明了
- /*
- * CityMapper cityMapper=sqlSession.getMapper(CityMapper.class);
- * List<City> citys=cityMapper.findCityByName("und");
- * System.out.println(citys);
- */
- // 使用sqlsession进行查询
- List<City> citys = sqlSession.selectList("findCityByName", "und");
- System.out.println(citys);
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- } finally {
- if (sqlSession != null)
- sqlSession.close();
- }
- }
- /**
- * 查找数目
- */
- @Test
- public void findCityCount() {
- SqlSession sqlSession = null;
- try {
- sqlSession = SqlSessionUtil
- .getSqlSessionFactory("mybatis-conf.xml").openSession();
- // 使用Mapper进行查询 使用接口更加清晰 明了
- CityMapper cityMapper = sqlSession.getMapper(CityMapper.class);
- CityQueryVo vo = new CityQueryVo();
- City city = new City();
- city.setName("und");
- vo.setCity(city);
- int num = cityMapper.findCityCount(vo);
- System.out.println(num);
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- } finally {
- if (sqlSession != null)
- sqlSession.close();
- }
- }
- /**
- * 通过id集合查找数目
- */
- @Test
- public void findCityCountByIds() {
- SqlSession sqlSession = null;
- try {
- sqlSession = SqlSessionUtil
- .getSqlSessionFactory("mybatis-conf.xml").openSession();
- // 使用Mapper进行查询 使用接口更加清晰 明了
- CityMapper cityMapper = sqlSession.getMapper(CityMapper.class);
- CityQueryVo vo = new CityQueryVo();
- City city = new City();
- city.setName("und");
- vo.setCity(city);
- List<Integer> ids = Arrays.asList(1, 2, 3, 4, 5, 6);
- vo.setIds(ids);
- int num = cityMapper.findCityCountByIds(vo);
- System.out.println(num);
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- } finally {
- if (sqlSession != null)
- sqlSession.close();
- }
- }
- @Test
- public void findCityByHashmap() {
- SqlSession sqlSession = null;
- try {
- sqlSession = SqlSessionUtil
- .getSqlSessionFactory("mybatis-conf.xml").openSession();
- // 使用Mapper进行查询 使用接口更加清晰 明了
- CityMapper cityMapper = sqlSession.getMapper(CityMapper.class);
- Map<String, Object> hashmap=new HashMap<String, Object>();
- hashmap.put("id", "1");
- hashmap.put("name", "");
- City city=cityMapper.findCityByHashmap(hashmap);
- System.out.println(city);
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- } finally {
- if (sqlSession != null)
- sqlSession.close();
- }
- }
- /**
- * 插入对象
- */
- @Test
- public void insertCity() {
- SqlSession sqlSession = null;
- City city = new City();
- try {
- sqlSession = SqlSessionUtil
- .getSqlSessionFactory("mybatis-conf.xml").openSession();
- CityMapper cityMapper = sqlSession.getMapper(CityMapper.class);
- city.setName("under");
- city.setCountryCode("AFG");
- city.setDistrict("china");
- city.setPopulation(10000);
- cityMapper.insertCity(city);
- System.out.println("成功插入");
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- } finally {
- if (sqlSession != null)
- sqlSession.close();
- }
- }
- /**
- * 获取插入后的id
- */
- @Test
- public void insertCityAfter() {
- SqlSession sqlSession = null;
- City city = new City();
- try {
- sqlSession = SqlSessionUtil
- .getSqlSessionFactory("mybatis-conf.xml").openSession();
- CityMapper cityMapper = sqlSession.getMapper(CityMapper.class);
- city.setName("ww");
- city.setCountryCode("AFG");
- city.setDistrict("guangzhou");
- city.setPopulation(10000);
- cityMapper.insertCityAfter(city);
- System.out.println("成功插入");
- System.out.println(city.getId());
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- } finally {
- if (sqlSession != null)
- sqlSession.close();
- }
- }
- /**
- * 修改对象
- */
- @Test
- public void updateCity() {
- SqlSession sqlSession = null;
- City city = null;
- try {
- sqlSession = SqlSessionUtil
- .getSqlSessionFactory("mybatis-conf.xml").openSession();
- CityMapper cityMapper = sqlSession.getMapper(CityMapper.class);
- city = cityMapper.fetchByCityById(3);
- city.setPopulation(10000);
- System.out.println(city);
- cityMapper.updateCity(city);
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- } finally {
- if (sqlSession != null)
- sqlSession.close();
- }
- }
- /**
- * 移除对象
- */
- @Test
- public void removeCityById() {
- SqlSession sqlSession = null;
- City city = null;
- try {
- sqlSession = SqlSessionUtil
- .getSqlSessionFactory("mybatis-conf.xml").openSession();
- CityMapper cityMapper = sqlSession.getMapper(CityMapper.class);
- cityMapper.removeCityById(4);
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- } finally {
- if (sqlSession != null)
- sqlSession.close();
- }
- }
- }
本文主要是对Mapper编程的CRUD进行了学习 sql片段 输入映射 输出映射 进行了学习
0 0
- mybatis3学习笔记之Mapper编程
- mybatis3.2.7学习笔记1_Mapper编程
- Mybatis3文档阅读(三)之Mapper XML
- Mybatis学习笔记之mapper代理
- MyBATIS3入门学习笔记
- mybatis3学习笔记
- mybatis3学习笔记(一)
- springmvc学习笔记(7)-springmvc整合mybatis之mapper
- springmvc学习笔记(7)-springmvc整合mybatis之mapper
- mybatis mapper代理学习笔记
- Mybatis学习笔记之五:Mybatis3.X与Spring4.X的整合
- Mybatis3笔记。
- mybatis3源码学习之数据库连接池
- Mybatis3学习
- mybatis3中注解方式使用mapper
- 通用Mapper和PageHelper插件 学习笔记
- MyBatis源码学习笔记(七)mapper映射文件配置之insert、update、delete
- Mybatis 源码学习笔记(八)mapper映射文件配置之select、resultMap
- 浅谈Java中的hashcode方法
- Java静态内部类
- Linux下的Oracle编程技术
- Valid Palindrome
- 计算最大链路块
- mybatis3学习笔记之Mapper编程
- 小猫统计——导入通达信日K线数据
- 【卡特兰数】hdu 2067 小兔的棋盘
- 最小的k个数
- cache和内存的映射方式
- sublime text2 插件安装方法
- 1. Java简介
- 实现Runnable 多线程卖票
- 配置linux中可能遇到的问题总结