mybatis的xml配置和注解配置

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis的xml配置和注解配置相关的知识,希望对你有一定的参考价值。

xml配置

spring-application.xml

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context.xsd"

    <import resource="spring-annotation-componentScan.xml" />
    <import resource="spring-data.xml" />
    <import resource="spring-mybatis.xml" />
    <import resource="spring-transaction.xml" />
</beans>

spring-annotation-componentScan.xml

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.demo"/>

</beans>

spring-data.xml

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder ignore-unresolvable="true"  location="jdbc.properties" />
    <!-- 配置数据源 使用的是Druid数据源 -->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="${jdbc.url}" />
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="${druid.initialSize}" />
        <!-- 连接池最大使用连接数量 -->
        <property name="maxActive" value="${druid.maxActive}" />
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="${druid.minIdle}" />
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="${druid.maxWait}" />
        <property name="poolPreparedStatements" value="${druid.poolPreparedStatements}" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="${druid.maxPoolPreparedStatementPerConnectionSize}" />
        <!-- 用来检测有效sql -->
        <property name="validationQuery" value="${druid.validationQuery}" />
        <property name="testOnBorrow" value="${druid.testOnBorrow}" />
        <property name="testOnReturn" value="${druid.testOnReturn}" />
        <property name="testWhileIdle" value="${druid.testWhileIdle}" />
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="${druid.minEvictableIdleTimeMillis}" />
        <!-- 打开removeAbandoned功能 -->
        <property name="removeAbandoned" value="${druid.removeAbandoned}" />
        <!-- 1800秒,也就是30分钟 -->
        <property name="removeAbandonedTimeout" value="${druid.removeAbandonedTimeout}" />
        <!-- 关闭abanded连接时输出错误日志 -->
        <property name="logAbandoned" value="${druid.logAbandoned}" />
        <!-- 监控数据库
        <property name="filters" value="${druid.filters}" />
        -->
    </bean>
</beans>

spring-mybatis.xml

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
      <!-- 创建SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据源:必须属性 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 指定mybatis的 XML映射器文件地址 -->
        <property name="mapperLocations" value="classpath*:mybatis/*.xml" />
        <!-- 可在mybatis配置文件中设置 -->
        <property name="configuration">
            <bean class="org.apache.ibatis.session.Configuration">
                <property name="mapUnderscoreToCamelCase" value="true"/>
            </bean>
        </property>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.demo.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>
</beans>

spring-transaction.xml

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">
         <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 注解方式配置事物 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

测试

        ClassPathXmlApplicationContext context11 = new ClassPathXmlApplicationContext("classpath:spring-application.xml");
        UserMapper userMapper = context11.getBean(UserMapper.class);
        User user = userMapper.getById(6498);
        System.out.println("id = [" + user.getId() + "]");
        System.out.println("name = [" + user.getName() + "]");

注解配置

ApplicationConfig启动入口

@Configuration
@Import({DaoConfig.class, ComponentScanConfig.class})
public class ApplicationConfig {
}

ComponentScanConfig扫描注解bean

@Configuration
@ComponentScan(basePackages = {"com.demo.enity","com.demo.dao","com.demo.mapper","com.demo.service"})
public class ComponentScanConfig {
}

DaoConfig持久层配置

@Configuration
@Import({MybatisConfig.class, TransactionConfig.class})
public class DaoConfig {
}

MybatisConfig ORM配置

@Configuration
@Import(DruidPoolConfig.class)
public class MybatisConfig {

    @Autowired
    private DataSource dataSource;

    @Bean("sqlSessionFactory")
    public SqlSessionFactoryBean sqlSessionFactory() throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setFailFast(true);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/*.xml"));
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        sqlSessionFactoryBean.setConfiguration(configuration);
        return sqlSessionFactoryBean;
    }

        @Bean
    public static MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.demo.mapper");
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        return mapperScannerConfigurer;
    }
}

注意:
MapperScannerConfigurer 实现了BeanDefinitionRegistryPostProcessor接口,因此该bean必须static修饰。否则启动加载的顺序会出现错误,如:DataSource 为null;

PathMatchingResourcePatternResolver此类可以通配符加载资源;

DruidPoolConfig连接池配置

@Configuration
@Import(DruidJdbcConfig.class)
public class DruidPoolConfig {

    private final static Logger LOGGER = LoggerFactory.getLogger(DruidPoolConfig.class);

    @Autowired
    private DruidJdbcConfig druidJdbcConfig;

    @Bean("dataSource")
    public DataSource dataSource(){
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(druidJdbcConfig.getUrl());
        datasource.setUsername(druidJdbcConfig.getUsername());
        datasource.setPassword(druidJdbcConfig.getPassword());
        datasource.setDriverClassName(druidJdbcConfig.getDriverClassName());
        datasource.setInitialSize(druidJdbcConfig.getInitialSize());
        datasource.setMinIdle(druidJdbcConfig.getMinIdle());
        datasource.setMaxActive(druidJdbcConfig.getMaxActive());
        datasource.setMaxWait(druidJdbcConfig.getMaxWait());
        datasource.setTimeBetweenEvictionRunsMillis(druidJdbcConfig.getTimeBetweenEvictionRunsMillis());
        datasource.setMinEvictableIdleTimeMillis(druidJdbcConfig.getMinEvictableIdleTimeMillis());
        datasource.setValidationQuery(druidJdbcConfig.getValidationQuery());
        datasource.setTestWhileIdle(druidJdbcConfig.isTestWhileIdle());
        datasource.setTestOnBorrow(druidJdbcConfig.isTestOnBorrow());
        datasource.setTestOnReturn(druidJdbcConfig.isTestOnReturn());
        datasource.setRemoveAbandoned(druidJdbcConfig.isRemoveAbandoned());
        datasource.setRemoveAbandonedTimeout(druidJdbcConfig.getRemoveAbandonedTimeout());
        datasource.setLogAbandoned(druidJdbcConfig.isLogAbandoned());
        try {
            datasource.setFilters(druidJdbcConfig.getFilters());
        } catch (SQLException e) {
            LOGGER.error("datasource.setFilters occur error.", e);
        }
        return datasource;
    }
}

DruidJdbcConfig数据库连接配置

@Configuration
@PropertySource("classpath:jdbc.properties")
public class DruidJdbcConfig {
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    @Value("${jdbc.driverClassName}")
    private String driverClassName;
    @Value("${druid.initialSize}")
    private int initialSize;
    @Value("${druid.minIdle}")
    private int minIdle;
    @Value("${druid.maxActive}")
    private int maxActive;
    @Value("${druid.maxWait}")
    private int maxWait;
    @Value("${druid.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;
    @Value("${druid.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;
    @Value("${druid.validationQuery}")
    private String validationQuery;
    @Value("${druid.testWhileIdle}")
    private boolean testWhileIdle;
    @Value("${druid.testOnBorrow}")
    private boolean testOnBorrow;
    @Value("${druid.testOnReturn}")
    private boolean testOnReturn;
    @Value("${druid.removeAbandoned}")
    private boolean removeAbandoned;
    @Value("${druid.removeAbandonedTimeout}")
    private int removeAbandonedTimeout;
    @Value("${druid.logAbandoned}")
    private boolean logAbandoned;
    @Value("${druid.filters}")
    private String filters;
    @Value("${druid.logSlowSql}")
    private boolean logSlowSql;
    @Value("${druid.loginUsername}")
    private String loginUsername;
    @Value("${druid.loginPassword}")
    private String loginPassword;

TransactionConfig事物配置

@Configuration
@Import(DruidPoolConfig.class)
@EnableTransactionManagement
public class TransactionConfig {

    @Autowired
    private DataSource dataSource;

    @Bean("transactionManager")
    public DataSourceTransactionManager transactionManager(){
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }
}

注意:@EnableTransactionManagement注解管理事物,相当于 <tx:annotation-driven transaction-manager="transactionManager" />

测试

        AnnotationConfigApplicationContext context12 = new AnnotationConfigApplicationContext();
        context12.register(ApplicationConfig.class);
        context12.refresh();
        UserService userService = context12.getBean(UserService.class);
        User user = userService.save(6498);
        System.out.println("id = [" + user.getId() + "]");
        System.out.println("name = [" + user.getName() + "]");

以上是关于mybatis的xml配置和注解配置的主要内容,如果未能解决你的问题,请参考以下文章

springboot通过xml集成mybatis实现mysql数据库操作探坑记

MyBatis 使用简单的 XML或注解用于配置和原始映射

mybatis执行CRUD操作的两种方式配置和注解

Spring+MyBatis纯注解零XML整合

Mybatis在接口上使用注解配置SQL语句以及接口与xml一起使用

mybatis中xml映射和方法注解两种配置sql语句的方式是不是可以同时存在