目录
- MyBatis
- 目标
- MyBatis演示
- Configuration.xml
- 映射文件
- 初始化配置文件
- Dao
- Spring与MyBatis集成
- pom
- Spring配置文件
- MyBatis配置文件
- 其它
- SpringBoot与MyBatis集成
- POM
- 数据准备
- schema.sql
- test-data.sql
- 数据源配置
- Dao
- UserMapper
- UserMapper.xml
- 测试
- MyBatis配置文件详解
- Mybatis映射文件详解
- 动态SQL元素
- if
- choose、when、otherwise
- where、trim、set
- where
- trim
- set
- foreach
- bind与模糊查询
- MyBatis中使用OGNL表达式
MyBatis
标签(空格分隔): 一文总结
目标
MyBatis动态代码生成
映射文件
与Spring集成
与SpringBoot集成
MyBatis演示
Configuration.xml
-
映射文件
初始化配置文件
package com.imooc.db;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/**
* 访问数据库类
*/
public class DBAccess {
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;
}
}
Dao
package org.zln.dao;
import org.springframework.stereotype.Repository;
import org.zln.domain.Message;
import java.util.List;
/**
* Created by sherry on 000006/7/6 19:16.
*/
@Repository
public class MessageDao extends BaseDao {
public List queryMessageList(String command,String description){
return sqlSessionTemplate.selectList("org.zln.domain.Message.queryMessageList");
}
}
Spring与MyBatis集成
pom
4.0.0
org.zln.bms
bms
1.0-SNAPSHOT
war
4.3.7.RELEASE
1.7.25
2.8.1
2.8.1
3.5
1.4.194
3.4.2
1.3.1
1.2
4.0.0-b01
2.8.7
4.2.1
4.12
2.2.2
2.10.3
3.16
3.1-FINAL
2.2
5.1.42
1.16.16
1.0.29
1.10.19
1.8.10
3.0.5.RELEASE
joda-time
joda-time
2.9.7
org.mybatis.generator
mybatis-generator-core
1.3.5
org.thymeleaf
thymeleaf
${thymeleaf.version}
org.slf4j
slf4j-api
org.thymeleaf
thymeleaf-spring4
${thymeleaf.version}
org.slf4j
slf4j-api
org.projectlombok
lombok
${lombok.version}
mysql
mysql-connector-java
${mysql-connector-java.version}
com.alibaba
druid
${druid.version}
org.springframework
spring-webmvc
${spring.version}
org.springframework
spring-tx
${spring.version}
org.springframework
spring-context-support
${spring.version}
org.springframework
spring-jdbc
${spring.version}
org.springframework
spring-aop
${spring.version}
org.aspectj
aspectjrt
${aspect.version}
org.aspectj
aspectjweaver
${aspect.version}
org.springframework
spring-test
${spring.version}
test
org.apache.poi
poi
${poi.version}
org.apache.poi
poi-ooxml
${poi.version}
poi
poi-contrib
${poi-contrib.version}
commons-io
commons-io
${commons-io.version}
org.apache.logging.log4j
log4j-slf4j-impl
${log4j-slf4j-impl.version}
org.apache.logging.log4j
log4j-core
${log4j-core.version}
org.apache.commons
commons-lang3
${commons-lang3.version}
com.h2database
h2
${h2.version}
org.mybatis
mybatis
${mybatis.version}
org.mybatis
mybatis-spring
${mybatis-spring.version}
com.github.pagehelper
pagehelper
${pagehelper.version}
jstl
jstl
${jstl.version}
javax.servlet
javax.servlet-api
${servlet-api.version}
provided
com.fasterxml.jackson.core
jackson-databind
${jackson-databind.version}
junit
junit
${junit.version}
test
net.sf.ehcache
ehcache
${ehcache.version}
${project.artifactId}
src/main/resources
**/*.properties
**/*.xml
**/*.sql
**/*.html
false
org.apache.maven.plugins
maven-resources-plugin
2.7
UTF-8
org.apache.maven.plugins
maven-compiler-plugin
3.2
1.8
UTF-8
org.apache.tomcat.maven
tomcat7-maven-plugin
2.2
8080
/bms
Spring配置文件
MyBatis配置文件
其它
Mapper接口的生成与XML都可以使用代码生成工具生成
如果有需要修改,再在此基础上进行修改
如果需要执行批量操作,建议使用JDBC,用MyBatis有点麻烦
SpringBoot与MyBatis集成
POM
4.0.0
org.zln.spb
spb02-web
1.0-SNAPSHOT
jar
spb02-web
JavaWeb开发模板
org.springframework.boot
spring-boot-starter-parent
1.5.4.RELEASE
UTF-8
UTF-8
1.8
3.0.2.RELEASE
2.0.4
1.16.16
3.5
1.4.194
1.3.0
4.2.1
com.github.pagehelper
pagehelper
${pagehelper.version}
com.h2database
h2
${h2.version}
org.apache.commons
commons-lang3
${commons-lang3.version}
org.projectlombok
lombok
${lombok.version}
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-websocket
org.springframework.boot
spring-boot-starter-jdbc
org.mybatis.spring.boot
mybatis-spring-boot-starter
${mybatis.starter.version}
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
数据准备
schema.sql
-- 测试用表
create table User (
id identity
,username varchar(100)
,password varchar(100)
);
test-data.sql
insert into User (username,password) values ('姓名1','pd1');
insert into User (username,password) values ('姓名2','pd2');
insert into User (username,password) values ('姓名3','pd3');
insert into User (username,password) values ('姓名4','pd4');
insert into User (username,password) values ('姓名5','pd5');
insert into User (username,password) values ('姓名6','pd6');
insert into User (username,password) values ('姓名7','pd7');
insert into User (username,password) values ('姓名8','pd8');
insert into User (username,password) values ('姓名9','pd9');
insert into User (username,password) values ('姓名10','pd10');
insert into User (username,password) values ('姓名11','pd11');
数据源配置
package org.zln.spb.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import javax.sql.DataSource;
/**
* 数据库相关配置
* Created by nbcoolkid on 2017-06-26.
*/
@Configuration
public class DbConfig {
/**
* H2嵌入式数据库,用于开发
* @return
*/
@Bean(destroyMethod = "shutdown")
@Primary
@Profile("dev")
public DataSource dataSourceH2(){
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("classpath:sql/schema.sql")
.addScript("classpath:sql/test-data.sql")
.setScriptEncoding("UTF-8")
.build();
}
}
Dao
UserMapper
package org.zln.spb.dao.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.zln.spb.pojo.vo.User;
/**
* Created by nbcoolkid on 2017-06-26.
*/
@Mapper
public interface UserMapper {
User selectByPrimaryKey(int id);
}
UserMapper.xml
测试
package org.zln.spb.dao.mapper;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.*;
/**
* Created by nbcoolkid on 2017-06-26.
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void selectByPrimaryKey() throws Exception {
System.out.println("UserMapper:"+userMapper);
System.out.println(userMapper.selectByPrimaryKey(1));
}
}
MyBatis配置文件详解
Mybatis映射文件详解
动态SQL元素
if
and role_name like concat('%',#{roleName},'%')
choose、when、otherwise
and role_no=#{roleNo}
and role_name like concat('%',#{roleName},'%')
and note is not null
where、trim、set
where
and role_name like concat('%',#{roleName},'%')
当条件满足的时候,才会拼接where
关键字
而且前缀and
会自动去掉
trim
and role_name like concat('%',#{roleName},'%')
prefix
表示语句的前缀
prefixOverrides
表示需要去掉的第一个字符串,如果有多种,可以这样子prefixOverrides="and|or"
set
用于执行更新语句
update t_tole
tole_name=#{roleName},
where role_no=#{roleNo}
使用trim改写
update t_tole
tole_name=#{roleName},
where role_no=#{roleNo}
suffixOverrides
表示需要去掉的最后一个字符串
foreach
bind与模糊查询
bind
一般用于模糊查询的字符串连接
MySQL
中使用concat
Oracle
中使用||
如果传递过来的参数有多个,
则编写多个bind
标签即可
MyBatis中使用OGNL表达式
在MyBatis中,通过使用OGNL表达式,从传递的参数中获取数据,组装SQL
String与基本数据类型 _parameter
自定义类型(对象) 属性名
集合
数组 array
List list
Map _parameter
获取集合中的一条数据
数组 array[索引] 基本数据类型数组
array[索引].属性名 对象数据类型数组
List list[索引]
list[索引].属性名
Map _parameter.key
_parameter.key.属性名
利用foreach标签从集合中取出数据(遍历拼接SQL)
如果collection中的数组或List,i表示下标,如果collection是Map,i表示key。item(或item.属性名)表示迭代出来的值
separator 表示 迭代出来的元素之间的分隔符
举例
delete from MESSAGE where ID in(
#{item}
)