MyBatis学习小结
一款轻量级的ORM框架
全局配置文件 SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 加载全局配置, 延迟加载和二级缓存等 -->
<settings>
<setting name="lazyLoadingEnabled" value="true">
</setting>
<!-- 以下配置在mybatis的3.4.1版本后默认为false -->
<!-- <setting name="aggressiveLazyLoading" value="false"/> -->
<!-- <setting name="cacheEnabled" value="true"/> -->
<!-- 使用JDBC的getGeneratedKeys获取数据库自增主键值,默认为false -->
<setting name="useGeneratedKeys" value="true">
</setting>
<!-- 使用列别名替换列名,默认为true -->
<setting name="useColumnLabel" value="true">
</setting>
<!-- 开启驼峰标识命名转换,默认为false:Table(create_time) -> Entity(createTime) -->
<setting name="mapUnderscoreToCamelCase" value="true">
</setting>
</settings>
<!-- 定义别名 -->
<typealiases>
<!-- <typeAlias type="domain.User" alias="user"/> -->
<package name="domain">
</package>
</typealiases>
<!-- 事务及连接池,整合spring后需要在spring中进行配置 -->
<environments default="development">
<environment id="development">
<transactionmanager type="JDBC">
</transactionmanager>
<datasource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver">
</property>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis">
</property>
<property name="username" value="root">
</property>
<property name="password" value="root">
</property>
</datasource>
</environment>
</environments>
<!-- 加載映射文件 -->
<mappers>
<!-- 加载单个映射文件<mapper resource="sqlMap/UserMapper.xml" /> -->
<!-- 加载包下的所有映射文件(使用mapper代理) -->
<package name="mapperProxy">
</package>
</mappers>
</configuration>
基本映射文件
<?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="mabatis">
<select id="selectUser" resulttype="com.mybatis.entity.User">
<!-- 使用#{value}占位符 -->
select * from user where id = #{value}
<!-- 使用${value}拼接符,只能写value?可能会引起SQL注入 -->
select * from user where name like '%${value}%'
<!-- 使用字符连接符||,或函数concat(),oracle只能连接两个字符 !-->
select * from user where name like '%' || #{model.name} || '%'
</select>
</mapper>
获取MySQL自增主键ID的两种方式
1.使用mysql的 LAST_INSERT_ID() 函数:
<insert id="insertUser" parametertype="user">
<selectkey keyproperty="id" order="AFTER" resulttype="int">
select LAST_INSERT_ID()
</selectkey>
insert into user(username,birthday,sex,address) values(#{username}, #{birthday}, #{sex}, #{address})
<!-- 使用mybatis向oracle数据库添加/修改数据时尽量指定jdbcType -->
</insert>
2.使用 useGeneratedKeys 属性,可在全局配置文件中将此属性设为true:
<insert id="insertUser" keyproperty="id" parametertype="user" usegeneratedkeys="true">
insert into user(username,birthday,sex,address) values(#{username}, #{birthday}, #{sex}, #{address})
</insert>
获取非自增主键的id
使用MySQL的 UUID() 函数
使用Oracle的序列的伪列:seq_name.nextval
创建SqlSessionFactory
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
/**
* arg0:映射文件中的namespace + statement的id
* arg1:指定和映射文件中所匹配的parameterType类型的参数
*/
User user = sqlSession.selectOne("mabatis.selectUser", 1);
//更新操作需要手动提交事务
sqlSession.commit();
sqlSession.close();
使用mapper代理:只写接口,mybatis自动实现:
1. xml的namespace名要与dao接口的全类名一致
2. 方法名对应statement的id
3. 参数对应parameterType
4. 返回类型对应ResultType
//获取代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
动态SQL
if判断
where
foreach
sql片段:基于单表
若有多个参数,不需要写parameterType,但需要使用@Param注解绑定参数名称
<select id="findAll" resultType="product">
select * from product limit #{begin}, #{pageSize}
</select>
List<Product> findAll(@Param("begin") int begin, @Param("pageSize") int pageSize);
关联查询
左外连接查询(left join on):左方全查,右方只查询满足条件的
SQL使用多表连接查询,使用resultMap接收查询结果集:
<!-- autoMapping默认为false,只能自动映射基本属性,
关联映射要在collection和association中声明,属性少的话建议写上result -->
<resultmap automapping="true" id="orderMap" type="orders">
<!-- id一定要写清column和property,否则没有唯一标识符 -->
<id column="oid" property="oid">
</id>
<!-- property为引用对象名,使用ofType声明集合中元素的java类型 -->
<collection automapping="true" oftype="orderitem" property="orderitems">
<id column="itemid" property="itemid">
</id>
<!-- 使用javaType声明关联对象的java类型 -->
<association automapping="true" javatype="product" property="product">
<id column="pid" property="pid">
</id>
</association>
</collection>
</resultmap>
延迟加载
二级缓存
批量删除
<delete id="deleteBatch">
delete from emp where empno in
<!-- 在这里声明参数是数组或者List集合 -->
<foreach close=")" collection="array" item="empno" open="(" separator=",">
#{empno, jdbcType=INTEGER}
</foreach>
</delete>
<delete id="deleteBatch" parametertype="map">
delete from emp where empno in
<!-- 若参数类型为map,则直接写为map中存放数组的key即可 -->
<foreach close=")" collection="empnos" item="empno" open="(" separator=",">
#{empno, jdbcType=INTEGER}
</foreach>
</delete>
mybatis调用存储过程
<!-- 返回值也是map? -->
<select id="getUserSexCount" parameterMap="getUserSexCountMap" statementType="CALLABLE">
call get_user_sex_count(?,?)
</select>
<parameterMap type="java.util.Map" id="getUserSexCountMap">
<parameter property="sexid" jdbcType="INTEGER" mode="IN"/>
<parameter property="usercount" jdbcType="INTEGER" mode="OUT"/>
</parameterMap>
分页插件:pagehelper
<!-- 1. 首先引入分页插件 -->
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.0.0</version>
</dependency>
<!-- 2. 在mybatis的配置文件中配置插件及参数 -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!-- 分页参数合理化,不允许小于1或大于总页数的 -->
<property name="reasonable" value="true"/>
</plugin>
</plugins>
// 3. 使用,在请求方法中进行查询之前调用
@RequestMapping(value="/list")
public String list(@RequestParam(value="pageNo", defaultValue="1") Integer pageNo, Model model) {
//分页插件:查询之前调用,4为每页显示的数量
PageHelper.startPage(pageNo, 4);
//startPage方法后紧跟的查询就是一个分页查询
List<Employee> list = employeeService.selectAll(pageNo);
//封装了详细的分页信息,传入查询结果及连续显示的页数
PageInfo<Employee> pageInfo = new PageInfo<Employee>(list, 5);
model.addAttribute("pageInfo", pageInfo);
return "list";
}
mybatis-generator
generator.xml:默认在项目根路径下
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 数据库驱动包位置,手动生成才需要配置,若在项目中添加jar包就可以了 -->
<!-- <classPathEntry location=".\mysql-connector-java-5.1.39-bin.jar" /> -->
<context id="DB2Tables" targetRuntime="MyBatis3">
<!-- 不生成注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 数据库链接URL、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/shop" userId="root"
password="root">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 生成javaBean的包名和位置,.\指当前工程下 -->
<javaModelGenerator targetPackage="cn.mbq.model"
targetProject=".\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 生成的映射文件包名和位置 -->
<sqlMapGenerator targetPackage="cn.mbq.mapper"
targetProject=".\java">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 生成DAO的包名和位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="cn.mbq.dao" targetProject=".\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 不生成Example文件 -->
<table tableName="user" domainObjectName="User"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
</context>
</generatorConfiguration>
1.使用本地命令行的方式生成:
#同一目录下必须包含这些文件,最好不要带中文
java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite
2.使用java工程的方式创建:运行此java文件
public class Generator {
public static void main(String[] args) throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
// 默认文件在项目根路径下
File configFile = new File("src/generator.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
callback, warnings);
myBatisGenerator.generate(null);
}
}
MyBatis学习小结的更多相关文章
- Mybatis学习笔记之一(环境搭建和入门案例介绍)
一.Mybatis概述 1.1 Mybatis介绍 MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了go ...
- Mybatis学习笔记之二(动态mapper开发和spring-mybatis整合)
一.输入映射和输出映射 1.1 parameterType(输入类型) [传递简单类型] 详情参考Mybatis学习笔记之一(环境搭建和入门案例介绍) 使用#{}占位符,或者${}进行sql拼接. [ ...
- Mybatis 学习总结
1 Mybatis入门 1.1 单独使用jdbc编程问题总结 1.1.1 jdbc程序 public static void main(String[] args) { Connection conn ...
- mybatis学习笔记(10)-一对一查询
mybatis学习笔记(10)-一对一查询 标签: mybatis mybatis学习笔记10-一对一查询 resultType实现 resultMap实现 resultType和resultMap实 ...
- mybatis学习笔记之基础框架(2)
mybatis学习笔记之基础框架(2) mybatis是一个持久层的框架,是apache下的顶级项目. mybatis让程序将主要精力放在sql上,通过mybatis提供的映射方式,自由灵活生成满足s ...
- mybatis学习笔记(7)-输出映射
mybatis学习笔记(7)-输出映射 标签: mybatis mybatis学习笔记7-输出映射 resultType 输出简单类型 输出pojo对象和pojo列表 resultMap result ...
- flex学习小结
接触到flex一个多月了,今天做一个学习小结.如果有知识错误或者意见不同的地方.欢迎交流指教. 画外音:先说一下,我是怎么接触到flex布局的.对于正在学习的童鞋们,我建议大家没事可以逛逛网站,看看人 ...
- Python 学习小结
python 学习小结 python 简明教程 1.python 文件 #!/etc/bin/python #coding=utf-8 2.main()函数 if __name__ == '__mai ...
- react学习小结(生命周期- 实例化时期 - 存在期- 销毁时期)
react学习小结 本文是我学习react的阶段性小结,如果看官你是react资深玩家,那么还请就此打住移步他处,如果你想给一些建议和指导,那么还请轻拍~ 目前团队内对react的使用非常普遍,之 ...
随机推荐
- Unicode 和 ANSI
Project Properties -> General-> Character set,里面显示了是不是unicode. Unicode处理String的方式不一样,一定要注意!! ...
- python--optparse
import optparse op = optparse.OptionParser() op.add_option("--s", dest="server") ...
- cordova学习:事件Events
deviceready: 当cordova完全加载,可以调用cordova API接口 支持平台:Amazon.Fire OS.Android.BlackBerry 10.iOS.Tizen.Wind ...
- UVA 1604:Cubic Eight-Puzzle(模拟,BFS Grade C)
题意: 3*3方格,有一个是空的.其他的每个格子里有一个立方体.立方体最初上下白色,前后红色,左右蓝色.移动的方式为滚.给出初态空的位置,终态上面颜色情况,问最少多少步能到达.如果超过30步不能到达, ...
- django返回响应对象
Django的视图必须要返回一个HttpResponse对象(或者其子类对象),不能像flask一样直接返回字符串. Django: return HttpResponse("Hello&q ...
- python的递归算法学习(2):具体实现:斐波那契和其中的陷阱
1.斐波那契 什么是斐波那契,斐波那契额就是一个序列的整数的排序,其定义如下: Fn = Fn-1 + Fn-2 with F0 = 0 and F1 = 1 也就是,0,1,1,2,3,5,8,13 ...
- poj2774(最长公共子串)
poj2774 题意 求两个字符串的最长公共子串 分析 论文 将两个字符串合并,中间插入分隔符,在找最大的 height 值的时候保证,两个字符串后缀的起始点分别来自原来的两个字符串. code #i ...
- Java线程同步:synchronized锁住的是代码还是对象
所以我们在用synchronized关键字的时候,能缩小代码段的范围就尽量缩小,能在代码段上加同步就不要再整个方法上加同步.这叫减小锁的粒度,使代码更大程度的并发.原因是基于以上的思想,锁的代码段太长 ...
- POJ 3735 Training little cats(矩阵乘法)
[题目链接] http://poj.org/problem?id=3735 [题目大意] 有一排小猫,给出一系列操作,包括给一只猫一颗花生, 让某只猫吃完所有的花生以及交换两只猫的花生, 求完成m次操 ...
- 检索COM 类工厂中CLSID 为{00024500-0000-0000-C000-000000000046}组件时失败
检索 COM 类工厂中 CLSID 为{00024500-0000-0000-C000-000000000046} 的组件时失败,原因是出现以下错误: 80070005 当在ASP.NET应用程序中引 ...