资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

mybatis的xml配置和注解配置

xml配置

spring-application.xml

作为一家“创意+整合+营销”的成都网站建设机构,我们在业内良好的客户口碑。成都创新互联提供从前期的网站品牌分析策划、网站设计、网站设计制作、网站设计、创意表现、网页制作、系统开发以及后续网站营销运营等一系列服务,帮助企业打造创新的互联网品牌经营模式与有效的网络营销方法,创造更大的价值。



    
    
    

spring-annotation-componentScan.xml




    

spring-data.xml




    
    
    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    

spring-mybatis.xml



      
    
        
        
        
        
        
        
            
                
            
        
    

    
        
        
    

spring-transaction.xml



         
    
        
    
    
    

测试

        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注解管理事物,相当于

测试

        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配置和注解配置
标题URL:http://cdkjz.cn/article/iphoeg.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220