springbootMybatisalready

SpringBoot整合Mybatis+druid快速开发

2021-12-13  本文已影响0人  小胖学编程
结构信息.png

1. 配置类

配置类:

@Slf4j
@Configuration
public class DBConfig {

    @Value("${mysql.mapperLocations}")
    private String mapperLocations;

    @Value("${mysql.configLocation}")
    private String configLocation;

    /**
     * 数据源
     */
    @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);
            //设置mybatis-config.xml配置文件位置
            sessionFactoryBean.setConfigLocation(new DefaultResourceLoader().getResource(configLocation));
            //设置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创建失败", e);
            return null;
        }
    }

    /**
     * 操作事务的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注入的风险
     */
    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注入的风险!!!-->
    <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>
    <!--结果集是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>

详见:mybatis如何预防不经意间的SQL注入

上一篇 下一篇

猜你喜欢

热点阅读