与spring3集成
1在src目录下新建config目录,将mybatis配置文件configuration.xml和
applicationContex.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"
xmlns:aop="http://www.springframework.org/schema/aop" 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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!--配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://127.0.0.1:3306/mybatis_demo?characterEncoding=utf8" />
<property name="username" value="root" />
<property name="password" value="yue4512138" />
</bean>
<!--SqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--dataSource属性指定要用到的连接池 -->
<property name="dataSource" ref="dataSource" />
<!--configLocation属性指定mybatis的核心配置文件 -->
<property name="configLocation" value="config/Configuration.xml" />
</bean>
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<!--sqlSessionFactory属性指定要用到的SqlSessionFactory实例 -->
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
<!--mapperInterface属性指定映射器接口,用于实现此接口并生成映射器对象 -->
<property name="mapperInterface" value="cn.yue.mybatis.inter.IUserOperation" />
</bean>
</beans>
测试类
/**
* spring集成mybatis测试类 *
*
* @version
*
* @Description:
*
* @author <a href="mailto:
[email protected]">Retacn</a>
*
* @since 2014-8-5
*
*/
public class MybatisSpringTest {
private static ApplicationContext ctx;
static {
ctx = new ClassPathXmlApplicationContext("config/applicationContext.xml");
}
public static void main(String[] args) {
IUserOperation mapper = (IUserOperation) ctx.getBean("userMapper");
// 测试id=1的用户查询,根据数据库中的情况,可以改成你自己的.
System.out.println("得到用户id=1的用户信息");
User user = mapper.selectUserByID(1);
System.out.println(user.getUserAddress());
// 得到文章列表测试
System.out.println("得到用户id为1的所有文章列表");
List<Article> articles = mapper.getUserArticles(1);
for (Article article : articles) {
System.out.println(article.getContent() + "--" + article.getTitle());
}
}
}
参考:http://blog.csdn.net/techbirds_bao/article/details/9233599/