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 !"".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>
<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.属性名 |
提示:”“双引号的转义为"" 、 &&转义为&&
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 !"".equals(name.trim())">
and a.NAME=#{name}
</if>
<if test="description != null and !"".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( |
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
Mybtis框架总结(一)的更多相关文章
- IDEA+Maven 整合SSM框架实现简单的增删改查(新手入门,傻瓜操作)
原博客地址:https://blog.csdn.net/khxu666/article/details/79851070 选用SSM框架的原因在目前的企业级Java应用中,Spring框架是必须的.S ...
- SSM框架整合练习——一个简单的文章管理系统
使用SSM框架搭建的简易文章管理系统,实现了简单的增删改查功能. @ 目录 开发工具版本: 最终的项目结构 IDEA+Maven搭建项目骨架 1. 新建Maven项目: 2. 在新建的项目中添加所需要 ...
- ssm基础搭建步骤
今天搭建新的项目环境,从网上找了些ssm的搭建步骤,终于找到了一位csdn的大佬,可以说写的特别详细,按照上面步骤搭建即可,为了方便日后参考,转载到本人博客,原文链接:https://blog.csd ...
- SSM+Maven+IDEA增删改查
开发工具 IntelliJ IDEA Apache-tomcat-9.0 JDK 1.8 MySQL 8.0.11 Maven 3.5.4 IDEA+Maven搭建项目骨架 1. 新建Maven项目: ...
- 框架源码系列十二:Mybatis源码之手写Mybatis
一.需求分析 1.Mybatis是什么? 一个半自动化的orm框架(Object Relation Mapping). 2.Mybatis完成什么工作? 在面向对象编程中,我们操作的都是对象,Myba ...
- 一篇SSM框架整合友好的文章(二)
上一篇讲述了DAO 层,mybatis实现数据库的连接,DAO层接口设计,以及mybtis和spring的整合.DAO层采用接口设计方式实现,接口和SQL实现的分离,方便维护.DAO层所负责的仅仅是接 ...
- 避免重复造轮子的UI自动化测试框架开发
一懒起来就好久没更新文章了,其实懒也还是因为忙,今年上半年的加班赶上了去年一年的加班,加班不息啊,好了吐槽完就写写一直打算继续的自动化开发 目前各种UI测试框架层出不穷,但是万变不离其宗,驱动PC浏览 ...
- ABP入门系列(1)——学习Abp框架之实操演练
作为.Net工地搬砖长工一名,一直致力于挖坑(Bug)填坑(Debug),但技术却不见长进.也曾热情于新技术的学习,憧憬过成为技术大拿.从前端到后端,从bootstrap到javascript,从py ...
- 旺财速啃H5框架之Bootstrap(五)
在上一篇<<旺财速啃H5框架之Bootstrap(四)>>做了基本的框架,<<旺财速啃H5框架之Bootstrap(二)>>篇里也大体认识了bootst ...
随机推荐
- T24基础-基本命令(1)
如果你不知道什么是T24,那这篇文章对你意义不大.如果你所在银行IT刚好就准备使用或已经使用T24作为银行核心系统,那我的文章对你会很有帮助. 1. LIST 这个语句相当于SQL里的“select ...
- java如何在eclipse编译时自动生成代码
用eclipse写java代码,自动编译时,如何能够触发一个动作,这个动作是生成本项目的代码,并且编译完成后,自动生成的代码也编译好了, java编辑器中就可以做到对新生成的代码的自动提示? 不生成代 ...
- 两种设置disabled属性以及三种方法移除disabled属性
//两种方法设置disabled属性 $('#areaSelect').attr("disabled",true); $('#areaSelect').attr("dis ...
- .Net Office开源组件
1.NPOI NPOI 是 POI 项目的 .NET 版本.POI是一个开源的Java读写Excel.WORD等微软OLE2组件文档的项目.使用 NPOI 你就可以在没有安装 Office 或者相应环 ...
- jsonP跨域调用
-------------------------------------jsonP跨域调用------------------------------------- <div class=&q ...
- nsq
官网:http://nsq.io (1)描述 都是message broker,rabbitmq久经考验,nsq则是后起之秀.rabbitmq是erlang编写,nsq是golang. 安装:http ...
- 6、Samba 服务器配置
1.安装samba服务 [root@rhel6_80 samba]# yum -y install samba #安装samba [root@rhel6_80 samba]# rpm -qa |gre ...
- webpack-vue搭建,部署到后端
1.安装npm(安装node自带npm),npm安装成功测试 2.安装cnpm,也可以装nvm-windows 步骤1,打开user/admin/.npmrc,输入,也可以用命令 步骤2,输入npm ...
- 右键添加 CMD 命令提示符
# 右键添加 CMD 命令提示符 当然是修改注册表 - 打开注册表编辑器(按下Win+R打开运行对话框,输入regedit),找到[HKEY_CLASSES_ROOT/Folder/shell] ...
- java 用插入排序思想,对不规则数组排序。
知道插入排序后,无意中发现,用插入排序思想,对不规则数组排序的排序 发现和许多大神写的不一样,大神写的简洁多了.--------