Mybtis框架总结(一)

一:Mybaits下载并搭建核心框架

1:下载mybatis的jar包;

2:创建mybatis框架链接数据库的配置文件Configuration.xml,格式如下

<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
<!--
<settings>
<setting name="useGeneratedKeys" value="false"/>
<setting name="useColumnLabel" value="true"/>
</settings>

 -->

//类的别名

<typeAliases>
<typeAlias alias="UserAlias" type="org.apache.ibatis.submitted.complex_property.User"/>
</typeAliases>

//数据库链接
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="" value=""/>
</transactionManager>
<dataSource type="UNPOOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/micro_message"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>

//xml文件映射
<mappers>
<mapper resource="com/imooc/config/sqlxml/Message.xml"/>
<mapper resource="com/imooc/config/sqlxml/Command.xml"/>
<mapper resource="com/imooc/config/sqlxml/CommandContent.xml"/>
</mappers>

</configuration>

 

数据库的操作:

1、加载驱动;

2、获取链接;

3、执行SQL语句;

4、获取操作结果封装信息;

5、返回操作结果;

SqlSession的作用:

1、向sql语句中传入参数;

2、执行sql语句;

3、获取执行sql语句的结果;

4、事物的控制;

我们如何获取SqlSession对象:

1、通过配置文件获取数据库链接相关信息;

2、通过配置信息构建SqlSessionFactory;

3、通过SqlSessionFactory打开数据库回话;

案例如下:

public class SqlSessionUtil{

     public SqlSession getSqlSession() throws IOException{

    //通过配置文件获取数据库链接信息

    Reader reader = Resources.getResourceAsReader("com/imooc/config/Configuration.xml");

    //通过配置文件创建一个SqlSessionFactory

    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);    

    // 通过sqlSessionFactory打开一个数据库会话
    SqlSession sqlSession = sqlSessionFactory.openSession();
    return sqlSession;

}

}

 

sqlSession对数据库的操作,如下:

/**
* 和message表相关的数据库操作
*/
public class MessageDao {

/**
* 根据查询条件查询消息列表
*/
public List<Message> queryMessageList(String command,String description) {
DBAccess dbAccess = new DBAccess();
List<Message> messageList = new ArrayList<Message>();
SqlSession sqlSession = null;
try {
sqlSession = dbAccess.getSqlSession();
Message message = new Message();
message.setCommand(command);
message.setDescription(description);
// 通过sqlSession执行SQL语句
messageList = sqlSession.selectList("Message.queryMessageList",message);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
return messageList;
}

/**
* 单条删除
*/
public void deleteOne(int id) {
DBAccess dbAccess = new DBAccess();
SqlSession sqlSession = null;
try {
sqlSession = dbAccess.getSqlSession();
// 通过sqlSession执行SQL语句
sqlSession.delete("Message.deleteOne", id);
sqlSession.commit();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
}

 

Messge.xml

<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="Message">

<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 !&quot;&quot;.equals(command.trim())">
and COMMAND=#{command}
</if>
<if test="description != null and !&quot;&quot;.equals(description.trim())">
and DESCRIPTION like '%' #{description} '%'
</if>
</where>
</select>

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

<delete id="deleteOne" parameterType="int">
delete from MESSAGE where ID = #{_parameter}
</delete>

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

OGNL表达式在mybatis中的运用(OGNL是一种功能强大的语言,如能调用java中的方法):

 
Mybatis中的OGNL表达式
取值范围 标签中的属性
取值写法 String与基本数据类型   _parameter
自定义实体类   属性名称
集合   数组:array
  List:list
  Map:_parameter
操作符 java常见操作符   +、—、*、/、==、!=、||、&&等等
OGNL特有操作符   and、or、mod、in、not in
从集合中取出一条数据 数组   array[索引](String[])
  array[索引].属性名称(Message[])
集合   list[索引](List<String>)
  list[索引].属性名(List<String>)
Map   _parameter.key(Map<String,String>)
  key.属性名(Map<String,String>)
利用foreach标签从集合中取出数据 <foreach colletion = "array" index = "i" item = "item">
数组 i:索引(下标) item
List
Map i:key item.属性名

提示:”“双引号的转义为&quot;&quot;    、 &&转义为&amp;&amp;

 

mybatis中Sql操作中的一对多关系的xml文件,如下

<?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="Command">
<resultMap type="com.imooc.bean.Command" id="Command">
<id column="C_ID" jdbcType="INTEGER" property="id"/>
<result column="NAME" jdbcType="VARCHAR" property="name"/>
<result column="DESCRIPTION" jdbcType="VARCHAR" property="description"/>

//用于一对多关系的sql查询;property 是com.imooc.bean.Command实体类中的CommandContent的集合属性,resultMap是commandContent.xml中的namespace.resultMap.id
<collection property="contentList" resultMap="CommandContent.Content"/>
</resultMap>

<select id="queryCommandList" parameterType="com.imooc.bean.Command" resultMap="Command">
select a.ID C_ID,a.NAME,a.DESCRIPTION,b.ID,b.CONTENT,b.COMMAND_ID
from COMMAND a left join COMMAND_CONTENT b
on a.ID=b.COMMAND_ID
<where>
<if test="name != null and !&quot;&quot;.equals(name.trim())">
and a.NAME=#{name}
</if>
<if test="description != null and !&quot;&quot;.equals(description.trim())">
and a.DESCRIPTION like '%' #{description} '%'
</if>
</where>
</select>
</mapper>

 

mybatis的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="CommandContent">
<resultMap type="com.imooc.bean.CommandContent" id="Content">
<id column="ID" jdbcType="INTEGER" property="id"/>
<result column="CONTENT" jdbcType="VARCHAR" property="content"/>
<result column="COMMAND_ID" jdbcType="VARCHAR" property="commandId"/>

//用于多对一的Mybatis,property是CommandContent实体类的属性 resultMap是person.xml中的namespace.resultMap.id

 <association property="person" javaType="com.kerwin.mybatis.pojo.Person" resultMap="namespace.resultMap.id">

      <id column="p_id" property="id"/>

      <result column="name" property="name"/>

</association

</resultMap>
</mapper>

 

Mybatis中的常用标签:

 
Mybaits中的常用标签
功能 标签名 使用方法
定义SQL语句 insert 插入
delete 删除
update 更新
select 查询
控制动态SQL拼接     foreach

delete from MESSAGE where ID in(
<foreach collection="list" item="item" separator=",">
#{item}
</foreach>
)
</delete>

 
 if

<where>
<if test="command != null and !&quot;&quot;.equals(command.trim())">
and COMMAND=#{command}
</if>
<if test="description != null and !&quot;&quot;.equals(description.trim())">
and DESCRIPTION like '%' #{description} '%'
</if>
</where>

 
 choose

<choose test="">

<when test = ""></when>

<when test = ""></when>

<when test = ""></when>

<otherwise></otherwise>

</choose> 

类似java中的if(){}if(){}if(){}语句

   格式化输出 where  用于解决sql语句中条件都不满足,去除where,and等 
 set 用于update语句中的去除 逗号、和set等 
 trim

<trim prefix="where" prefixOverrides="and/or" suffix = "" suffixOverrides=""></trim>  

prefix 是在前加where关键字   perfixOverrides 用于去除,suffix后加,suffixOverrides去除,可以代替where 、set标签

配置关联关系   collection  用于一对多的结果做关联 
associaction  用于多对一的结果做关联 
 定义常量 sql  用于定义sql常量 
 引用常量  include 用于引用sql常量 <include refid = "id"> 
配置java对象属性与查询结果中列名是对应关系  resultMap  结果对象属性对应标签 

 

在mybatis中容易混淆:

mybatis中容易混淆
resultMap resultType
resultMap赋值为resultMap标签中的id值,resultType赋值是实体类
paramerMap paramerType
 
#{} ${}
Mybatis表达式中使用的是#{}

 

 

二、Log4j日志

1、加入log4j的jar包,引入log4j.preperties,如下:

//DEBUG是输出信息级别,Console是信息输出位置(如控制台);信息级别有:debug、info、warn、error,有低到高,依次包含;mybatis中的级别为debug;

log4j.rootLogger=DEBUG,Console

//日志输出的的位置
log4j.appender.Console=org.apache.log4j.ConsoleAppender

//输出日志的布局
log4j.appender.Console.layout=org.apache.log4j.PatternLayout

//输出日志的自定义格式
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n

//个性化,为某个包配置输出级别
log4j.logger.org.apache=INFO

 

posted @ 2016-03-10 10:03  牧师963  阅读(1539)  评论(0编辑  收藏  举报