Mybatis入门例子
Mybatis是轻量级的持久化框架,的确上手非常快.
Mybatis大体上的思路就是由一个总的config文件配置全局的信息,比如mysql连接信息等。然后再mapper中指定查询的sql,以及参数和返回值。
在Service中直接调用这个mapper即可。
依赖的jar包
<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>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
</dependency>
主要的mybatis配置文件
<?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="mybatis.Student"/>
</typeAliases>
<!-- 配置mysql连接 -->
<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://192.168.56.101:3306/mysql"/>
<property name="username" value="root"/>
<property name="password" value="123qwe"/>
</dataSource>
</environment>
</environments>
<!-- 配置mapper -->
<mappers>
<mapper resource="StudentMapper.xml"/>
</mappers>
</configuration>
创建SqlSession工厂
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){
System.out.println(e.getMessage());
}
}
return sqlSessionFactory;
}
public static SqlSession openSession(){
return getSqlSessionFactory().openSession();
}
}
创建Student类:
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;
}
}
创建Mapper配置文件
<?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="mybatis.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=#{ID}
</select>
<insert id="insertStudent" parameterType="Student">
INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB) VALUES(#{studId},#{name},#{email},#{dob})
</insert>
</mapper>
创建Mapper接口
public interface StudentMapper {
List<Student> findAllStudents();
Student findStudentById(Integer id);
void insertStudent(Student student);
}
创建服务类和测试类
public class StudentService {
public List<Student> findAllStudents(){
SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
try{
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
return studentMapper.findAllStudents();
}finally {
sqlSession.close();
}
}
public Student findStudentById(Integer studId){
SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
return studentMapper.findStudentById(studId);
}finally {
sqlSession.close();
}
}
public void createStudent(Student student){
SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
try{
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
studentMapper.insertStudent(student);
sqlSession.commit();
}finally {
sqlSession.close();
}
}
}
单元测试类
public class StudentServiceTest {
private static StudentService studentService;
@BeforeClass
public static void setup(){
studentService = new mybatis.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();
student.setStudId(3);
student.setName("student_"+3);
student.setEmail("student_"+3+"@email.com");
student.setDob(new Date());
studentService.createStudent(student);
Student newStudent = studentService.findStudentById(3);
Assert.assertNotNull(newStudent);
}
}
数据库脚本
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)
);
insert into STUDENTS(stud_id,name,email,dob) values(1,"student1","student1@email.com","1999-08-08");
insert into STUDENTS(stud_id,name,email,dob) values(2,"student2","student2@email.com","2000-01-01");
select * from STUDENTS;
Mybatis入门例子的更多相关文章
- MyBatis入门(五)---延时加载、缓存
一.创建数据库 1.1.建立数据库 /* SQLyog Enterprise v12.09 (64 bit) MySQL - 5.7.9-log : Database - mybatis ****** ...
- Mybatis入门看这一篇就够了
什么是MyBatis MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为 ...
- mybatis入门--初识mybatis
初识mybatis 今天,一起来说说mybits这个框架吧.这是一个持久层的框架.之前叫做ibatis.所以,在它的代码中出现ibatis这个词的时候,不要感到惊讶.不是写错了,它确实就是这个样子的. ...
- Mybatis入门篇之结果映射,你射准了吗?
目录 前言 什么是结果映射? 如何映射? 别名映射 驼峰映射 配置文件开启驼峰映射 配置类中开启驼峰映射 resultMap映射 总结 高级结果映射 关联(association) 例子 关联的嵌套 ...
- MyBatis1:MyBatis入门
MyBatis是什么 MyBatis是什么,MyBatis的jar包中有它的官方文档,文档是这么描述MyBatis的: MyBatis is a first class persistence fra ...
- mybatis入门基础(二)----原始dao的开发和mapper代理开发
承接上一篇 mybatis入门基础(一) 看过上一篇的朋友,肯定可以看出,里面的MybatisService中存在大量的重复代码,看起来不是很清楚,但第一次那样写,是为了解mybatis的执行步骤,先 ...
- MyBatis入门基础(一)
一:对原生态JDBC问题的总结 新项目要使用mybatis作为持久层框架,由于本人之前一直使用的Hibernate,对mybatis的用法实在欠缺,最近几天计划把mybatis学习一哈,特将学习笔记记 ...
- 【Bootstrap Demo】入门例子创建
本文简单介绍下如何来使用 Bootstrap,通过引入 Bootstrap,来实现一个最基本的入门例子. 在前一篇博文[Bootstrap]1.初识Bootstrap 基础之上,我们完全可以更加方便快 ...
- MyBatis入门案例、增删改查
一.MyBatis入门案例: ①:引入jar包 ②:创建实体类 Dept,并进行封装 ③ 在Src下创建大配置mybatis-config.xml <?xml version="1.0 ...
随机推荐
- max min 与 min max 的差别
在求解最优化问题时,遇到一个对偶问题的转换:对于形如 的问题,可以转换为求解 即原问题的对偶问题.而在一般情况下: 对于这个为题的说明我参照http://math.stackexchange.com/ ...
- CSS无序列实现表宽度自适应的表格
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 堆排序Heap sort
堆排序有点小复杂,分成三块 第一块,什么是堆,什么是最大堆 第二块,怎么将堆调整为最大堆,这部分是重点 第三块,堆排序介绍 第一块,什么是堆,什么是最大堆 什么是堆 这里的堆(二叉堆),指得不是堆栈的 ...
- Ansible常用模块
http://liumissyou.blog.51cto.com/4828343/1749121
- Linux下连接MSSQL之安装FreeTDS
$ tsql -H MSSQL服务器服务IP -p 1433 -U MSSQL服务器登陆帐号 -P MSSQL服务器登陆密码http://www.cnblogs.com/ilovexiao/p/355 ...
- PHP AJAX上传文件
- Pointers and Dynamic Allocation of Memory
METHOD 1: Consider the case where we do not know the number of elements in each row at compile time, ...
- 从up6-down2升级到down3
概述: 添加存储过程down_f_process.sql,down_f_del.sql 更新DnFile.updateProcess,DnFile.Delete 更新down.js 更新down.fo ...
- 网页的Width ,Height
Jquery中可直接用接口$().height(); 获取浏览器窗口高$(window).height() 获取内部文档高$("body").height() 原生JS 网页可见区 ...
- hibernate中保存一个对象后再设置此对象的属性为什么不需要调用update方法了
hibernate中保存一个对象后再设置此对象的属性为什么不需要调用update方法了 例如session.save(user);user.setAge(20); 原因: hibernate对象的三种 ...