构建Mybatis项目(三)

将Spring3和mybatis3整合

添加依赖文件

commons-dbcp-1.4.jar

commons-logging-1.1.1.jar

commons-pool-1.5.5.jar

mybatis-spring-1.0.0.jar

org.springframework.asm-3.0.5.RELEASE.jar

org.springframework.beans-3.0.5.RELEASE.jar

org.springframework.context-3.0.5.RELEASE.jar

org.springframework.context.support-3.0.5.RELEASE.jar

org.springframework.core-3.0.5.RELEASE.jar

org.springframework.expression-3.0.5.RELEASE.jar

org.springframework.jdbc-3.0.5.RELEASE.jar

org.springframework.orm-3.0.5.RELEASE.jar

org.springframework.transaction-3.0.5.RELEASE.jar

 

创建spring配置文件spring.configuration.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 数据源 -->
<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!-- Sql会话工厂 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath*:org/test/mybatis/mapper/*.xml" />
</bean>
 
 	<!-- Sql会话对象 -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> 
<constructor-arg index="0" ref="sqlSessionFactory" /> 
</bean> 
</beans>
 

 

创建Spring测试类org.test.spring.root.Main

package org.test.spring.root;
import org.apache.ibatis.session.SqlSession;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.test.mybatis.mapper.PeopleMapper;
import org.test.mybatis.model.People;
public class Main {
/**
 * @param args
 */
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("spring.configuration.xml");
SqlSession session=(SqlSession)ac.getBean("sqlSession");
PeopleMapper pmp=(PeopleMapper)session.getMapper(PeopleMapper.class);
People pp=new People();
pp.setPassWord("dashagua");
pp.setRealName("dashagua");
pp.setUserName("dashagua");
pmp.insertPeople(pp);
}
}
 

 

发现由spring管理的会话对象不用提交就可以插入数据.执行后数据库多出一条数据

相关推荐