Spring3.2整合MyBatis,我的Spring版本是3.2,MyBatis版本是3.0.4。
1.建工程,建包。
2.建立测试表:使用MySQL数据库
##数据库的脚本
drop table if exists stu;
create table stu(
sid int primary key auto_increment,
sname varchar(32),
sage int,
sbirth datetime
);
3.定义bean如下:
package bean;
public class Student {
private int id;
private String name;
private int age;
private String birth;
//省略 getter和setter方法
}
4.添加所需要的jar包,需要添加四类jar包:
a).第一类spring的jar包(spring核心的和一些日志组件)
b).第二类MyBatis的jar包
c).第三类Mybatis-spring.jar(可在MyBATIS的官网下载)
d).第四类驱动包+数据源包(此处使用Apache Commons的DBCP组件)
以上jar包均可在相应官网下载得到。附件中有整个程序的截图。
5.DAO层接口定义如下:
package dao;
import bean.Student;
//DAO层接口
public interface IStudentDao {
//添加
public void addStudent(Student stu);
//删除根据主键删除
public void deleteStudent(int sid);
//修改
public void updateStudent(Student stu);
//查询
public Student getStudentById(int id);
//分页start:表示从第几条记录开始查询 max:表示最大显示多少条记录
public List<Student> getSome(int start,int max);
}
6.service包中定义服务类,内部引用Dao层
package service;
import java.util.List;
import bean.Student;
import dao.IStudentDao;
//服务层。。。
public class StudentService {
//注入dao
private IStudentDao dao;
public void add(Student stu){
dao.addStudent(stu);
}
public void delete(int sid){
dao.deleteStudent(sid);
}
public void setDao(IStudentDao dao) {
this.dao = dao;
}
public void update(Student stu){
dao.updateStudent(stu);
}
public List<Student> getSome(int start,int max){
return dao.getSome(start, max);
}
public Student get(int id){
return dao.getStudentById(id);
}
}
7.下面是关键的Spring的配置文件,在src下创建名字为applicationContext.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--配置数据库的连接信息文件-->
<context:property-placeholder location="properties/db.properties"/>
<!-- 配置数据源 -->
<bean id="ds" class="org.apache.commons.dbcp.BasicDataSource"
p:driverClassName="${driver}" p:url="${url}" p:username="${user}"
p:password="${pwd}" />
<!-- SqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
<property name="dataSource" ref="ds"></property>
<!-- 设置mybatis配置文件的位置 由于数据源,SQL的映射文件等属性均在
applicationContext文件中设置了,所以mybatis的config文件只需用来做一些
其他设置。因此该文件可以省略不写 此处作为示例用来注册别名-->
<property name="configLocation" value="classpath:properties/mybatis_config.xml"></property>
<!-- 注册映射文件的位置 -->
<property name="mapperLocations" value="bean/Student.xml"></property>
</bean>
<!-- 配置SqlSesionTemplate -->
<bean id="sst" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSessionFactory"></constructor-arg>
</bean>
<!-- dao 其中引用SqlSession SqlSessionTemplate实现了SqlSession-->
<bean id="dao" class="dao.StudentDaoImpl">
<!-- dao中时SqlSession 此处是具体实现类SqlSessionTemplate -->
<property name="session" ref="sst"></property>
</bean>
<!-- StudentService -->
<bean id="service" class="service.StudentService" p:dao-ref="dao" />
</beans>
7.1 properties/db.properteis
##这里是数据连接信息 (必选的)
driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///xx
user=root
pwd=xx
7.2 MyBatis的配置文件 properties/mybatis_config.xml
<?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>
<typeAliases>
<typeAlias type="bean.Student" alias="stu"/>
</typeAliases>
</configuration>
7.3 MyBATIS的SQL映射文件 bean/student.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xxx"><!-- 命名空间:主要是避免命名的冲突 -->
<!-- 添加学生
获得主键数据新添加的主键:
1.通过useGenerateKeys=true 来设置
keyColumn:表示表中的字段
keyProperty:表示类中的属性
2.通过<insert>的<selectKey>来获得主键
-->
<insert id="addStudent" parameterType="stu"
useGeneratedKeys="true" keyColumn="sid" keyProperty="id">
insert into stu(sname,sage,sbirth)
values(#{name},#{age},#{birth})
<!-- 返回主键 -->
<!--
<selectKey keyProperty="id" resultType="int">
select @@last_insert_id as sid
</selectKey>
-->
</insert>
<!-- 根据ID查询 -->
<select id="getStuById" parameterType="int"
resultType="stu">
select sid as id,sname as name,
sage as age,sbirth as birth
from stu where sid=#{id}
</select>
<!-- 分页 -->
<select id="getSome" parameterType="map" resultType="stu">
select sid as id,sname as name,sage as age
,sbirth as birth from stu limit #{start},#{max}
</select>
</mapper>
8.最后,测试文件
package test;
import java.util.Date;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.StudentService;
import bean.Student;
public class Test {
public static void main(String[] args) {
Student s = new Student();
s.setName("et");
s.setAge(123);
s.setBirth(new Date());
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
StudentService service = ctx.getBean("service",StudentService.class);
int i =service.add(s);
/*Student s =(Student)service.getStudentById(1);
System.out.println(s.getName()+"\t"+s.getAge()+"\t"+s.getBirth());
*/
/* List<Student> ss = service.getSome(1,3);
for(Student s:ss){
System.out.println(s);
}*/
}
}
最后,附件中有整个小程序的截图。。