深入理解MyBatis(一)—MyBatis基础
来源:互联网 发布:linux登陆花屏 编辑:程序博客网 时间:2024/06/02 21:39
深入理解MyBatis(一)—MyBatis基础
MyBatis是一个可以自定义SQL,存储过程和高级映射的ORM框架;相比于传统的JDBC,MyBatis底层维护着数据库连接池避免了连接不断创建销毁带来的资源消耗,同时MyBatis的SQL语句写在配置文件里.实现了代码和SQL的解耦;另外MyBatis提供了数据库表字段与对象属性之间的映射,无需手动创建对象进行属性的赋值;
相比于Hibernate,Spring JPA等全自动的ORM框架,MyBatis是一种需要手写SQL的半自动化的ORM框架
个人主页:tuzhenyu’s page
原文地址:深入理解MyBatis(一)—MyBatis基础
(1) 基本原理
基本的处理流程
根据配置文件创建session工厂sessionFactory;
由SeesionFactory产生数据库会话session;
通过数据库会话session完成数据库具体的操作,增改查删和事务管理;
处理完后关闭会话session
MyBatis功能架构
API接口:由session会话暴露出具体的增改查删和事务管理操作接口;
数据处理:主要包括SQL查找,SQL解析,SQL执行和结果映射等;
底层支持:主要包括数据库连接管理,事务管理,配置资源加载解析和缓存机制等
(2) MyBatis基本使用
创建config.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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <!-- 配置数据库连接信息 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test" /> <property name="username" value="root" /> <property name="password" value="tuzhenyu" /> </dataSource> </environment> </environments> <mappers> <mapper resource="mybatis/mapping/UserMapper.xml"/> </mappers></configuration>
- 创建实体类用作映射对象
@Setter@Getterpublic class User { private int id; private String name; private String password; private String score;}
- 创建DAO层接口
public interface UserMapper { public User getUser(int id) throws Exception;}
创建Mapper代理
mapper作为根节点,其下面可以配置的元素节点有:select,update,insert,delete,cache,cache-ref,resultMap,sql
select的resultType用来定义查询的返回值类型,如果返回值是list类型则根据mapper方法的返回值类型确定是调用selectOne(返回单个对象调用)还是selectList
resultMap是用来完成高级输出结果映射。如果查询出来的列名和pojo的属性名不一致,通过定义一个resultMap对列名和pojo属性名之间作一个映射关系,也可以通过映射完成结果的中间处理。
<?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="mybatis.mapping.UserMapper"> <select id="getUser" parameterType="int" resultType="mybatis.domain.User"> select * from user where id=#{id} </select></mapper>
- 通过session工厂获取session会话,执行代理查询
public static void main(String[] args) throws Exception{ String resource = "mybatis/config.xml"; InputStream is = Main.class.getClassLoader().getResourceAsStream(resource); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession session = sessionFactory.openSession(); UserMapper userMapper = session.getMapper(UserMapper.class); User user = userMapper.getUser(1); System.out.println(user.getName()); }
(3) 动态SQL
- 条件判断
<select id="dynamicIfTest" parameterType="Blog" resultType="Blog"> select * from t_blog where 1 = 1 <if test="title != null"> and title = #{title} </if> <if test="content != null"> and content = #{content} </if> <if test="owner != null"> and owner = #{owner} </if></select>
- where 条件判断
<select id="dynamicWhereTest" parameterType="Blog" resultType="Blog"> select * from t_blog <where> <if test="title != null"> title = #{title} </if> <if test="content != null"> and content = #{content} </if> <if test="owner != null"> and owner = #{owner} </if> </where></select>
- foreach循环遍历
<select id="dynamicForeachTest" resultType="Blog"> select * from t_blog where id in <foreach collection="list" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
(4) 嵌套查询
嵌套查询主要是通过resultMap实现的高级映射查询,主要分为嵌套语句查询和嵌套结果查询
嵌套语句查询:嵌套查询主要是将select语句产生的结果传到resultMap中进行二次处理映射成符合要求的对象
先执行 queryBlogInfoById 的select方法对应的语句从Blog表里获取到ResultSet结果集;
取出ResultSet下一条有效记录,然后根据resultMap定义的映射规格,通过这条记录的数据z再进行相应的查询处理来构建对应的一个BlogInfo 对象。
当要对BlogInfo中的author属性进行赋值的时候,发现有一个关联的查询,此时Mybatis会先执行这个select查询语句,得到返回的结果,将结果设置到BlogInfo的author属性上;
对BlogInfo的posts进行赋值时,也有上述类似的过程。
重复2步骤,直至ResultSet. next () == false;
嵌套语句查询容易产生N+1问题,可以通过join的方法将多次查询转换成一次join查询
<resultMap type="com.foo.bean.BlogInfo" id="BlogInfo"> <id column="blog_id" property="blogId" /> <result column="title" property="title" /> <association property="author" column="blog_author_id" javaType="com.foo.bean.Author" select="com.foo.bean.AuthorMapper.selectByPrimaryKey"> </association> <collection property="posts" column="blog_id" ofType="com.foo.bean.Post" select="com.foo.bean.PostMapper.selectByBlogId"> </collection> </resultMap> <select id="queryBlogInfoById" resultMap="BlogInfo" parameterType="java.math.BigDecimal"> SELECT B.BLOG_ID, B.TITLE, B.AUTHOR_ID AS BLOG_AUTHOR_ID FROM LOULUAN.BLOG B where B.BLOG_ID = #{blogId,jdbcType=DECIMAL} </select>
嵌套结果查询:通过联合查询将结果一次性从数据库中取出,再利用ResultMap进行映射转换成需要的对象
- 通过left join的方式将数据一次性从数据库中取出
- 根据结果集的信息和BlogInfo 的resultMap定义信息,对返回的结果集在内存中进行组装、赋值,构造BlogInfo;
- 返回构造出来的结果List 结果。
<resultMap type="com.foo.bean.BlogInfo" id="BlogInfo"> <id column="blog_id" property="blogId"/> <result column="title" property="title"/> <association property="author" column="blog_author_id" javaType="com.foo.bean.Author"> <id column="author_id" property="authorId"/> <result column="user_name" property="userName"/> <result column="password" property="password"/> <result column="email" property="email"/> <result column="biography" property="biography"/> </association> <collection property="posts" column="blog_post_id" ofType="com.foo.bean.Post"> <id column="post_id" property="postId"/> <result column="blog_id" property="blogId"/> <result column="create_time" property="createTime"/> <result column="subject" property="subject"/> <result column="body" property="body"/> <result column="draft" property="draft"/> </collection> </resultMap>
<select id="queryAllBlogInfo" resultMap="BlogInfo"> SELECT B.BLOG_ID, B.TITLE, B.AUTHOR_ID AS BLOG_AUTHOR_ID, A.AUTHOR_ID, A.USER_NAME, A.PASSWORD, A.EMAIL, A.BIOGRAPHY, P.POST_ID, P.BLOG_ID AS BLOG_POST_ID , P.CREATE_TIME, P.SUBJECT, P.BODY, P.DRAFT FROM BLOG B LEFT OUTER JOIN AUTHOR A ON B.AUTHOR_ID = A.AUTHOR_ID LEFT OUTER JOIN POST P ON P.BLOG_ID = B.BLOG_ID </select>
(4) 总结
MyBatis的基本应用是创建Mapper代理将SQL与程序解耦,进一步的应用可以使用MyBatis的动态SQL,嵌入查询等高级特性;
- 深入理解MyBatis(一)—MyBatis基础
- 深入理解MyBatis(二)—MyBatis初始化
- 深入理解MyBatis(五)—MyBatis的插件机制
- 深入理解MyBatis(六)—MyBatis的缓存机制
- 深入理解MyBatis(七)—MyBatis事务
- 深入理解MyBatis(八)—Spring和MyBatis集成
- (一)Mybatis基础
- 《深入理解mybatis原理(一)》 Mybatis初始化机制详解
- 深入理解mybatis原理(一) Mybatis初始化机制详解
- Mybatis学习笔记--(一)Mybatis基础
- 深入理解mybatis
- 《深入理解mybatis原理》
- 深入理解mybatis
- 深入理解Mybatis
- 深入理解mybatis原理
- 深入理解mybatis
- Mybatis入门基础(一)
- 深入理解MyBatis框架——SqlSession
- CodeForces
- 编写现代 CSS 代码的 20 个建议
- JavaScript模板引擎
- 3993: [SDOI2015]星际战争
- 面试OR笔试33——矩阵中的路径
- 深入理解MyBatis(一)—MyBatis基础
- Ubuntu nginx配置虚拟主机
- 如何查看当前mysql的引擎
- 122. Best Time to Buy and Sell Stock II
- Optional类包含的方法介绍及其示例
- nyoj 79 拦截导弹
- MyBatis从入门到放弃七:二级缓存原理分析
- Ubuntu下截图及编辑软件
- KMP算法Java实现