mybatis的Dao开发(Mapper动态代理方式)官方推荐使用

Mapper接口开发方法只需要程序员编写Mapper接口(相当于Dao接口),由Mybatis框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。

Mapper接口开发需要遵循以下规范:

  1. Mapper.xml文件中的namespace与mapper接口的类路径相同。
  2. Mapper接口方法名和Mapper.xml中定义的每个statement的id相同
  3. Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql 的parameterType的类型相同
  4. Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同
<?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">

<!-- namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离 
注意:使用mapper代理方法开发,namespace有特殊重要的作用,namespace等于mapper接口地址
-->
<mapper namespace="cn.itcast.mybatis.mapper.UserMapper">

	<!-- 定义sql片段
	id:sql片段的唯 一标识
	
	经验:是基于单表来定义sql片段,这样话这个sql片段可重用性才高
	在sql片段中不要包括 where
	 -->
	<sql id="query_user_where">
		<if test="userCustom!=null">
			<if test="userCustom.sex!=null and userCustom.sex!=''">
				and user.sex = #{userCustom.sex}
			</if>
			<if test="userCustom.username!=null and userCustom.username!=''">
				and user.username LIKE '%${userCustom.username}%'
			</if>
			<if test="ids!=null">
			<!-- 使用 foreach遍历传入ids
			collection:指定输入 对象中集合属性
			item:每个遍历生成对象中
			open:开始遍历时拼接的串
			close:结束遍历时拼接的串
			separator:遍历的两个对象中需要拼接的串
			 -->
			 <!-- 使用实现下边的sql拼接:
			  AND (id=1 OR id=10 OR id=16) 
			  -->
			<foreach collection="ids" item="user_id" open="AND (" close=")" separator="or">
				<!-- 每个遍历需要拼接的串 -->
				id=#{user_id}
			</foreach>
			
			<!-- 实现  “ and id IN(1,10,16)”拼接 -->
			<!-- <foreach collection="ids" item="user_id" open="and id IN(" close=")" separator=",">
				每个遍历需要拼接的串
				#{user_id}
			</foreach> -->
			
			</if>
		</if>
	</sql>


	<!-- 定义resultMap
	将SELECT id id_,username username_ FROM USER 和User类中的属性作一个映射关系
	
	type:resultMap最终映射的java对象类型,可以使用别名
	id:对resultMap的唯一标识
	 -->
	 <resultMap type="user" id="userResultMap">
	 	<!-- id表示查询结果集中唯一标识 
	 	column:查询出来的列名
	 	property:type指定的pojo类型中的属性名
	 	最终resultMap对column和property作一个映射关系 (对应关系)
	 	-->
	 	<id column="id_" property="id"/>
	 	<!-- 
	 	result:对普通名映射定义
	 	column:查询出来的列名
	 	property:type指定的pojo类型中的属性名
	 	最终resultMap对column和property作一个映射关系 (对应关系)
	 	 -->
	 	<result column="username_" property="username"/>
	 
	 </resultMap>

	<!-- 用户信息综合查询
	#{userCustom.sex}:取出pojo包装对象中性别值
	${userCustom.username}:取出pojo包装对象中用户名称
	 -->
	<select id="findUserList" parameterType="cn.itcast.mybatis.po.UserQueryVo" 
			resultType="cn.itcast.mybatis.po.UserCustom">
	SELECT * FROM USER
	<!-- 
	where可以自动去掉条件中的第一个and
	 -->
	<where>
		<!-- 引用sql片段 的id,如果refid指定的id不在本mapper文件中,需要前边加namespace -->
		<include refid="query_user_where"></include>
		<!-- 在这里还要引用其它的sql片段  -->
	</where>
		
		
	</select>
	
	<!-- 用户信息综合查询总数
	parameterType:指定输入类型和findUserList一样
	resultType:输出结果类型
	 -->
	<select id="findUserCount" parameterType="cn.itcast.mybatis.po.UserQueryVo" resultType="int">
	   SELECT count(*) FROM USER 
	   
	  <!-- 
	where可以自动去掉条件中的第一个and
	 -->
	<where>
		<!-- 引用sql片段 的id,如果refid指定的id不在本mapper文件中,需要前边加namespace -->
		<include refid="query_user_where"></include>
		<!-- 在这里还要引用其它的sql片段  -->
	</where>
	   
	   
	</select>

	<!-- 在 映射文件中配置很多sql语句 -->
	<!-- 需求:通过id查询用户表的记录 -->
	<!-- 通过 select执行数据库查询
	id:标识 映射文件中的 sql
	将sql语句封装到mappedStatement对象中,所以将id称为statement的id
	parameterType:指定输入 参数的类型,这里指定int型 
	#{}表示一个占位符号
	#{id}:其中的id表示接收输入 的参数,参数名称就是id,如果输入 参数是简单类型,#{}中的参数名可以任意,可以value或其它名称
	
	resultType:指定sql输出结果 的所映射的java对象类型,select指定resultType表示将单条记录映射成的java对象。
	 -->
	<select id="findUserById" parameterType="int" resultType="user">
		SELECT * FROM USER WHERE id=#{value}
	</select>
	
	<!-- 使用resultMap进行输出映射
	resultMap:指定定义的resultMap的id,如果这个resultMap在其它的mapper文件,前边需要加namespace
	-->
	<select id="findUserByIdResultMap" parameterType="int" resultMap="userResultMap">
		SELECT id id_,username username_ FROM USER WHERE id=#{value}
	</select>
	
	<!-- 根据用户名称模糊查询用户信息,可能返回多条
	resultType:指定就是单条记录所映射的java对象 类型
	${}:表示拼接sql串,将接收到参数的内容不加任何修饰拼接在sql中。
	使用${}拼接sql,引起 sql注入
	${value}:接收输入 参数的内容,如果传入类型是简单类型,${}中只能使用value
	 -->
	<select id="findUserByName" parameterType="java.lang.String" resultType="cn.itcast.mybatis.po.User">
		SELECT * FROM USER WHERE username LIKE '%${value}%'
	</select>
	
	<!-- 添加用户 
	parameterType:指定输入 参数类型是pojo(包括 用户信息)
	#{}中指定pojo的属性名,接收到pojo对象的属性值,mybatis通过OGNL获取对象的属性值
	-->
	<insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
		<!-- 
		将插入数据的主键返回,返回到user对象中
		
		SELECT LAST_INSERT_ID():得到刚insert进去记录的主键值,只适用与自增主键
		
		keyProperty:将查询到主键值设置到parameterType指定的对象的哪个属性
		order:SELECT LAST_INSERT_ID()执行顺序,相对于insert语句来说它的执行顺序
		resultType:指定SELECT LAST_INSERT_ID()的结果类型
		 -->
		<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
			SELECT LAST_INSERT_ID()
		</selectKey>
		insert into user(username,birthday,sex,address) value(#{username},#{birthday},#{sex},#{address})
		<!-- 
		使用mysql的uuid()生成主键
		执行过程:
		首先通过uuid()得到主键,将主键设置到user对象的id属性中
		其次在insert执行时,从user对象中取出id属性值
		 -->
		<!--  <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">
			SELECT uuid()
		</selectKey>
		insert into user(id,username,birthday,sex,address) value(#{id},#{username},#{birthday},#{sex},#{address}) -->
		
		
	</insert>
	
	<!-- 删除 用户
	根据id删除用户,需要输入 id值
	 -->
	<delete id="deleteUser" parameterType="java.lang.Integer">
		delete from user where id=#{id}
	</delete>
	
	<!-- 根据id更新用户
	分析:
	需要传入用户的id
	需要传入用户的更新信息
	parameterType指定user对象,包括 id和更新信息,注意:id必须存在
	#{id}:从输入 user对象中获取id属性值
	 -->
	<update id="updateUser" parameterType="cn.itcast.mybatis.po.User">
		update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} 
		 where id=#{id}
	</update>
	
</mapper>


namespace写上被增强类的限定名,由此进行捆绑.被增强接口类的方法注册到Mapper映射文件中

 

package cn.itcast.mybatis.mapper;

import java.util.List;

import cn.itcast.mybatis.po.User;
import cn.itcast.mybatis.po.UserCustom;
import cn.itcast.mybatis.po.UserQueryVo;

public interface UserMapper {
	
	//用户信息综合查询
	public List<UserCustom> findUserList(UserQueryVo userQueryVo) throws Exception;
	
	//用户信息综合查询总数
	public int findUserCount(UserQueryVo userQueryVo) throws Exception;
	
	//根据id查询用户信息
	public User findUserById(int id) throws Exception;
	
	//根据id查询用户信息,使用resultMap输出
	public User findUserByIdResultMap(int id) throws Exception;
	
	
	//根据用户名列查询用户列表
	public List<User> findUserByName(String name)throws Exception;
	
	//插入用户
	public void insertUser(User user)throws Exception;
	
	//删除用户
	public void deleteUser(int id)throws Exception;

}

 被增强类的方法名和Mapper.xml映射文件的id一致,返回值和resultType一致,注意,若java方法中返回值为List<UserCustomer>

映射文件的resultType的值是UserCustomer.

Public class UserMapperTest extends TestCase {

	private SqlSessionFactory sqlSessionFactory;
	
	protected void setUp() throws Exception {
		//mybatis配置文件
		String resource = "sqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		//使用SqlSessionFactoryBuilder创建sessionFactory
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	}

	
	Public void testFindUserById() throws Exception {
		//获取session
		SqlSession session = sqlSessionFactory.openSession();
		//获取mapper接口的代理对象
		UserMapper userMapper = session.getMapper(UserMapper.class);
		//调用代理对象方法
		User user = userMapper.findUserById(1);
		System.out.println(user);
		//关闭session
		session.close();
		
	}
	@Test
	public void testFindUserByUsername() throws Exception {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		List<User> list = userMapper.findUserByUsername("张");
		System.out.println(list.size());

	}
Public void testInsertUser() throws Exception {
		//获取session
		SqlSession session = sqlSessionFactory.openSession();
		//获取mapper接口的代理对象
		UserMapper userMapper = session.getMapper(UserMapper.class);
		//要添加的数据
		User user = new User();
		user.setUsername("张三");
		user.setBirthday(new Date());
		user.setSex("1");
		user.setAddress("北京市");
		//通过mapper接口添加用户
		userMapper.insertUser(user);
		//提交
		session.commit();
		//关闭session
		session.close();
	}
	

}

测试方法,先创建SqlSessionFactory生成sqlsession对象,sqlsession对象获取被增强接口类,被增强的接口类就可以调用自己的方法操作数据库.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值