mybatis使用笔记
springboot整合mybatis
导包
<dependency> <groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- alibaba的druid数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
配置
spring: datasource:
name: mysql_test
type: com.alibaba.druid.pool.DruidDataSource
druid:
filters: stat
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=UTC
username: root
password: root
initial-size: 1
min-idle: 1
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: SELECT "x"
test-while-idle: true
test-on-borrow: false
test-on-return: false
pool-prepared-statements: false
max-pool-prepared-statement-per-connection-size: 20
mybatis:
mapper-locations: classpath*:/mybaits/mappings/*.xml
type-aliases-package: com.eximple.model
config-location: #classpath*:/mybaits/mybatis-config.xml
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
type-handlers-package: #扫描typeHandlers的包
check-config-location: true #检查配置文件是否存在
executor-type: SIMPLE #设置执行模式(SIMPLE, REUSE, BATCH),默认为SIMPLE
启动类中加
@MapperScan("com.example.mapper")
--------------------------------------------------------
pagehelper分页插件
导包
<dependency> <groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
配置
pagehelper: helperDialect: mysql
reasonable: false
supportMethodsArguments: true
params: count=countSql
或
@Beanpublic PageHelper pageHelper(){
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("helperDialect", "mysql");
properties.setProperty("offsetAsPageNum", "true");
properties.setProperty("rowBoundsWithCount", "true");
properties.setProperty("reasonable", "false");
pageHelper.setProperties(properties);
}
或
@Beanpublic PageHelper pageHelper(){
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("dialect", "mysql");
properties.setProperty("offsetAsPageNum", "true");
properties.setProperty("rowBoundsWithCount", "true");
properties.setProperty("reasonable", "true");
pageHelper.setProperties(properties);
}
或
/** * mybatis-plus分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor page = new PaginationInterceptor();
page.setDialectType("mysql");
return page;
}
注意:设置plugins时必须在sqlSessionFactoryBean.getObject()之前。SqlSessionFactory在生成的时候就会获取plugins,并设置到Configuration中,如果在之后设置则不会注入。
分页业务代码
public PageInfo<UserDomain> findUsers(int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize);
List<User> users = userDao.findUsers();
PageInfo result = new PageInfo(users);
return result;
}
--------------------------------------------------------
使用mybatis generator自动生成代码插件
pom中加入
<plugin> <groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin>
在resources/generator下创建文件generatorConfig.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>
<!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
<classPathEntry location="d:MySQLconnectormysql-connector-java-5.1.38-bin.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库链接URL,用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test" userId="root" password="root">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置-->
<javaModelGenerator targetPackage="com.examaple.model" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成映射文件的包名和位置-->
<sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources/mybatis/mappings">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成DAO的包名和位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.examaple.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
<table tableName="t_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
配置运行参数后运行
--------------------------------------------------------
mybatis插入数据,返回新增数据的id值
xml的insert方法加上useGeneratedKeys和keyProperty配置
<insert id="insertUser" useGeneratedKeys="true" keyProperty="userId" parameterType="com.examaple.entity.User"> insert into t_User(user_name,password)
values(#{userName},#{password})
</insert>
--------------------------------------------------------
mybatis用xml标签元素实现数据库表关联查询
一对一
使用<association>元素进行一对一关联映射非常简单,只需要参考如下两种示例配置即可
一对多
<resultMap>元素中,包含了一个<collection>子元素,MyBatis就是通过该元素来处理一对多关联关系的
<collection>子元素的属性大部分与<association>元素相同,但其还包含一个特殊属性--ofType
ofType属性与javaType属性对应,它用于指定实体对象中集合类属性所包含的元素类型。
多对多
多对多的关联关系查询,同样可以使用前面介绍的<collection >元素进行处理(其用法和一对多关联关系查询语句用法基本相同)
--------------------------------------------------------
mybatis中大于等于小于等于的写法
第一种写法:
原符号 < <= > >= & " "
替换符号 < <= > >= & ' "
例如:sql如下:
create_time >= #{startTime} and create_time <= #{endTime}
第二种写法:
小于等于
<![CDATA[ <= ]]>
大于等于
<![CDATA[ >= ]]>
例如:sql如下:
create_time <![CDATA[ >= ]]> #{startTime} and create_time <![CDATA[ <= ]]> #{endTime}
--------------------------------------------------------
mybatis中"#{}"和"${}"的区别
1、#相当于对数据 加上 双引号,$相当于直接显示数据。
2、#{}根据参数的类型进行处理,比如传入String类型,则会为参数加上双引号。#{}传参在进行SQL预编译时,会把参数部分用一个占位符 ? 代替,这样可以防止 SQL注入。
3、${}将参数取出不做任何处理,直接放入语句中,就是简单的字符串替换,并且该参数会参加SQL的预编译,需要手动过滤参数防止 SQL注入。
4、因此 mybatis 中优先使用#{};当需要动态传入表名或列名时,再考虑使用${},如排序字段
--------------------------------------------------------
MyBatis 调用存储过程
如在UserMapper.xml中调用procedure_getUserById存储过程
<!-- 根据id查询用户 -->
<select id="getUserById" parameterType="Integer" resultType="user" statementType="CALLABLE">
{call procedure_getUserById(#{id,mode=IN})}
</select>
--------------------------------------------------------
mybatis中传入参数的问题
A.mybatis中传入String类型参数
1.用_parameter接收
<select id="findUsers" parameterType="java.lang.String" resultType="com.example.entity.User"> SELECT id,name FROM t_user where 1=1
<if test="_parameter!= null and _parameter!= """>
AND name LIKE concat("%",#{_parameter},"%")
</if>
</select>
2.在dao入参加@Param("name")
<select id="findUsers" parameterType="java.lang.String" resultType="com.example.entity.User"> SELECT id,name FROM t_user where 1=1
<if test="_parameter!= null and _parameter!= """>
AND name LIKE concat("%",#{name},"%")
</if>
</select>
B.mybatis中传入Map List Array类型参数
<!--List:forech中的collection属性类型是List,collection的值必须是:list,item的值可以随意,Dao接口中参数名字随意 --><select id="getUsers" parameterType="List" resultType="User">
select name t_user
where id in
<foreach collection="list" item="id" index="index" open="(" close=")" separator=",">
#{id}
</foreach>
</select>
<!--Array:forech中的collection属性类型是array,collection的值必须是:array,item的值可以随意,Dao接口中参数名字随意 -->
<select id="getUsers" parameterType="List" resultType="User">
select name t_user
where id in
<foreach collection="array" item="id" index="index" open="(" close=")" separator=",">
#{id}
</foreach>
</select>
<!--Map:不单单forech中的collection属性是map.key,其它所有属性都是map.key,比如下面的ids -->
<select id="getUsers" parameterType="List" resultType="User">
select name t_user
where id in
<foreach collection="ids" item="id" index="index" open="(" close=")" separator=",">
#{id}
</foreach>
</select>
--------------------------------------------------------
Mybatis配置中开启全局延迟加载
<configuration> <settings>
<!--开启全局的懒加载-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--关闭立即加载,其实不用配置,默认为false-->
<setting name="aggressiveLazyLoading" value="false"/>
<!--开启Mybatis的sql执行相关信息打印-->
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
</configuration>
--------------------------------------------------------
mybatis配置文件中的常用配置
db.properties文件中的配置:
myBatis.cache.enabled=truemyBatis.lazy.loading.enabled=true
myBatis.aggressive.lazy.loading=false
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456
mybatis-config.xml配置:
<configuration>
<!-- 引用db.properties配置文件 -->
<properties resource="db.properties"/>
<settings>
<setting name="cacheEnabled" value="${myBatis.cache.enabled}"/>
<!--开启全局的懒加载-->
<setting name="lazyLoadingEnabled" value="${myBatis.lazy.loading.enabled}"/>
<!--关闭立即加载,其实不用配置,默认为false-->
<setting name="aggressiveLazyLoading" value="${myBatis.aggressive.lazy.loading}"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="autoMappingBehavior" value="PARTIAL"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25000"/>
<!--开启Mybatis的sql执行相关信息打印-->
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
<environments default="mysql">
<environment id="development1">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
<environment id="development2">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<typeAliases>
<package name="com.example.entity"/>
</typeAliases>
<mappers>
<package name="com.example.mapper"/>
</mappers>
<!-- 配置分页插件 -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
</configuration>
--------------------------------------------------------
Mybatis工作流程及其原理与解析 https://blog.csdn.net/u010890358/article/details/80665753
以上是 mybatis使用笔记 的全部内容, 来源链接: utcz.com/z/512400.html