mybatis知识点总结





mybatis:


持久层框架,属于数据访问层


mybatis和hibernate的区别?

mybatis: 半自动化持久层框架  可以自己配sql语句
hibernate: 全自动化持久层框架  不需自己配sql语句

mybatis和jdbc的区别:





环境搭建:


主要有配置文件和映射文件 

1. 下载jar包,官网  可以用在java project 或 web project

https://github.com/mybatis/mybatis-3/releases

需要mybatis 和 连接数据库 jar 包

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>

<!-- 全局别名,之后映射文件引用可以使用PersonEntity代替com.maven.mybatis.entity.PersonEntity-->
<typeAliases>
<typeAlias type="com.maven.mybatis.entity.PersonEntity" alias="PersonEntity"/>
</typeAliases>

<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=""/>
</dataSource>
</environment>
</environments>
<!-- 指定映射定义文件 -->
<mappers>
<mapper resource="com/maven/mybatis/mapper/PersonEntityMapper.xml"/>
</mappers>

</configuration>


常用的标签含义:

configuration 配置


properties 属性:

引入外部properties文件:

<properties resource="org/mybatis/example/config.properties">
 <property name="username" value="dev_user"/>
 <property name="password" value="F2Fa3!33TYyg"/>
</properties>
settings 设置
typeAliases 类型别名

别名配置2中方式:

1. 类型别名是为 Java 类型设置一个短的名字

<typeAliases>
 <typeAlias alias="Author" type="domain.blog.Author"/>
 <typeAlias alias="Blog" type="domain.blog.Blog"/>
 <typeAlias alias="Comment" type="domain.blog.Comment"/>
 <typeAlias alias="Post" type="domain.blog.Post"/>
 <typeAlias alias="Section" type="domain.blog.Section"/>
 <typeAlias alias="Tag" type="domain.blog.Tag"/>
</typeAliases>

2。 指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean
<typeAliases>
 <package name="domain.blog"/>
</typeAliases>

typeHandlers 类型处理器
objectFactory 对象工厂
plugins 插件
environments 环境


<environments default="development">
 <environment id="development">
<transactionManager type="JDBC">
 <property name="..." value="..."/>
</transactionManager>
<dataSource type="POOLED">
 <property name="driver" value="${driver}"/>
 <property name="url" value="${url}"/>
 <property name="username" value="${username}"/>
 <property name="password" value="${password}"/>
</dataSource>
 </environment>
</environments>


environment 环境变量
transactionManager 事务管理器

在 MyBatis 中有两种类型的事务管理器(也就是 type=”[JDBC|MANAGED]”

JDBC – 这个配置就是直接使用了 JDBC 的提交和回滚设置,它依赖于从数据源得到的连接来管理事务作用域。
MANAGED – 这个配置几乎没做什么。它从来不提交或回滚一个连接,而是让容器来管理事务的整个生命周期(比如 JEE 应用服务器的上下文)。
默认情况下它会关闭连接,然而一些容器并不希望这样,因此需要将 closeConnection 属性设置为 false 来阻止它默认的关闭行为
dataSource 数据源

有三种内建的数据源类型(也就是 type=”[UNPOOLED|POOLED|JNDI]

UNPOOLED– 这个数据源的实现只是每次被请求时打开和关闭连接
POOLED– 这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来,避免了创建新的连接实例时所必需的初始化和认证时间。 这是一种使得并发 Web 应用快速响应请求的流行处理方式
JNDI – 这个数据源的实现是为了能在如 EJB 或应用服务器这类容器中使用,容器可以集中或在外部配置数据源,然后放置一个 JNDI 上下文的引用。这种数据源配置只需要两个属性

databaseIdProvider 数据库厂商标识

mappers 映射器

引入映射文件4种方式:

<!-- 使用相对于类路径的资源引用 -->
<mappers>
 <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
 <mapper resource="org/mybatis/builder/BlogMapper.xml"/>
 <mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>


<!-- 使用完全限定资源定位符(URL) -->
<mappers>
 <mapper url="file:///var/mappers/AuthorMapper.xml"/>
 <mapper url="file:///var/mappers/BlogMapper.xml"/>
 <mapper url="file:///var/mappers/PostMapper.xml"/>
</mappers>


<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
 <mapper class="org.mybatis.builder.AuthorMapper"/>
 <mapper class="org.mybatis.builder.BlogMapper"/>
 <mapper class="org.mybatis.builder.PostMapper"/>
</mappers>


<!-- 将包内的映射器接口实现全部注册为映射器 -->
<mappers>
 <package name="org.mybatis.builder"/>
</mappers>



3. 编写映射文件    配置sql语句的相应操作 用于定义SQL语句和映射信息

<?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.maven.mybatis.mapper.PersonEntityMapper">
<select id="queryAll" resultType="PersonEntity">
select * from t_person
</select>

<insert id="insert" parameterType="PersonEntity">
insert into t_person(id, name) values(#{id}, #{name})
</insert>

</mapper>


常用标签:

resultMap – 是最复杂也是最强大的元素,用来描述如何从数据库结果集中来加载对象。

可以解决属性名和字段名冲突不一致的情形

<resultMap id="userResultMap" type="User">
 <id property="id" column="user_id" />
 <result property="username" column="user_name"/>
 <result property="password" column="hashed_password"/>
</resultMap>


sql – 可被其他语句引用的可重用语句块。

用来定义可重用的 SQL 代码段
insert – 映射插入语句
update – 映射更新语句
delete – 映射删除语句
select – 映射查询语句 

<select id="selectPerson" parameterType="int" resultType="hashmap">
 SELECT * FROM PERSON WHERE ID = #{id}
</select>


这个语句被称作 selectPerson,接受一个 int(或 Integer)类型的参数,并返回一个 HashMap 类型的对象,其中的键是列名,值便是结果行中的对应值。


注意参数符号:


#{id}  表示去参数id的值


属性:

id 在命名空间中唯一的标识符,可以被用来引用这条语句。
parameterType 将会传入这条语句的参数类的完全限定名或别名。这个属性是可选的,因为 MyBatis 可以通过 TypeHandler 推断出具体传入语句的参数,默认值为 unset。
resultType 从这条语句中返回的期望类型的类的完全限定名或别名。注意如果是集合情形,那应该是集合可以包含的类型,而不能是集合本身。使用 resultType 或 resultMap,但不能同时使用。
resultMap 外部 resultMap 的命名引用。结果集的映射是 MyBatis 最强大的特性,对其有一个很好的理解的话,许多复杂映射的情形都能迎刃而解。使用 resultMap 或 resultType,但不能同时使用。



<insert id="insertAuthor">
 insert into Author (id,username,password,email,bio)
 values (#{id},#{username},#{password},#{email},#{bio})
</insert>


<update id="updateAuthor">
 update Author set
username = #{username},
password = #{password},
email = #{email},
bio = #{bio}
 where id = #{id}
</update>


<delete id="deleteAuthor">
 delete from Author where id = #{id}
</delete>






4. 调用


SqlSessionFactoryBuilder:该对象负责根据MyBatis配置文件SqlMapConfig.xml构建SqlSessionFactory实例
SqlSessionFactory:每一个MyBatis的应用程序都以一个SqlSessionFactory对象为核心。该对象负责创建SqlSession对象实例。
SqlSession:该对象包含了所有执行SQL操作的方法,用于执行已映射的SQL语句。 



例子:

String conf = "SqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource);


//创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder();
//通过SessionFactoryBuilder对象获取SqlSessionFactory
SqlSessionFactory sf = sfb.build(in);


//创建Session
SqlSession session = sf.openSession(); 

//执行增删改查操作




//NAMESPACE为SqlMapper.xml文件根标签的namespace属性
//第一个参数:指映射文件的id值:namespace.id
//第二个参数:指映射文件中匹配parameterType类型的实参

//增加
session.insert(NAMESPACE + ".insert", person);

//更新
session.update(NAMESPACE + ".update", person);

//删除
session.delete(NAMESPACE + ".delete", 100);

//查询多行记录
List<PersonEntity> personList = session.selectList(NAMESPACE + ".queryAll");



session.commit();

//执行完毕之后关闭
session.close();




sql映射的两种方式:

1. 基于id来映射 <上面写的>

注意: namespace="包名.映射文件名"
<mapper namespace="com.maven.mybatis.mapper.PersonEntityMapper">
<select id="queryAll" resultType="PersonEntity">
select * from t_person
</select>
</mapper>

2. 基于接口来映射

注意: namespace="包名.接口名"  id=""  必须和接口中方法名保持一致
<mapper namespace="com.maven.mybatis.mapper.PersonEntityDaoIF">
<select id="queryAll" resultType="PersonEntity">
select * from t_person
</select>
</mapper>

接口: PersonEntityDaoIF.java

public interface PersonEntityDaoIF{

public  List<PersonEntity> queryAll();

}

调用:

SqlSession session = sqlSessionFactory.openSession();
PersonEntityDaoIF mapper = session.getMapper(PersonEntity.class);//返回接口对象
mapper.queryAll();//调用接口中相应方法


session.close();


动态SQL:


<!-- if判断 -->
<select id="findUsersByCriteria" parameterType="User"
resultType="User">
SELECT * FROM t_user
<!-- 这个where标签会自动的删除第一个AND -->
<where>
<if test="name!=null and name!=''">
AND name like '%${name}%'
</if>
<if test="age!=null and age!=''">
AND age=#{age}
</if>
</where>
</select>



Sql片段:当我们通过条件查询用户所有信息,和通过条件查询所有用户的数量

<!-- 定义sql片段 
id属性:表示sql片段的唯一标识
一定要基于单标操作定义sql片段,这样这个sql片段的可重用性才高
在sql片段中不要包括where条件
-->
<sql id="query_user_where">
<if test="name!=null and name!=''">
AND name like '%${name}%'
</if>
<if test="age!=null and age!=''">
AND age=#{age}
</if>
</sql>




<!--引用sql片段-->
<where>
<!-- refid用来引用sql片段的id值,如果该sql片段不在本配置文件中需要加namespace的值 -->
<include refid="query_user_where"></include>
</where>



foreach:向sql传递数组或list时,用foreach构建SQL


<delete id="deleteBatch"> 
    delete from user where id in
    <foreach collection="array" item="id" index="index" open="(" close=")" separator=",">
      #{id}
    </foreach>
</delete>


- collection :collection属性的值有三个分别是list、array、map三种,分别对应的参数类型为:List、数组、map集合,我在上面传的参数为数组,所以值为array
- item:
- index:表示在迭代过程中每次迭代到的位置(下标)
- open:前缀
- close:后缀
- separator:分隔符,表示迭代时每个元素之间以什么分隔



一对一映射


resultType实现较为简单,对于多表映射中只要增加其他勒种属性即可完成映射。但是会新增一个子类,如果对查询结果没有要求可以用它。
resultMap实现较为复杂,需要自定义resultMap。但是不需要新增子类,用我们传统的对象模型即可完成映射,并且支持延迟加载的功能,而resultType不支持。
    


<resultMap type="cn.chinasofti.entity.Orders" id="resultMapOrder">
<!-- 配置Order主类信息  -->
<id column="id" property="id"/>
<result column="note" property="note"/>
<result column="createdate" property="createdate"/>

<association property="user" javaType="User">
<id column="uid" property="id"/>
<result column="username" property="username"/>
<result column="sex" property="sex"/>
<result column="address" property="address"/>
<result column="birthday" property="birthday"/>
</association>
</resultMap>

<select id="findOrderUserWithResultMap" resultMap="resultMapOrder">
SELECT 语句
</select>




- association属性:配置关联的表
- javaType属性:代表映射表中的实体对象的真实类型


一对多映射




<resultMap type="User" id="resultMapUser">
<!-- 配置User信息 -->
<id column="_uid" property="id"/>
<result column="username" property="username"/>
<result column="birthday" property="birthday"/>
<result column="sex" property="sex"/>
<result column="address" property="address"/>

<!-- 配置Orders集合信息 -->
<collection property="orders" ofType="Orders">
<id column="_oid" property="id"/>
<result column="createdate" property="createdate"/>
<result column="note" property="note"/>
</collection>
</resultMap>

<select id="findUserOrders" resultMap="resultMapUser">
SELECT 语句
</select>





- ofType属性:申明的是集合中元素的类型
!注意:当两个表的主键列名相同时,在配置的时候一定要为其配置一个别名,否者该类查询出的集合中只有一条数据



一级缓存:默认开启,是基于SqlSession范围的缓存
    二级缓存:默认不支持二级缓存,是基于Mapper范围的缓存


 
















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值