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

来源:互联网 发布:男朋友尺寸大体验知乎 编辑:程序博客网 时间:2024/05/01 05:20

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;}@Overridepublic 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 studentsset 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.Driverjdbc.url=jdbc:mysql://localhost:3306/mybatisjdbc.username=rootjdbc.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@Transactionalpublic class StudentServImpl implements StudentServ {@Resourceprivate 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 {@AutowiredStudentServ studentServ;@Testpublic 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 */@Testpublic void testDeleteStudent() throws Exception {int studNo = 10001;int result = studentServ.deleteStudent(studNo);System.out.println("result = " + result);}/** * 测试updateStudent方法 * @throws Exception */@Testpublic 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 */@Testpublic void testGetStudent() throws Exception {int studNo = 10001;Student student = studentServ.getStudent(studNo);System.out.println(student);}/** * 测试getAllStudents方法 * @throws Exception */@Testpublic void testGetAllStudents() throws Exception {List<Student> students = studentServ.getAllStudents();for (Student student : students) {System.out.println(student);} }/** * 测试pagingQueryStudents方法 * @throws Exception */@Testpublic 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#Consolelog4j.appender.Console=org.apache.log4j.ConsoleAppenderlog4j.appender.Console.layout=org.apache.log4j.PatternLayoutlog4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%nlog4j.logger.java.sql.ResultSet=DEBUGlog4j.logger.org.apache=DEBUGlog4j.logger.java.sql.Connection=DEBUGlog4j.logger.java.sql.Statement=DEBUGlog4j.logger.java.sql.PreparedStatement=DEBUG


0 0
原创粉丝点击