spring4零配置集成mybatis3

pom.xml

<!-- mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.3.0</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.3</version>
		</dependency>


AppConfig.java

@Bean
public DataSource dataSource(){
    connectionPoolDataSource.setDatabaseName(dataSourceSetting.getDatabaseName());                       connectionPoolDataSource.setDriverClassName(env.getProperty("db1.jdbc.driver"));
        connectionPoolDataSource.setUrl(env.getProperty("db1.jdbc.url"));
        connectionPoolDataSource.setUsername(env.getProperty("db1.jdbc.username"));
        connectionPoolDataSource.setPassword(env.getProperty("db1.jdbc.password"));     connectionPoolDataSource.setValidationQuery(env.getProperty("db1.jdbc.validationQuery"));
        connectionPoolDataSource.setMaxActive(16);
 connectionPoolDataSource.setDatabaseName(env.getProperty("db1.jdbc.databaseName"));       connectionPoolDataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        return connectionPoolDataSource;
    }


/**
     * mybatis整合-SqlSessionFactory
     * @return
     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(){
    	SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    	sqlSessionFactoryBean.setDataSource(this.dataSource());
    	sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("/config/sqlMapConfig.xml"));
    	return sqlSessionFactoryBean;
    }

   
    @Bean
    public SqlSessionTemplate sqlSessionTemplate() throws Exception{
    	SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(this.sqlSessionFactory().getObject());
    	return sqlSessionTemplate;
    }


sqlMapConfig.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>
     <mappers>
         <mapper resource="config/sqlMap/test.xml"/>
     </mappers>
 </configuration>


test.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="test">
    
    <select id="testSelect" resultType="java.util.HashMap">
    	select * from sys_user where 1=1 and user_name=#{name}
    </select>
    
</mapper>


DAO

public class TestDao {
	private static final Logger logger = Logger.getLogger(TestDao.class);	
	@Inject
	SqlSessionTemplate sqlSessionTemplate;
 public void testMybatis(String name)
    {
    	Map<String, Object> _params = new HashMap<String, Object>();
    	_params.put("name", name);
    	List<Object> list  = sqlSessionTemplate.selectList("test.testSelect", _params);
        logger.info("list=="+list);
    }
}

你可能感兴趣的:(spring,框架,mybatis)