快上网专注成都网站设计 成都网站制作 成都网站建设
成都网站建设公司服务热线:028-86922220

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

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://6mz.cn/article/iphoeg.html

其他资讯