1、db.properties文件
#db.properties
dataSource=org.apache.commons.dbcp.BasicDataSource
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatisrelation
jdbc.username=root
jdbc.password=root
2、 mybatis-configuration.xml mybatis的配置文件
<?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>
<!--开启二级缓存 -->
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
<!-- 包的别名定义 -->
<typeAliases>
<package name="com.ys.po"/>
</typeAliases>
<!-- 注意:下面的以前有mybatis全局配置文件管理mapper,现在转移到spring容器管理 -->
<!-- <mappers>
<mapper class="com.ys.po.UserMapper"/>
</mappers> -->
</configuration>
3、在 spring 全局配置文件中 applicationContext.xml 中配置 SqlSessionFactory,以及数据源
<!-- 加载classpath下的db.properties文件,里面配了数据库连接的一些信息 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置数据源 -->
<bean id="dataSource" class="${dataSource}" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="5" />
</bean>
<!-- 配置sqlSessionFactory,SqlSessionFactoryBean是用来产生sqlSessionFactory的 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载mybatis的全局配置文件,放在classpath下的mybatis文件夹中 -->
<property name="configLocation" value="mybatis/mybatis-configuration.xml" />
<!-- 加载数据源,使用上面配置好的数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>
测试
public class UserMapperTest {
private ApplicationContext applicationContext;
@Before
public void setUp() throws Exception {
applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");//得到spring容器
}
@Test
public void testSelectUserById() throws Exception {
UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");
User user = userMapper.selectUserById(1);
System.out.println(user);
}
}