mybatis3的基本使用0

本文详细介绍了一个使用MyBatis实现的学生信息管理系统案例,包括数据库建模、Maven项目的搭建、依赖配置、工具类编写、JavaBean定义、Mapper接口及XML映射文件的创建,并通过JUnit进行功能测试。

创建db_mybatis数据库,再创建t_student表,内含id,name, age字段。

CREATE TABLE `t_student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=15 DEFAULT CHARSET=utf8

 

创建maven项目tmybatis项目,

pom.xml添加如下依赖,

<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
        <dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.26</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.2.8</version>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.2</version>
		</dependency>

 

这样就把mybatis,mysql-jdbc common-logging和junit都引入到依赖中。

第一步,新建util包,建一个SqlSessionFactoryUtil工具类,用于获取sqlSession

package com.dxwpay.tmybatis.util;

import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class SqlSessionFactoryUtil {
	
	private static SqlSessionFactory sqlSessionFactory;
	
	private static SqlSessionFactory getSqlSessionFactory() {
		if(sqlSessionFactory == null) {
			InputStream inputStream = null;
			try {
				inputStream = Resources.getResourceAsStream("mybatis-config.xml");
				sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
		return sqlSessionFactory;
	}
	
	public static SqlSession openSession() {
		return getSqlSessionFactory().openSession();
	}

}

 

第二步,建model包,编写Student的javaBean

package com.dxwpay.tmybatis.model;

public class Student {
	
	private int id;
	private String name;
	private int age;
	
	public Student() {
		super();
	}
	public Student(int id, String name, int age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
	
	

}

第三步,建mappers包,创建StudentMapper接口mapper

package com.dxwpay.tmybatis.mappers;

import java.util.List;
import java.util.Map;

import com.dxwpay.tmybatis.model.Student;

public interface StudentMapper {
	
	public int add(Student student);
	public int delete(int id);
	public Student select(int id);
	public int update(Student student);
	public List<Student> selectAll();
	
	public List<Student> selectByPage(Map map);


}

把各种配置文件写好,如mybatis-config.xml, jdbc.properties文件

 jdbc.properties

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

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>
	<!-- 引入jdbc配置文件 -->
	<properties resource="jdbc.properties" />

	<typeAliases>
		<typeAlias type="com.dxwpay.tmybatis.model.Student" alias="Student" />
	</typeAliases>

	<!-- 对事务的管理和连接池的配置 -->
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driverClassName}" />
				<property name="url" value="${jdbc.url}" />
				<property name="username" value="${jdbc.username}" />
				<property name="password" value="${jdbc.password}" />
			</dataSource>
		</environment>
	</environments>
	
	<!-- mapping 文件路径配置 -->  
    <mappers>  
        <mapper resource="com/dxwpay/tmybatis/mappers/StudentMapper.xml" />  
    </mappers>  

</configuration>

写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">

<!-- namespace:必须与对应的接口全类名一致 id:必须与对应接口的某个对应的方法名一致 -->
<mapper namespace="com.dxwpay.tmybatis.mappers.StudentMapper">
    <resultMap type="Student" id="StudentResult">
        <id property="id" column="id" />
        <result property="name" column="name" />
        <result property="age" column="age" />
    </resultMap>

	<insert id="add" parameterType="Student">
		insert into t_student values(null,#{name},#{age})
	</insert>
 	<delete id="delete" parameterType="Integer">
		delete from t_student where id=#{id}
	</delete>
	<update id="update" parameterType="Student">
	    update t_student set name=#{name},age=#{age} where id=#{id}
	</update>
	<select id="select" parameterType="Integer" resultType="Student">
	    select * from t_student where id=#{id}
	</select>
	<select id="selectAll" resultMap="StudentResult">
	    select * from t_student
	</select>
	
	<select id="selectByPage" parameterType="Map" resultMap="StudentResult">
	    select * from t_student limit #{pageStart},#{pageSize}
	</select>
	

</mapper>

 

这里再写juit的测试(StudentMapperTest)。

package com.dxwpay.tmybatis.test.mappers;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.dxwpay.tmybatis.mappers.StudentMapper;
import com.dxwpay.tmybatis.model.Student;
import com.dxwpay.tmybatis.util.SqlSessionFactoryUtil;

public class StudentMapperTest {
	
	private static Log logger = LogFactory.getLog(StudentMapperTest.class);
	private SqlSession sqlSession = null;
	private StudentMapper studentMapper = null;
	@Before
	public void setUp() throws Exception {
		sqlSession = SqlSessionFactoryUtil.openSession();
		studentMapper = sqlSession.getMapper(StudentMapper.class);
	}
	
	@After
	public void tearDown() throws Exception {
		sqlSession.close();
	}
	
	@Test
	public void TestAdd() {
		logger.info("---添加学生---");
		Student student = new Student();
		student.setName("得分提");
		student.setAge(26);
		int i = studentMapper.add(student);
		sqlSession.commit();
		if(i == 0) {
			logger.info("添加学生失败!");
		} else {
			logger.info("添加学生成功,影响行数: " + i);
		}
	}
	
	@Test
	public void TestDelete() {
		logger.info("---删除学生---");
		int i = studentMapper.delete(5);
		sqlSession.commit();
		if(i == 0) {
			logger.info("删除学生失败!");
		} else {
			logger.info("删除学生成功,影响行数: " + i);
		}
	}
	
	@Test
	public void TestUpdate() {
		logger.info("---更新学生---");
		Student student = new Student(3,"天生",33);
		int i = studentMapper.update(student);
		sqlSession.commit();
		if(i == 0) {
			logger.info("更新学生失败!");
		} else {
			logger.info("更新学生成功,影响行数: " + i);
		}
	}
	
	@Test
	public void TestSelect() {
		logger.info("---查询学生---");
		Student student = studentMapper.select(3);
		logger.info(student);
	}
	
	@Test
	public void TestSelectAll() {
		logger.info("---查询所有学生---");
		List<Student> listStudent = studentMapper.selectAll();
		for(Student s: listStudent) {
			logger.info(s);
		}
	}
	
	@Test
	public void TestSelectByPage() {
		logger.info("---按分页查询学生---");
		Map<String, Object> map = new HashMap<String,Object>();
		int page = 1;
		int pageSize = 5;
		map.put("pageStart", (page-1) * pageSize );
		map.put("pageSize", pageSize);
		List<Student> listStudent = studentMapper.selectByPage(map);
		for(Student s: listStudent) {
			logger.info(s);
		}
	}

}

可以分别对某个方法进行junit或者对整个mapper进行juit测试。

运行结果如下:

八月 02, 2016 10:53:46 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestDelete
信息: ---删除学生---
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestDelete
信息: 删除学生失败!
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestSelect
信息: ---查询学生---
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestSelect
信息: Student [id=3, name=李生, age=33]
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestUpdate
信息: ---更新学生---
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestUpdate
信息: 更新学生成功,影响行数: 1
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestSelectAll
信息: ---查询所有学生---
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestSelectAll
信息: Student [id=1, name=张三, age=21]
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestSelectAll
信息: Student [id=2, name=李四, age=32]
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestSelectAll
信息: Student [id=3, name=天生, age=33]
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestSelectAll
信息: Student [id=4, name=魏云, age=32]
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestSelectAll
信息: Student [id=6, name=学魏, age=23]
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestSelectAll
信息: Student [id=7, name=魏学, age=24]
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestSelectAll
信息: Student [id=8, name=魏学23, age=24]
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestSelectAll
信息: Student [id=9, name=蒋魏学, age=24]
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestSelectAll
信息: Student [id=10, name=待得分, age=26]
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestSelectAll
信息: Student [id=11, name=得分提, age=26]
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestSelectAll
信息: Student [id=12, name=得分提, age=26]
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestSelectAll
信息: Student [id=13, name=得分提, age=26]
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestSelectAll
信息: Student [id=14, name=得分提, age=26]
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestAdd
信息: ---添加学生---
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestAdd
信息: 添加学生成功,影响行数: 1
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestSelectByPage
信息: ---按分页查询学生---
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestSelectByPage
信息: Student [id=1, name=张三, age=21]
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestSelectByPage
信息: Student [id=2, name=李四, age=32]
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestSelectByPage
信息: Student [id=3, name=天生, age=33]
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestSelectByPage
信息: Student [id=4, name=魏云, age=32]
八月 02, 2016 10:53:47 下午 com.dxwpay.tmybatis.test.mappers.StudentMapperTest TestSelectByPage
信息: Student [id=6, name=学魏, age=23]

可以看到删除失败,是因为测试过一次,那个数据已经被删除了。其它测试成功。!

转载于:https://my.oschina.net/lenglingx/blog/726181

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值