文档章节

Mybatis学习笔记(一)--- 开始使用Mybatis

Ray2016
 Ray2016
发布于 2016/07/06 15:36
字数 883
阅读 7
收藏 0

        相比较传统的JDBC,使用Mybatis的好处在于省略了获取和释放数据库连接,准备PreparedStatement,向SQL中插入参数等代

码,使开发人员更加关注于数据持久代码的开发。本篇博客就从通过一个Demo来讲解如何使用Mybatis这个简单易用的持久层解决方案。


        创建STUDENTS数据表并向其中插入一些样本数据

CREATE TABLE STUDENTS
(
stud_id int(11) NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL,
email varchar(50) NOT NULL,
dob date DEFAULT NULL,
PRIMARY KEY (stud_id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

/*Sample Data for the students table */
insert into students(stud_id,name,email,dob)
values (1,'Student1', 'student1@gmail.com','1983-06-25');

insert into students(stud_id,name,email,dob)
values (2,'Student2', 'student2@gmail.com','1983-06-25');


        使用MAVEN创建JAVA项目

       项目结构如图所示:

        pom.xml文件为:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.learn</groupId>
	<artifactId>mybatis</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>mybatis</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.2.2</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.22</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.5</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.5</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>

        创建mybatis-config.xml和StudentMapper.xml配置文件

        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 alias="Student" type="com.learn.mybatis_demo.domain.Student" />
	</typeAliases>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
				<property name="username" value="root" />
				<property name="password" value="sa12345" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="com/learn/mybatis_demo/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">
<mapper namespace="com.learn.mybatis_demo.mappers.StudentMapper">
	<resultMap type="Student" id="StudentResult">
		<id property="studId" column="stud_id" />
		<result property="name" column="name" />
		<result property="email" column="email" />
		<result property="dob" column="dob" />
	</resultMap>

	<select id="findAllStudents" resultMap="StudentResult">
		SELECT * FROM STUDENTS
	</select>
	
	<select id="findStudentById" parameterType="int" resultType="Student">
		SELECT STUD_ID AS STUDID, NAME, EMAIL, DOB
		FROM STUDENTS WHERE STUD_ID=#{studId}
	</select>
	
	<insert id="insertStudent" parameterType="Student">
		INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB)
		VALUES(#{studId},#{name},#{email},#{dob})
	</insert>
</mapper>

        创建MyBatisSqlSessionFactory单例

package com.learn.mybatis_demo.util;

import java.io.IOException;
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 MyBatisSqlSessionFactory {

	private static SqlSessionFactory sqlSessionFactory;

	public static SqlSessionFactory getSqlSessionFactory() {
		if(sqlSessionFactory == null) {
			InputStream inputStream;
			try {
				inputStream = Resources.getResourceAsStream("mybatis-config.xml");
				sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			} catch (IOException e) {
				throw new RuntimeException(e.getCause());
			}
		}
		return sqlSessionFactory;
	}
	
	public static SqlSession openSession() {
		return getSqlSessionFactory().openSession();
	}
}


        创建StudentMapper接口和StudentService

package com.learn.mybatis_demo.domain;

import java.util.Date;

public class Student {

	private Integer studId;
	private String name;
	private String email;
	private Date dob;

	public Integer getStudId() {
		return studId;
	}

	public void setStudId(Integer studId) {
		this.studId = studId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public Date getDob() {
		return dob;
	}

	public void setDob(Date dob) {
		this.dob = dob;
	}
}

package com.learn.mybatis_demo.mappers;

import java.util.List;

import com.learn.mybatis_demo.domain.Student;

public interface StudentMapper {

	List<Student> findAllStudents();
	Student findStudentById(Integer id);
	void insertStudent(Student student);
}

package com.learn.mybatis_demo.service;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.learn.mybatis_demo.domain.Student;
import com.learn.mybatis_demo.mappers.StudentMapper;
import com.learn.mybatis_demo.util.MyBatisSqlSessionFactory;

public class StudentService {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	public List<Student> findAllStudents() {
		SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
		try {
			StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
			return studentMapper.findAllStudents();
		} finally {
			sqlSession.close();
		}
	}
	
	Student findStudentById(Integer studId) {
		logger.debug("Select Student By ID :{}", studId);
		SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
		try {
			StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
			return studentMapper.findStudentById(studId);
		} finally {
			sqlSession.close();
		}
	}
	void createStudent(Student student) {
		SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
		try {
			StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
			studentMapper.insertStudent(student);
			sqlSession.commit();
		} finally {
			sqlSession.close();
		}
	}
}

        创建JUnit测试来测试StudentService

package com.learn.mybatis_demo.service;

import java.util.Date;
import java.util.List;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import com.learn.mybatis_demo.domain.Student;

public class StudentServiceTest {

	private static StudentService studentService;
	
	@BeforeClass
	public static void setUp() {
		studentService = new StudentService(); 
	}
	
	@AfterClass
	public static void teardown() {
		studentService = null;
	}
	
	@Test
	public void testFindAllStudents() {
		List<Student> students = studentService.findAllStudents();
		Assert.assertNotNull(students);
		for (Student student : students) {
			System.out.println(student);
		}
	}
	
	@Test
	public void testFindStudentById() {
		Student student = studentService.findStudentById(1);
		Assert.assertNotNull(student);
		System.out.println(student);
	}
	
	@Test
	public void testCreateStudent() {
		Student student = new Student();
		int id = 3;
		student.setStudId(id);
		student.setName("student_" + id);
		student.setEmail("student_" + id + "@gmail.com");
		student.setDob(new Date());
		studentService.createStudent(student);
		Student newStudent = studentService.findStudentById(id);
		Assert.assertNotNull(newStudent);
	}
}

       测试结果截图








© 著作权归作者所有

共有 人打赏支持
Ray2016
粉丝 1
博文 4
码字总数 3859
作品 0
朝阳
程序员
私信 提问
MyBatis学习笔记系列教程

【MyBatis学习笔记】系列之预备篇一:ant的下载与安装 【MyBatis学习笔记】系列之预备篇二:ant入门示例 【MyBatis学习笔记】系列之一:MyBatis入门示例 【MyBatis学习笔记】系列之二:MyBat...

HenrySun
2016/10/15
19
0
如何在MyBatis-3.2.7中使用Log4j2 rc2——MyBatis学习笔记之十九

前天我上传了我的MyBatis系列课程(http://edu.51cto.com/course/course_id-1110.html)的第六讲,主要内容是如何使用Log4j2(具体版本为v2.0-rc1)为MyBatis 3.2.7配置日志。实际上目前最新...

NashMaster2011
2014/07/09
0
0
MyBatis多对多保存示例——MyBatis学习笔记之十七

前几天有网友问到MyBatis多对多的问题,不过愧对网友厚爱的是,最近一直忙,直到现在才有时间处理此事。今天就先写一个多对多保存的示例,算是对这位网友的初步回应,以后会有更多相关的博文...

NashMaster2011
2013/08/11
0
0
MyBatis中如何通过继承SqlSessionDaoSupport来编写DAO(二)

(本文示例工程源代码下载地址:http://down.51cto.com/data/1975295) 在上一篇博文的最后,介绍了使用@PostConstruct注解标注StudentDao的init方法,这样在Spring完成依赖注入后此方法即会...

NashMaster2011
2015/01/14
0
0
MyBatis多对多关联查询示例——MyBatis学习笔记之十八

MyBatis系列的上一篇博客发表时,笑笑还没有出生。转眼间八个月过去了,他已经是个大宝宝了。这么长时间未更新MyBatis系列的博客,想来真是罪过。不过有了宝宝之后,的确会分散自己很大一部分...

NashMaster2011
2014/04/23
0
0

没有更多内容

加载失败,请刷新页面

加载更多

dockerfile 镜像构建(1)

通用dockerfile 利用已经编译好的.jar 来构建镜像。要构建的目录如下: [root@iZuf61quxhnlk9m2tkx16cZ demo_jar]# docker build -t demo:1 . 运行镜像: [root@iZuf61quxhnlk9m2tkx16cZ de...

Canaan_
41分钟前
1
0
Redis radix tree源码解析

Redis实现了不定长压缩前缀的radix tree,用在集群模式下存储slot对应的的所有key信息。本文将详述在Redis中如何实现radix tree。 核心数据结构 raxNode是radix tree的核心数据结构,其结构体...

阿里云云栖社区
44分钟前
10
0
vue import 传入变量

在做动态添加component的时候,传入变量就会报错,出现以下错误信息: vue-router.esm.js?fe87:1921 Error: Cannot find module '@/components/index'. at eval (eval at ./src/components ......

朝如青丝暮成雪
46分钟前
2
0
Flutter开发 Dio拦截器实现token验证过期的功能

前言: 之前分享过在Android中使用Retrofit实现token失效刷新的处理方案,现在Flutter项目也有“token验证过期”的需求,所以接下来我简单总结一下在Flutter项目中如何实现自动刷新token并重...

EmilyWu
47分钟前
9
0
final Map可以修改内容,final 常量不能修改

1.final Map 可以put元素,但是不可以重新赋值 如: final Map map = new HashMap(); map = new HashMap();//不可以 因为栈中变量map引用地址不能修改 2.final str = “aa”; str = "bb";/......

qimh
50分钟前
4
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部