您的位置:首页 > 其它

mybatis学习笔记

2016-04-23 14:28 197 查看
Dao 层 需求:
1.对象能与数据库进行交互 
2.能执行sql语句 
---------------------
mybatis  
sqlSession作用:
1.向Sql语句中传入参数
2.执行sql语句 
3.获取执行sql语句的结果
4,事务的控制 

----------------------------
如何得到SqlSession:
1.通过配置文件获取到数据库连接的相关信息 
2.通过配置信息构建SqlSessionFactory
3.通过  SqlSessionFactory打开数据库会话

----------------------------------
OGNL vs  EL
OGNL  表达式  ,struts中使用 ,在mybatis中也使用 
OGNL  表达式
String 与基本数据类型 
自定义的类型   属性名 command
集合   {数组 array   List:list   Map:_parameter.key(Map<String,String>)或者 key.属性名}

mybatis  的xml文件中的foreach
<foreach collection="array" index="i" item="item">
在数组 array  和List中 i是指索引   Map中 i是指key值

操作符  ---java的操作符   + - * / == != || &&
         自己的特有的操作符  and or mod  in not in
------------------------------------------------------------------------
OGNL   可以直接用java的对象   直接支持java对象的方法 
<if test="command != null and !"".equals(command.trim())">
   
and COMMAND=#{command}
   </if>

------------------------------------
模糊匹配  '%' #{command} '%'

------------------------------------------
应用log4j  调试动态SQL
需要导入 log4j的jar包 以及log4j.properties 的配置文件 
properties配置文件中都是键值对的形式 

--------------------------------------
批量删除 

<delete id="deleteBatch" parameterType="java.util.List">
  delete from MESSAGE where ID in(
  <foreach collection="list" item="item" separator=",">
  #{item}
  </foreach>
  )
  </delete>

separator   分隔符 
--------------------------------------------
where  关键字  
<select id="queryMessageList" parameterType="com.imooc.bean.Message" resultMap="MessageResult">
    select ID,COMMAND,DESCRIPTION,CONTENT from MESSAGE
    <where>
    <if test="command != null and !"".equals(command.trim())">
   
and COMMAND=#{command}
   </if>
   <if test="description != null and !"".equals(description.trim())">
   
and DESCRIPTION like '%' #{description} '%'
   </if>
    </where>
  </select>

where关键字的作用 

1.代替where
2.当if中都不成立,等于无条件的检索 
3,若两个条件都满足 ,那么将第一个满足的and这个字去掉。,。。是的where的sql语句依然是正确的 
也就是成立的 

---------------------------------------------------
<sql> 标签

<select id="queryMessageList" parameterType="com.imooc.bean.Message" resultMap="MessageResult">
    select <include refid="columns"/> from MESSAGE
    <where>
    <if test="command != null and !"".equals(command.trim())">
   
and COMMAND=#{command}
   </if>
   <if test="description != null and !"".equals(description.trim())">
   
and DESCRIPTION like '%' #{description} '%'
   </if>
    </where>
  </select>

<sql id="columns">ID ,COMMAND,DESCRIPTION,CONTENT</sql>

-------------------------------------------------------\
set 标签
<update id="">
   <set>
    <if test="command != null and !"".equals(command.trim())">
   
and COMMAND=#{command}
   </if>
   <if test="description != null and !"".equals(description.trim())">
   
and DESCRIPTION like '%' #{description} '%'
   </if>
    </set>

</update>

1.代替set
2.如果有多个成立的话,将最后一个if中的语句的逗号去掉,确保sql语句的成功 

----------------------------------------------
trim  标签 

可以代替where标签和 set标签 
<trim prefix="where"  suffix=""  prefixOverrids="and|or" suffixOverrids=",">

</trim>

以下是可以代替set标签的  第一个字段代表是set的功能 ,第二个字段代表的是 将最后一个if语句中的逗号去掉,确保sql语句的正确
<trim prefix="set" suffixOverrides=",">

</trim>

---------------------------------------------------------------------
如果想要 你死我亡 的 类似if  else 的  
采用<choose>标签 

<choose>
  <when test="">
  </when>
   <when test="">
  </when>
 <when test="">
  </when>
 <when test="">
  </when>
  <otherwise></otherwise>
</choose>

----------------------------------------------------------
在主表中要关联到子表的值   定义的resultMap
如果javaBean中的属性是一个列表一样的集合 
 <resultMap type="com.imooc.bean.Message" id="MessageResult">
    <id column="ID" jdbcType="INTEGER" property="id"/>
    <result column="COMMAND" jdbcType="VARCHAR" property="command"/>
    <result column="DESCRIPTION" jdbcType="VARCHAR" property="description"/>
    <result column="CONTENT" jdbcType="VARCHAR" property="content"/>
    <collection property="javaBean中Message的属性"  resultMap="定义的类型的javaBean 的绝对路径" ></collection>  
</resultMap>
------------------------------------------------------

如果是子表中要关联到主表的引用
采用
assciation
4000
  具体用法和collection标签的用法一致
----------------------------------------------------------------------
resultMap  和 resultType的区别 

1.使用后者必须要保证查询的结果集中的列名和javaBean中的属性名相同,但是前者不必

 前者自己定义写好了resultMap,是靠id标签来的
2.在配置resultMap的时候可以通过一个typeHandler 属性来做类型转换

resultMap type="com.imooc.bean.Message" id="MessageResult">
    <id column="ID" jdbcType="INTEGER" property="id" typeHandler=""/>
    <result column="COMMAND" jdbcType="VARCHAR" property="command"/>
    <result column="DESCRIPTION" jdbcType="VARCHAR" property="description"/>
    <result column="CONTENT" jdbcType="VARCHAR" property="content"/>
    <collection property="javaBean中Message的属性"  resultMap="定义的类型的javaBean 的绝对路径" ></collection>  
</resultMap>

resultMap  可以进行属性之间的类型转换
3.都是表示结果集合java对象之间的对应关系

----------------------------------------------------------------------
parameterMap  和parameterType

parameterType 指向的java类型的 ,与OGNL  # {}  紧密相连的  ,可以是javaBean的对象 也可以是map

前者表明参数的属性和数据库的列名一致的  

------------------------------------------------------------
#{}     ${}的区别  
1.前者是将
select * from message where command=#{command}

编译的时候相当于将#{command}变成了 ?,然后通过statment进行setString赋值,进而成为完整的sql语句
select * from message where command=?

如果是select * from message where command=${command}   错的 
因为$是没有进行预编译的 。是直接将这个值放到sql语句上进行拼接的---并没有将其变为? 
${}会直接将command 比如段子放到sql语句上的 ,相当于拼一个字符串 
$符号加{}的话 。需要加单引号
select * from message where command=‘${command}’  加上单引号才是正确的 
 
'%${name}%'   相当于 ‘%’ #{name} '%'

order by这个是不需要被进行预编译的 ,不需要引号 ,所以这个时候采用$ ,比较好 
order by ${Id}

-------------------------------------------------------------------------
在sql语句中替换Not In 的方法 
not in  需要临时建立表 ,不建议用这样的做法 
参考http://blog.sina.com.cn/s/blog_70600f720101e7ib.html

----------------------------------------------------------------------------------
#{}   OGNL  的区别  
#{_parameter}  #{随便}  也是可以的 
但是 OGNL:{_paramerter}
------------------------------------------------------

若主表中是设定自增主键的,那么主表如何拿到这个键?

在插入一条信息到主表和子表的时候

<insert id="insert" userGenerateKeys="true"  KeyPropery="id" parameType="com.imooc.bean.Command">

<!-- 向资金流表里插入一条记录 并返回这条记录的Id-->
<insert id="InsertOneToWithdr"   parameterType="WithdrAlias"  useGeneratedKeys="true"  keyProperty="Id" > 
   
  insert into withdr(Id,type,mainId,cause,money,trantype,agId,agsum,usId,usersum,merId,mersum,syssum,status)
  values(null,#{type},#{mainId},#{cause},#{money},#{trantype},#{agId},#{agsum},#{usId},#{usersum},#{merId},#{mersum},#{syssum},#{status})

</insert>

----------------------------------------------------------------------------
乱码 
保险起见 ,
在Configuration.xml文件中 的 
数据库的url中  加入编码的设置 
  <property name="url" value="jdbc:mysql://192.168.0.132:3306/micro_message?useUnicode=true&characterEncoding=true"/>
----------------------------------------------------------------------------------------
接口式编程

xml配置文件的namespace  命名空间要和定义的接口的完全限定名要相同。。。然后定义一个接口,
在Dao层中处理中 ,
package com.imooc.dao;

import java.util.List;

import com.imooc.bean.Message;

/**
 * 与Message配置文件相对应的接口
 */
public interface IMessage {
/**
* 根据查询条件查询消息列表
*/
public List<Message> queryMessageList(Message message);
}

然后MessageDao类中 
 */
public List<Message> queryMessageList(Message message) {
DBAccess dbAccess = new DBAccess();
List<Message> messageList = new ArrayList<Message>();
SqlSession sqlSession = null;
try {
sqlSession = dbAccess.getSqlSession();
// 通过sqlSession执行SQL语句
IMessage imessage = sqlSession.getMapper(IMessage.class);
messageList = imessage.queryMessageList(message);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
return messageList;
}

xml文件的配置 
<mapper namespace="com.imooc.dao.IMessage">

  <resultMap type="com.imooc.bean.Message" id="MessageResult">
    <id column="ID" jdbcType="INTEGER" property="id"/>
    <result column="COMMAND" jdbcType="VARCHAR" property="command"/>
    <result column="DESCRIPTION" jdbcType="VARCHAR" property="description"/>
    <result column="CONTENT" jdbcType="VARCHAR" property="content"/>
  </resultMap>

  <select id="queryMessageList" parameterType="com.imooc.bean.Message" resultMap="MessageResult">
    select <include refid="columns"/> from MESSAGE
    <where>
    <if test="command != null and !"".equals(command.trim())">
   
and COMMAND=#{command}
   </if>
   <if test="description != null and !"".equals(description.trim())">
   
and DESCRIPTION like '%' #{description} '%'
   </if>
    </where>
  </select>
  
  <sql id="columns">ID,COMMAND,DESCRIPTION,CONTENT</sql>
  

--------------------------------------------------------------------------------------
接口式编程优点:
1.namespace不会进行冲突。。。
2.参数不是以object进行传入的,所以在编译的时候就可以进行判断。
IMessage imessage = sqlSession.getMapper(IMessage.class);
messageList = imessage.queryMessageList(message);
3.用在spring中。  
4.参数安全,返回的值也不是object ,而是具体的类型 

----------------------------------------------------------
package com.imooc.dao;

import java.util.List;

import com.imooc.bean.Message;

/**
 * 与Message配置文件相对应的接口
 */
public interface IMessage {
/**
* 根据查询条件查询消息列表
*/
public List<Message> queryMessageList(Message message);
}

1。没有实现类的接口,为什么就还可以执行????
采用的是动态代理

2.加载总的配置文件的时候,也就把其他配置文件也加载了 、。
--------------------------------------------------------------------------
mybatis  批量新增  
在xml文件中 写
<foreach collection="list" item="item" separator=",">

-----------------------------------------------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: