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的使用非常普遍,之 ...
 
随机推荐
- web应用性能优化经验总结
			
常见性能优化要求 在我经历的性能优化案例中,常见的问题都是这样开始的: a) 前台访问很慢,请帮忙分析优化 b) 用户对性能很不满意,再不解决就要投诉 c) 数 ...
 - Centos 6.3 nginx代理配置
			
1. 查看nginx所在位置 $ nginx -t /etc/nginx/nginx.conf 2. 配置 user nobody; #启动服务的用户 worker_processes ; err ...
 - mysq 中 information_schema 库
			
information_schema这个库,这个在mysql安装时就有了,提供了访问数据库元数据的方式.那什么是元数据库呢?元数据是关于数据的数据,如数据库名或表名,列的数据类型,或访问权限等.有些时 ...
 - Delphi实现截屏存盘的方法
			
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms ...
 - PL/SQL&存储过程||存储函数&触发器
			
plsql 有点:交互式 非过程化 数据操纵能力强 自动导航语句简单 调试简单 想率高 声明类型的方式 1.基本类型 2.引用变量 3.记录型变量 基本格式 declare 声明 b ...
 - Longest Common Substring($LCS$)
			
Longest Common Substring(\(LCS\)) 什么是子序列? 子序列就是某一个序列的不连续的一部分. 如图, \(abcde\)就是图中序列的一个子序列. 公共子序列 公共子序列 ...
 - 中国石油大学(华东)OJ题目的HTML爬取
			
这几天刷华东OJ的题,写博客还要复制HTML的代码,感觉麻烦的一批,然后就去摸鱼写了个小爬虫.. 看一下运行效果吧- 输入详细的pid.cid或id即可爬取相应的html代码 一些注意要点: 关键的还 ...
 - bzoj 1879: [Sdoi2009]Bill的挑战
			
题目链接 bzoj 1879: [Sdoi2009]Bill的挑战 题解 n<=15,装压吧 对所有字符串进行装压 可以预处理一个数组can[i][j]表示所有的字符串中,有哪些可以在第i位匹配 ...
 - Ubuntu 16.04没有/etc/default/rcS文件的UTC设置选项的问题解决
			
继续上一篇文章介绍了CentOS的时钟设置:http://www.cnblogs.com/EasonJim/p/8111747.html,大致的知道了BIOS在Linux的时区设置. 而现在关心的问题 ...
 - PHP安全相关的配置
			
PHP作为一门强大的脚本语言被越来越多的web应用程序采用,不规范的PHP安全配置可能会带来敏感信息泄漏.SQL注射.远程包含等问题,规范的安全配置可保障最基本的安全环境.下面我们分析几个会引发安全问 ...