MyBatis(3.2.3) + Spring(3.2.3) 简单示例

1. 建立工程,导入相关的jar包。


2. 实体类Student:

package com.huey.mybatis.entity;

import java.util.Date;

/**
 * 学生实体
 * @author huey2672
 * @version 1.0
 * @created 2014-7-25
 */
public class Student {

	private Integer no;
	private String name;
	private Date birthday;
	private String email;
	
	public Integer getNo() {
		return no;
	}
	
	public void setNo(Integer no) {
		this.no = no;
	}
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public Date getBirthday() {
		return birthday;
	}
	
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	
	public String getEmail() {
		return email;
	}
	
	public void setEmail(String email) {
		this.email = email;
	}
	
	public Student() {
		super();
	}

	public Student(Integer no, String name, Date birthday, String email) {
		super();
		this.no = no;
		this.name = name;
		this.birthday = birthday;
		this.email = email;
	}

	@Override
	public String toString() {
		return "Student [no=" + no + ", name=" + name + ", birthday="
				+ birthday + ", email=" + email + "]";
	}
	
}

3. 映射器StudentMapper:

package com.huey.mybatis.mapper;

import java.util.List;

import org.apache.ibatis.session.RowBounds;

import com.huey.mybatis.entity.Student;

/**
 * 映射器StudentMapper
 * 定义了对学生实体的一些基本操作
 * @author huey2672
 * @version 1.0
 * @created 2014-7-25
 */
public interface StudentMapper {
	
	/**
	 * 添加学生记录
	 * @param student
	 * @return 数据库中受影响的行数
	 */
	public int addStudent(Student student);
	
	/**
	 * 删除学生记录
	 * @param studNo
	 * @return 数据库中受影响的行数
	 */
	public int deleteStudent(Integer studNo);
	
	/**
	 * 更新学生记录
	 * @param student
	 * @return 数据库中受影响的行数
	 */
	public int updateStudent(Student student);

	/**
	 * 根据学生学号查询学生记录
	 * @param studNo
	 * @return
	 */
	public Student getStudent(Integer studNo);
	
	/**
	 * 查询所有学生记录
	 * @return
	 */
	public List<Student> getAllStudents();
	
	/**
	 * 分页查询学生记录
	 * @param rowBounds
	 * @return
	 */
	public List<Student> getAllStudents(RowBounds rowBounds);
}

4. 配置映射文件StudentMapper.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">

<!--注意:此处的命名空间是StudentMapper的全限定类名-->
<mapper namespace="com.huey.mybatis.mapper.StudentMapper">
	
	<!-- ResultMaps被用来将 SQL SELECT语句的结果集映射到JavaBeans的属性中 -->
	<resultMap type="Student" id="studentMap">
		<!-- 映射主键 -->
		<id property="no" column="stud_no" />
		<!-- 映射普通字段 -->
		<result property="name" column="stud_name"/>
		<result property="birthday" column="birthday"/>
		<result property="email" column="email"/>
	</resultMap>

	<!-- 添加学生记录 -->
	<!-- id名称需要与StudentMapper中的方法签名一致 -->
	<!-- Student这一别名在mybatis-config.xml中配置 -->
	<insert id="addStudent" parameterType="Student">
		insert into students(stud_no, stud_name, birthday, email)
		values(#{no}, #{name}, #{birthday}, #{email})
	</insert>

	<!-- 删除学生记录 -->
	<delete id="deleteStudent" parameterType="int">
		delete from students where stud_no=#{studNo}
	</delete>

	<!-- 更新学生记录 -->
	<update id="updateStudent" parameterType="Student">
		update students
		set stud_name=#{name}, birthday=#{birthday}, email=#{email}
		where stud_no=#{no}
	</update>

	<!-- 根据学生学号查询学生记录 -->
	<select id="getStudent" parameterType="int" resultMap="studentMap" >
		select * from students where stud_no=#{studNo}
	</select>

	<!-- 查询所有学生记录 -->
	<select id="getAllStudents" resultMap="studentMap">
		select * from students
	</select>

</mapper>

5. 配置文件mybatis-config.xml(无需配置environments元素):

<?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="com.huey.mybatis.entity.Student" alias="Student" />
	</typeAliases>
 
	<!-- mapper对应的xml配置文件 -->
	<mappers>
		<mapper resource="com/huey/mybatis/mapper/StudentMapper.xml" />
	</mappers>
	
</configuration>

6. JDBC数据库连接属性配置:

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=root

7. Spring配置文件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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- 启动@AspectJ支持 -->
	<aop:aspectj-autoproxy proxy-target-class="true" />
	<!-- 自动扫描指定包及其子包下的所有Bean类 -->
	<context:component-scan base-package="com.huey.mybatis" />
	<!-- 将配置值具体化到一个属性文件中,并且使用属性文件的key名作为占位符 -->
	<context:property-placeholder location="classpath:jdbc.properties"/>

	<!-- 配置数据源  -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${jdbc.driverClassName}" />
		<property name="jdbcUrl" value="${jdbc.url}" />
		<property name="user" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="maxPoolSize" value="50" />
		<property name="minPoolSize" value="1" />
		<property name="initialPoolSize" value="1" />
		<property name="maxIdleTime" value="20" />
	</bean>

	<!-- 配置SqlSessionFactory交由Spring管理 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation" value="classpath:mybatis-config.xml" />
	</bean>
	
	<!-- 扫描并注册包中的映射器 Mapper接口 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.huey.mybatis.mapper" />
	</bean>
	
	<!-- 将事务交由Spring管理 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
	
	<!-- 启用spring @Transactional注解 -->
	<tx:annotation-driven />
	
</beans>

8. 业务逻辑层接口StudentServ:

package com.huey.mybatis.serv;

import java.util.List;

import com.huey.mybatis.entity.Student;

/**
 * 业务逻辑层接口StudentServ
 * @author huey2672
 * @version 1.0
 * @created 2014-7-25
 */
public interface StudentServ {

	/**
	 * 添加学生记录
	 * @param student
	 * @return 实际添加学生记录的数量
	 */
	public int addStudent(Student student);
	
	/**
	 * 删除学生记录
	 * @param studNo
	 * @return 实际删除学生记录的数量
	 */
	public int deleteStudent(Integer studNo);
	
	/**
	 * 更新学生记录
	 * @param student
	 * @return 实际更新学生记录的数量
	 */
	public int updateStudent(Student student);

	/**
	 * 根据学生学号查询学生记录
	 * @param studNo
	 * @return
	 */
	public Student getStudent(Integer studNo);
	
	/**
	 * 查询所有学生记录
	 * @return
	 */
	public List<Student> getAllStudents();
	
	/**
	 * 分页查询学生记录
	 * @param pageIndex	页码,第一页的页码为1
	 * @param pageSize	每页记录数
	 * @return
	 */
	public List<Student> pagingQueryStudents(int pageIndex, int pageSize);
	
}

9. 业务逻辑层实现StudentServImpl:

package com.huey.mybatis.serv.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.huey.mybatis.entity.Student;
import com.huey.mybatis.mapper.StudentMapper;
import com.huey.mybatis.serv.StudentServ;

/**
 * 业务逻辑层实现StudentServImpl
 * @author huey2672
 * @version 1.0
 * @created 2014-7-25
 */
@Service
@Transactional
public class StudentServImpl implements StudentServ {

	@Resource
	private StudentMapper studentMapper;
	
	public int addStudent(Student student) {
		int count = 0;
		try {
			count = studentMapper.addStudent(student);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return count;
	}
	
	public int deleteStudent(Integer studNo) {
		int count = 0;
		try {
			count = studentMapper.deleteStudent(studNo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return count;
	}

	public int updateStudent(Student student) {
		int count = 0;
		try {count = studentMapper.updateStudent(student);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return count;
	}	

	public Student getStudent(Integer studNo) {
		Student student = null;
		try {
			student = studentMapper.getStudent(studNo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return student;
	}

	public List<Student> getAllStudents() {
		List<Student> students = new ArrayList<Student>();
		try {
			students = studentMapper.getAllStudents();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return students;
	}
	
	public List<Student> pagingQueryStudents(int pageIndex, int pageSize) {
		List<Student> students = new ArrayList<Student>();
		try {
			// offset表示开始位置
			int offset = (pageIndex - 1) * pageSize;
			// limit表示要取的记录的数目
			int limit = pageSize;
			students = studentMapper.getAllStudents(new RowBounds(offset, limit));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return students;
	}
	
}

10. 单元测试基类:

package com.huey.mybatis.serv.impl;

import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;

/**
 * Spring集成JUnit4,作为单元测试基类,方便测试
 * @author huey2672
 * @version 1.0
 * @created 2014-7-25
 */
@ContextConfiguration(locations={"classpath*:applicationContext*.xml"})
public class SpringTest extends AbstractJUnit4SpringContextTests {

}

11. 单元测试类:

package com.huey.mybatis.serv.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.huey.mybatis.entity.Student;
import com.huey.mybatis.serv.StudentServ;

/**
 * 单元测试类StudentServTest
 * 用于测试StudentServImpl中的方法
 * @author huey2672
 * @version 1.0
 * @created 2014-7-25
 */
public class StudentServImplTest extends SpringTest {
	
	@Autowired
	StudentServ studentServ;

	@Test
	public void testAddStudent() throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date birthday = sdf.parse("2008-08-08");
		Student student = new Student(10008, "猪八戒", birthday, "pig8@gamil.com");

		int result = studentServ.addStudent(student);
		System.out.println("result = " + result);
	}
	
	/**
	 * 测试deleteStudent方法
	 * @throws Exception
	 */
	@Test
	public void testDeleteStudent() throws Exception {
		int studNo = 10001;
		int result = studentServ.deleteStudent(studNo);
		System.out.println("result = " + result);
	}
	
	/**
	 * 测试updateStudent方法
	 * @throws Exception
	 */
	@Test
	public void testUpdateStudent() throws Exception {
		int studNo = 10001;
		Student student = studentServ.getStudent(studNo);
		if (student != null) {
			student.setEmail("zhangsan@gmail.com");
			int result = studentServ.updateStudent(student);
			System.out.println("result = " + result);
		} else {
			System.out.println("查询不到的学生记录");
		}
		
	}
	
	/**
	 * 测试getStudent方法
	 * @throws Exception
	 */
	@Test
	public void testGetStudent() throws Exception {
		int studNo = 10001;
		Student student = studentServ.getStudent(studNo);
		System.out.println(student);
	}
	
	/**
	 * 测试getAllStudents方法
	 * @throws Exception
	 */
	@Test
	public void testGetAllStudents() throws Exception {
		List<Student> students = studentServ.getAllStudents();
		for (Student student : students) {
			System.out.println(student);
		}
 	}
	
	/**
	 * 测试pagingQueryStudents方法
	 * @throws Exception
	 */
	@Test
	public void testPagingQueryStudents() throws Exception {
		int pageIndex = 2;
		int pageSize = 4;
		List<Student> students = studentServ.pagingQueryStudents(pageIndex, pageSize);
		for (Student student : students) {
			System.out.println(student);
		}
	}
	
}

12. log4j.properties配置:

log4j.rootLogger=debug, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n

log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.org.apache=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值