Mybatis学习 - 开发总结

2 篇文章 0 订阅
2 篇文章 0 订阅

一、代理开发方式

  • mybatis代理开发方式是当前企业开发的主流

  • Mapper接口开发方法只需要程序员编写Mapper接口,有Mybatis框架根据接口定义创建接口的动态代理对象。

  • Mapper接口开发需要遵循以下规范:
    (1)Mapper.xml文件中的namespace与mapper接口的全限定名相同
    (2)Mapper.xml中定义的每个statement的id和Mapper接口的方法名相同
    (3)Mapper.xml中定义的每个sql的parameterType的类型和Mapper接口方法的输入参数类型相同
    (4)Mapper.xml中定义的每个sql的resultType的类型和Mapper接口方法的输出参数类型相同

  • DEMO
    在核心配置文件中加入映射配置文件:

   <!-- 核心配置文件SqlMapConfg.xml -->
   <typeAliases>
        <typeAlias type="mybatis.model.User" alias="user"/>
   </typeAliases>
   <mappers>
        <mapper resource="mapper/proxy/UserMapper.xml"/>
   </mappers>
	<!-- 映射配置文件 -->
	<!-- mapper 根标签;
     namespace 命名空间,与下面的语句id一起组成查询的标识 -->
<mapper namespace="mybatis.mapper.UserMapper">
    <!-- mybatis中默认定义了typeAlias, 所以这里type可以直接使用int,对应Integer
		 user则在核心配置文件中使用了typeAlias标签定义 -->
    <select id="queryById"  parameterType="int" resultType="user">
        select * from user where id=#{id}
    </select>
</mapper>
package mybatis.mapper;

public interface UserMapper {
    User queryById(Integer id);
}

测试用例

// 加载核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
// 获得sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
// 获取代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
System.out.println(userMapper.queryById(1));
sqlSession.close();

附:mybatis默认定义的typeAlias
mybatis默认定义的typeAlias

二、动态SQL语句

<if>

<foreach>

<where>

<sql> sql片段抽取

三、例子

XxxMapper.xml

 <select id="selectUsers" resultType="javaModel">
 	select
 		uuid uuid,
 		passenger_id passengerId,
 		create_time createTime,
 		register_type registerType
 	from t_recommend
 	where status=1
 </select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值