1. 配置類
配置類:
@Slf4j
@Configuration
public class DBConfig {
@Value("${mysql.mapperLocations}")
private String mapperLocations;
@Value("${mysql.configLocation}")
private String configLocation;
/**
* 數(shù)據(jù)源
*/
@Bean("mysqlDataSource")
@ConfigurationProperties(prefix = "mysql.datasource")
public DataSource dataSource() {
return new DruidDataSource();
}
@Bean(name = "mysqlSessionFactory")
public SqlSessionFactory sqlSessionFactorys(@Qualifier("mysqlDataSource") DataSource dataSource) throws Exception {
try {
SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
//獲取配置文件的dataSource對象
sessionFactoryBean.setDataSource(dataSource);
//設(shè)置mybatis-config.xml配置文件位置
sessionFactoryBean.setConfigLocation(new DefaultResourceLoader().getResource(configLocation));
//設(shè)置mapper.xml文件所在位置
Resource[] resources = new PathMatchingResourcePatternResolver().getResources(mapperLocations);
sessionFactoryBean.setMapperLocations(resources);
return sessionFactoryBean.getObject();
} catch (IOException e) {
log.error("mybatis解析 mapper*xml 失敗", e);
return null;
} catch (Exception e) {
log.error("mybatis sqlSessionFactoryBean創(chuàng)建失敗", e);
return null;
}
}
/**
* 操作事務(wù)的Template
* 此處傳入的dataSource是mysqlDataSource的bean悬而。
*/
@Bean(name = "mysqlSessionTemplate")
public SqlSessionTemplate sqlSessionTemplate(
@Qualifier("mysqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
@Bean(name = "mysqlTransactionManager")
public PlatformTransactionManager xxxTransactionManager(@Qualifier("mysqlDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
yml配置:
mysql:
mapperLocations: classpath:mybatis/mapper/*.xml
configLocation: classpath:/mybatis/mybatis-config.xml
datasource:
name: mysql_test
url: jdbc:mysql://localhost:3306/test
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
minIdle: 5
maxActive: 100
initialSize: 10
maxWait: 60000
啟動類:
@MapperScan("com.tellme.mapper") //指定掃描的mapper包的位置
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
2.插件類
mybatis/mybatis-config.xml
配置:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="cacheEnabled" value="true" />
<setting name="lazyLoadingEnabled" value="true" />
<setting name="multipleResultSetsEnabled" value="true" />
<setting name="useColumnLabel" value="true" />
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="useGeneratedKeys" value="true" />
<setting name="defaultExecutorType" value="SIMPLE" />
<setting name="defaultStatementTimeout" value="25000" />
</settings>
<typeAliases>
<typeAlias alias="Integer" type="java.lang.Integer" />
<typeAlias alias="Long" type="java.lang.Long" />
<typeAlias alias="HashMap" type="java.util.HashMap" />
<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
<typeAlias alias="ArrayList" type="java.util.ArrayList" />
<typeAlias alias="LinkedList" type="java.util.LinkedList" />
</typeAliases>
<plugins>
<plugin interceptor="com.tellme.Intercept.MybatisLogInterceptor"/>
</plugins>
</configuration>
插件:
@Slf4j
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
RowBounds.class, ResultHandler.class})})
public class MybatisLogInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}
3. Mapper類
接口類:
public interface UserMapper {
User queryUserByUserid(Long userid);
List<User> queryByName(String name);
void insertUser(User user);
void updateUser(User user);
List<User> queryUserOrder(UserOrder userOrder);
/**
* 不存在sql注入的風(fēng)險
*/
List<User> queryUserOrderNoRisk(UserOrder userOrder);
}
xml類:mybatis/mapper/UserMapper.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="com.tellme.mapper.UserMapper">
<sql id="column">
id
,`name`,age
</sql>
<!--order by 存在sql注入的風(fēng)險W吵亍a濉半沽!-->
<select id="queryUserOrder" parameterType="com.tellme.po.UserOrder"
resultType="com.tellme.po.User">
select *
from t_user
order by ${orderByColumn} ${orderType}
</select>
<!--order by 不存在sql注入-->
<select id="queryUserOrderNoRisk" parameterType="com.tellme.po.UserOrder"
resultType="com.tellme.po.User">
select * from t_user
<if test="orderByColumn!=null and orderByColumn=='age'.toString()">
order by ${orderByColumn}
</if>
<if test="orderType!=null and orderType=='asc'.toString()">
asc
</if>
<if test="orderType!=null and orderType=='desc'.toString()">
desc
</if>
</select>
<select id="queryUserByUserid" parameterType="java.lang.Long"
resultType="com.tellme.po.User">
select
<include refid="column"></include>
from t_user
where id = #{userid}
</select>
<!--結(jié)果集是List,但是resultType依舊是單個元素-->
<select id="queryByName" parameterType="java.lang.String"
resultType="com.tellme.po.User">
select
<include refid="column"></include>
from t_user
where name = #{name}
</select>
<insert id="insertUser" parameterType="com.tellme.po.User">
INSERT INTO t_user (name, age) value (#{name},#{age})
</insert>
<update id="updateUser" parameterType="com.tellme.po.User">
UPDATE t_user
SET name=#{name},
age=#{age}
WHERE id = #{id}
</update>
</mapper>