mybaits3 知识点总结

来源:互联网 发布:人工智能 呼叫中心 编辑:程序博客网 时间:2024/06/05 01:02
MyBatis 的 XML 配置文件包含了影响 MyBatis 行为甚深的设置和属性信息。 XML 文档
的高层级结构如下:
configuration 配置
  properties 属性(O)
  settings 设置  (O)
  typeAliases 类型命名 (O)
  typeHandlers 类型处理器
  objectFactory 对象工厂
  plugins 插件
  environments 环境
  environment 环境变量
  transactionManager 事务管理器
  dataSource 数据源
  mappers映射器


1.properties
mybatis-config文件中 获取变量的值,2种方式
<properties resource="org/mybaits/example/config.properties">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8" />
</properties>


config.properties文件
username=root
password=root




<dataSource type="POOLED">
<property name="driver" value="${driver}" />
<property name="url"    value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</dataSource>




2.settings
<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/> 
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="enhancementEnabled" value="false"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25000"/>
</settings>


3.typeAliases
<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>




7.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>


8.mappers映射器
<mappers>
<mapper resource="com/mybatis/dao/UserMapper.xml" />
</mappers>


例如:
<mapper namespace="com.mybatis.dao.UserMapper">
<select id="selectUser" parameterType="user" resultType="user">
SELECT * FROM user WHERE username=#{username} AND password=#{password}
</select>
<insert id="insertUser" parameterType="user" flushCache="true">
INSERT INTO user (id,username,password) VALUES
(#{id},#{username},#{password})
</insert>
<update id="updateUser" parameterType="user">
UPDATE user SET password=#{password} WHERE id=#{id}
</update>
<delete id="deleteUser" parameterType="int">
DELETE FROM user WHERE id=#{userId}
</delete>
</mapper> 


=====================================================================================
SQL 映射文件有很少的几个顶级元素(按照它们应该被定义的顺序):
  cache   -   配置给定命名空间的缓存。
  cache- ref  –   从其他命名空间引用缓存配置。
  resultMap  –  最复杂,也是最有力量的元素,用来描述如何从数据库结果集中来加
载你的对象。
  (parameterMap  –  已经被废弃了!老式风格的参数映射。内联参数是首选,这个元
素可能在将来被移除。这里不会记录。)
  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}  对应的sql语句中 由一个“?”来标识
------------------------------------------------------------------------------------
插入主键自动增长的情况有2个,数据库支持自动增长
<insert id="insertAuthor" parameterType="domain.blog.Author"
useGeneratedKeys=”true” keyProperty=”id”>
insert into Author (username,password,email,bio)
values (#{username},#{password},#{email},#{bio})
</insert> 
设置 useGeneratedKeys=”true”,而且设置 keyProperty 到你已经做好的目标属性。
如果数据库不支持自动增长,
<insert id="insertAuthor" parameterType="domain.blog.Author">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
select CAST(RANDOM()*1000000 as INTEGER) a from SYSIBM.SYSDUMMY1
</selectKey>
insert into Author
(id, username, password, email,bio, favourite_section)
values
(#{id}, #{username}, #{password}, #{email}, #{bio},
#{favouriteSection,jdbcType=VARCHAR}
)
</insert>


----------------------------------------------------------------------------------
sql--代码复用


<sql id=”userColumns”> id,username,password </sql>


<select id=”selectUsers” parameterType=”int” resultType=”hashmap”>
select <include refid=”userColumns”/>
from some_table  where id = #{id}
</select>
-----------------------------------------------------------------------------------
字符串替换
ORDER BY ${columnName},这里 MyBatis 不会修改或转义字符串。
但是这样有很大的风险,可能造成SQL注入
-----------------------------------------------------------------------------------
result Map
resultMap 元素是 MyBatis 中最重要最强大的元素


<resultMap id="userResultMap" type="User">
<id property="id" column="user_id" />
<result property="username" column="username"/>
<result property="password" column="password"/>
</resultMap>
<select id=”selectUsers” parameterType=”int”
resultMap=”userResultMap ”>
select user_id, user_name, hashed_password
from some_table
where id = #{id}
</select>




resultMap
  constructor  –   类在实例化时,用来注入结果到构造方法中
  idArg  –  ID 参数;标记结果作为 ID 可以帮助提高整体效能
  arg  –  注入到构造方法的一个普通结果
  id   –  一个 ID 结果;标记结果作为 ID 可以帮助提高整体效能
  result –   注入到字段或 JavaBean 属性的普通结果
  association –   一个复杂的类型关联;许多结果将包成这种类型
  嵌入结果映射  –   结果映射自身的关联,或者参考一个
  collection   –   复杂类型的集
  嵌入结果映射  –   结果映射自身的集,或者参考一个
  discriminator  –   使用结果值来决定使用哪个结果映射
  case –   基于某些值的结果映射
  嵌入结果映射  –   这种情形结果也映射它本身,因此可以包含很多相
同的元素,或者它可以参照一个外部的结果映射。
最佳实践:通常逐步建立结果映射。单元测试的真正帮助在这里。如果你尝试创建
一次创建一个向上面示例那样的巨大的结果映射,那么可能会有错误而且很难去控制它
来工作。开始简单一些,一步一步的发展。而且要进行单元测试!使用该框架的缺点是
它们有时是黑盒(是否可见源代码)。你确定你实现想要的行为的最好选择是编写单元
测试。它也可以你帮助得到提交时的错误。
下面一部分将详细说明每个元素。




<constructor>
<idArg column="id" javaType="int"/>
<arg column=”username” javaType=”String”/>
</constructor>
public class User {
//… 
public User(int id, String username) {
//…
}
//…
}


关联
association  property="author" column="blog_author_id" javaType=" Author">
<id property="id" column="author_id"/>
<result property="username" column="author_username"/>
</association>
关联元素处理“有一个”类型的关系。








<resultMap id=”blogResult” type=”Blog”>
<association property="author" column="blog_author_id" 
javaType="Author"  select=”selectAuthor”/>
</resultMap>
<select id=”selectBlog” parameterType=”int” resultMap=”blogResult”>
SELECT * FROM BLOG WHERE ID = #{id}
</select>
<select id=”selectAuthor” parameterType=”int” resultType="Author">
SELECT * FROM AUTHOR WHERE ID = #{id}
</select>
这种方式很简单,但是对于大型数据集合和列表将不会表现很好。问题就是我们熟知的
“N+1 查询问题”。
最佳实践
<select id="selectBlog" parameterType="int" resultMap="blogResult">
select
B.id as blog_id,
B.title as blog_title,
B.author_id as blog_author_id,
A.id as author_id,
A.username as author_username,
A.password as author_password,
A.email as author_email,
A.bio as author_bio
From Blog B left outer join Author A on B.author_id = A.id
where B.id = #{id}
</select>


<resultMap id="blogResult" type="Blog">
<id property=”blog_id” column="id" />
<result property="title" column="blog_title"/>
<association property="author" column="blog_author_id"
javaType="Author"  resultMap=”authorResult”/>
</resultMap>
<resultMap id="authorResult" type="Author">
<id property="id" column="author_id"/>
<result property="username" column="author_username"/>
<result property="password" column="author_password"/>
<result property="email" column="author_email"/> 
<result property="bio" column="author_bio"/>
</resultMap>
此处的resultMap authorResult可以重用,如果没有重用的必要,可以这样写
<resultMap id="blogResult" type="Blog">
<id property=”blog_id” column="id" />
<result property="title" column="blog_title"/>
<association property="author" column="blog_author_id"
javaType="Author">
<id property="id" column="author_id"/>
<result property="username" column="author_username"/>
<result property="password" column="author_password"/>
<result property="email" column="author_email"/>
<result property="bio" column="author_bio"/>
</association>
</resultMap>




------------------------------------------------------------------------------------
集合
<collection property="posts" ofType="domain.blog.Post">
<id property="id" column="post_id"/>
<result property="subject" column="post_subject"/>
<result property="body" column="post_body"/>
</collection>




private List<Post> posts;


<resultMap id=”blogResult” type=”Blog”>
<collection property="posts" javaType=”ArrayList” column="blog_id"  
ofType="Post" select=”selectPostsForBlog”/>
</resultMap>
<select id=”selectBlog” parameterType=”int” resultMap=”blogResult”>
SELECT * FROM BLOG WHERE ID = #{id}
</select>
<select id=”selectPostsForBlog” parameterType=”int” resultType="Author">
SELECT * FROM POST WHERE BLOG_ID = #{id}
</select>


解读代码:
<collection property="posts" javaType=”ArrayList” column="blog_id"
ofType="Post" select=”selectPostsForBlog”/>
读作:“在 Post 类型的 ArrayList 中的 posts 的集合。”
javaType 属性是不需要的,因为 MyBatis 在很多情况下会为你算出来。
------------------------------------------------------------------------------------
鉴别器
<discriminator javaType="int" column="draft">
<case value="1" resultType="DraftPost"/>
</discriminator>


例如:
<resultMap id="vehicleResult" type="Vehicle">
<id property=”id” column="id" />
<result property="vin" column="vin"/>
<result property="year" column="year"/>
<result property="make" column="make"/>
<result property="model" column="model"/>
<result property="color" column="color"/>
<discriminator javaType="int" column="vehicle_type">
<case value="1" resultMap="carResult"/>
<case value="2" resultMap="truckResult"/>
<case value="3" resultMap="vanResult"/>
<case value="4" resultMap="suvResult"/>
</discriminator>
</resultMap>
------------------------------------------------------------------------------------
缓存
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>,mybatis支持自定义缓存,具体可查阅相关文档进行学习。
------------------------------------------------------------------------------------
动态 SQL
  if
  choose(when,otherwise)
  trim(where,set)
  foreach
if
<select id=”findActiveBlogWithTitleLike”
parameterType=”Blog” resultType=”Blog”>
SELECT * FROM BLOG
WHERE state = „ACTIVE‟
<if test=”title != null”>
AND title like #{title}
</if>
</select>


choose(when,otherwise)
<select id=”findActiveBlogLike”
parameterType=”Blog” resultType=”Blog”>
SELECT * FROM BLOG WHERE state = “ACTIVE”
<choose>
<when test=”title != null”>
AND title like #{title}
</when>
<when test=”author != null and author.name != null”>
AND title like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>


trim, where, set解决where 1=1的情况
<select id=”findActiveBlogLike”
parameterType=”Blog” resultType=”Blog”>
SELECT * FROM BLOG
<where>
<if test=”state != null”>
state = #{state}
</if>
<if test=”title != null”>
AND title like #{title}
</if>
<if test=”author != null and author.name != null”>
AND title like #{author.name}
</if>
</where>
</select>




<update id="updateAuthorIfNecessary"
parameterType="domain.blog.Author">
update Author
<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
<if test="email != null">email=#{email},</if>
<if test="bio != null">bio=#{bio}</if>
</set>
where id=#{id}
</update>


这里,set 元素会动态前置 SET 关键字,而且也会消除任意无关的逗号,那也许在应用
条件之后来跟踪定义的值。






foreach
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>


你可以传递一个 List 实例或者数组作为参数对象传给 MyBatis。当你这么做的时
候, MyBatis 会自动将它包装在一个 Map 中,用名称在作为键。 List 实例将会以“list”
作为键,而数组实例将会以“array”作为键。


------------------------------------------------------------------------------------
insert into Author (id,username,password,email,bio)
0 0
原创粉丝点击