Spring需要配置文件application.xml,配置如下
<!--声明了数据库连接池-->
<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?characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</bean>
<!--声明了SqlSessionFactory,用于管理数据库连接-->
<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="com.yihaomen.mybatis.inter.IUserOperation" />
</bean>
如上: 配置完毕之后,在代码也调用方式如下:
public class Test{
private static ApplicationContext ctx;
static
{
ctx = new ClassPathXmlApplicationContext("config/applicationContext.xml");
}
public static void main(String[] args)
{
IUserOperation mapper = (IUserOperation)ctx.getBean("userMapper");
System.out.println("得到用户id=1的用户信息");
User user = mapper.selectUserByID(1);
}
}
<!--声明了数据库连接池-->
<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?characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</bean>
<!--声明了SqlSessionFactory,用于管理数据库连接-->
<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="com.yihaomen.mybatis.inter.IUserOperation" />
</bean>
如上: 配置完毕之后,在代码也调用方式如下:
public class Test{
private static ApplicationContext ctx;
static
{
ctx = new ClassPathXmlApplicationContext("config/applicationContext.xml");
}
public static void main(String[] args)
{
IUserOperation mapper = (IUserOperation)ctx.getBean("userMapper");
System.out.println("得到用户id=1的用户信息");
User user = mapper.selectUserByID(1);
}
}