MyBatis 与 Spring 的整合(第一个例子)【学习笔记 四 】

本文介绍了如何将MyBatis与Spring进行整合,包括在pom.xml中添加依赖,配置SqlSessionFactory,使用SqlSessionTemplate,定义DAO接口bean,配置事务管理器,并通过一个完整的例子展示了从建表到测试的整个过程。
摘要由CSDN通过智能技术生成

MyBatis 与 Spring 的整合

      1.在pom.xml文件中添加下列内容,导入相关的jar包。

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.2</version>
    </dependency>

      2.Spring 管理SqlSessionFactory,在Spring IoC容器配置文件Context.xml中添加下列内容:


	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>		
		<property name="mapperLocations" value="classpath*:com/kfcl/hps/information/dao/mapper/*.xml"/>
		<property name="typeAliasesPackage" value="com.kfcl.hps.information.model"/>
		<property name="configuration">
			<bean class="org.apache.ibatis.session.Configuration">
				<property name="mapUnderscoreToCamelCase" value="true"></property>
			</bean>
		</property>	
	</bean>

 其中,dataSource为Spring管理的的连接池对象,mapperLocations填写MyBatis映射文件的路径,这里与Spring整合使用自动扫描机制,会自动搜索该路径所有符合条件的映射文件并解析,typeAliasesPackage填写Model类的路径,主要是扫描类型别名,Model类使用注解方式为Model全限定类名设置别名。

      3.Spring管理SqlSessionTemplate,在Spring IoC容器配置文件Context.xml中添加下列内容:

	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg index="0" ref="sqlSessionFactory"/>
	</bean>

      4.为每个dao接口定义bean

我们可以在Context.xml配置文件里为每个dao接口定义bean,但mybatis还提供了一种更简便的自动扫描注解的机制,即<mybatis:scan/>。 配置<mybatis:scan/>,需要在Context.xml配置文件里添加:

    <mybatis:scan base-package="com.example.dao"/>

      5.配置事务管理器。

在Context.xml文件中添加下列代码配置事务管理器:

	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>

添加下列代码,启用事务注解类,即可使用@Transactional注解启用事务。

	<!-- 启用事务注释 -->
	<tx:annotation-driven transaction-manager="transactionManager"/>

下面是关于事务管理的一个例子: 

如果不加注解@Transactional的话,事务不会滚,即事务a生效,事务b不执行

到这里已经完成了MyBatis和Spring 的整合

下面是一个整合后的例子:

    1.建表:

--创建学生表
create table Student(
    stuNo number,
    stuName varchar2(16),
    phone varchar2(11)
);
--序列
create sequence student_seq;

    2.创建对应的Model类:StudentModel.class,包路径为:com.example.model

public class StudentModel {
	private int stuNo;
	private String stuName;
	private String phone;
	public int getStuNo() {
		return stuNo;
	}
	public void setStuNo(int stuNo) {
		this.stuNo = stuNo;
	}
	public String getStuName() {
		return stuName;
	}
	public void setStuName(String stuName) {
		this.stuName = stuName;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
}

    3.创建dao层接口,包路径为:com.example.dao

public interface IStudentDao {
	//增加
	public void create(StudentModel student) throws Exception; 
	//删除
	public void delete(StudentModel student) throws Exception; 
	//修改
	public void update(StudentModel student) throws Exception; 
	//查询-全部
	public List<StudentModel> selectListByAll() throws Exception; 
}

    4.创建映射文件IStudentDaoMapper.xml,包路径:com.example.dao.mapper

<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.dao.IStudentDao">
	<insert id="create"	parameterType="com.example.model.StudentModel">
		insert into Student(StuNo,StuName,Phone)
		values(Student_SEQ.nextval,#{stuName},#{phone})
	</insert>
	<update id="update" parameterType="com.example.model.StudentModel">
		update Student set StuName=#{stuName}, Phone=#{phone}
		where StuNo=#{stuNo}
	</update>
	<delete id="delete" parameterType="com.example.model.StudentModel">
		delete from HT_Neighbourhood where StuNo=#{stuNo}
	</delete>
	<!-- 查询-全部 -->
	<select id="selectListByAll" resultType="com.example.model.StudentModel">
		select * from Student
	</select>
</mapper>

    5.创建业务层接口IStudentService,包路径:com.example.service

public interface IStudentService {
	//新增
	public void add(StudentModel student) throws Exception;
	//修改
	public void modify(StudentModel student) throws Exception;
	//删除
	public void delete(StudentModel student) throws Exception;
	//查询-全部记录
	public List<StudentModel> listByAll() throws Exception;
}

    6.创建业务层实现类StudentServiceImpl,包路径:com.example.service.impl

@Service("studentService")
public class StudentServiceImpl implements IStudentService {

	private IStudentDao studentDao;
	
	@Autowired
	public void setStudentDao(IStudentDao studentDao) {
		this.studentDao = studentDao;
	}

	@Override
	public void add(StudentModel student) throws Exception {
		studentDao.create(student);
	}

	@Override
	public void modify(StudentModel student) throws Exception {
		studentDao.update(student);
	}

	@Override
	public void delete(StudentModel student) throws Exception {
		studentDao.delete(student);
	}

	@Override
	public List<StudentModel> listByAll() throws Exception {
		return studentDao.selectListByAll();
	}

}

    7.修改Ioc容器配置内容,修改所有的包路径:

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>		
		<property name="mapperLocations" value="classpath*:com/example/dao/mapper/*.xml"/>
		<property name="typeAliasesPackage" value="com.example.model"/>
		<property name="configuration">
			<bean class="org.apache.ibatis.session.Configuration">
				<property name="mapUnderscoreToCamelCase" value="true"></property>
			</bean>
		</property>	
	</bean>
	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg index="0" ref="sqlSessionFactory"/>
	</bean>
	<!-- 自动扫描 -->
	<mybatis:scan base-package="com.example.dao"/>
	
	<!-- 配置事务管理器 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!-- 启用事务注释 -->
	<tx:annotation-driven transaction-manager="transactionManager"/>

    8.创建测试类

public class StudentServiceTest {
	
	public static final void main(String[] args) throws Exception {
		ApplicationContext wac=new ClassPathXmlApplicationContext("context.xml") ;
		IStudentService studentService=wac.getBean("studentService",IStudentService.class);	
		List<StudentModel> list=studentService.listByAll();
		for(StudentModel student:list) {
			System.out.println(student.getStuNo()+" "+student.getStuName()+" "+student.getPhone());
		}
	}
}

    9.执行测试类:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值