溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

mybatis的xml配置和注解配置

發(fā)布時間:2020-07-09 14:06:27 來源:網(wǎng)絡 閱讀:4666 作者:乾坤刀 欄目:軟件技術

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" />
    <!-- 配置數(shù)據(jù)源 使用的是Druid數(shù)據(jù)源 -->
    <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}" />
        <!-- 連接池最大使用連接數(shù)量 -->
        <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}" />
        <!-- 監(jiān)控數(shù)據(jù)庫
        <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">
      <!-- 創(chuàng)建SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 數(shù)據(jù)源:必須屬性 -->
        <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 實現(xiàn)了BeanDefinitionRegistryPostProcessor接口,因此該bean必須static修飾。否則啟動加載的順序會出現(xiàn)錯誤,如: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數(shù)據(jù)庫連接配置

@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() + "]");
向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI