后台(35)——MyBatis入门示例

探索Android软键盘的疑难杂症
深入探讨Android异步精髓Handler
详解Android主流框架不可或缺的基石
站在源码的肩膀上全解Scroller工作机制

Android多分辨率适配框架(1)— 核心基础
Android多分辨率适配框架(2)— 原理剖析
Android多分辨率适配框架(3)— 使用指南

自定义View系列教程00–推翻自己和过往,重学自定义View
自定义View系列教程01–常用工具介绍
自定义View系列教程02–onMeasure源码详尽分析
自定义View系列教程03–onLayout源码详尽分析
自定义View系列教程04–Draw源码分析及其实践
自定义View系列教程05–示例分析
自定义View系列教程06–详解View的Touch事件处理
自定义View系列教程07–详解ViewGroup分发Touch事件
自定义View系列教程08–滑动冲突的产生及其处理


##版权声明


在本篇博客中,我们来一起完成MyBatis的入门示例

##准备数据库和表

DROP TABLE student;

CREATE TABLE student( 
           id INT PRIMARY KEY AUTO_INCREMENT,
           name VARCHAR(100), 
           gender VARCHAR(10), 
           birthday DATE 
);


INSERT INTO student (name,gender,birthday) VALUES ('波多结衣','female','1995-12-11');
INSERT INTO student (name,gender,birthday) VALUES ('波少结衣','female','1996-11-12');
INSERT INTO student (name,gender,birthday) VALUES ('杉原杏璃','female','1997-10-13');
INSERT INTO student (name,gender,birthday) VALUES ('佐佐木希','female','1998-09-14');
INSERT INTO student (name,gender,birthday) VALUES ('伊藤梅子','female','1999-08-15');

我们建立数据库mb,并创建一张表student并为其插入数据。

##创建JavaBean

/**
 * 本文作者:谷哥的小弟
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
package cn.com.helloworld;

import java.util.Date;

public class Student {
	private int id;
	private String name;
	private String gender;
	private Date birthday;
	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 String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", gender=" + gender
				+ ", birthday=" + birthday + "]";
	}
	
}

请注意:将JavaBean中的字段与数据库中表中的字段保持一致

##导入MyBatis相关jar包
请下载MyBatis开发所需jar包并存放至工程的lib目录。

##SqlMapConfig.xml
在有了数据库和JavaBean之后我们来编写MyBatis的全局配置文件SqlMapConfig.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>
	<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/mb?characterEncoding=utf-8" />
				<property name="username" value="root" />
				<property name="password" value="root" />
			</dataSource>
		</environment>
	</environments>
</configuration>

在该配置文件中配置由MyBatis所采用的事务和数据库连接池

##StudentMapper.xml
刚才我们编写了MyBatis的全局配置文件SqlMapConfig.xml,现在我们来编写与JavaBean相关的配置文件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="student">
	
</mapper>

我们在该配置文件中添加标签<mapper></mapper>并设置其namespace为student。

再将StudentMapper.xml配置到SqlMapConfig.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>
	<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/mb?characterEncoding=utf-8" />
				<property name="username" value="root" />
				<property name="password" value="root" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="sqlmap/StudentMapper.xml" />
	</mappers>
</configuration>

请参见代码第15—17行

##CRUD操作
在完成了之上的准备工作后,我们来利用MyBatis实现简单的增删改查。

我们先来做一个最简单的例子:依据Stundet的id查询学生信息

首先在映射文件StudentMapper.xml中写sql语句:

<?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="student">

	<select id="findStudentById" parameterType="int" resultType="cn.com.helloworld.Student">
		SELECT * FROM student WHERE id=#{value}
	</select>
	
</mapper>

在该xml文件中为我们的需求写了一个sql语句,请注意

  • id标识该sql语句的唯一性,因为之后随着功能的扩展在该xml文件中会有许多sql语句。其实,类似于StudentMapper.xml这样的mapper.xml文件中每一个sql语句都对应一个MappedStatement对象,sql语句的id即是MappedStatement的id。
  • parameterType表示输入参数类型。此处我们要依据id查询学生,那么输入参数就是一个int类型的数字
  • resultType表示查询结果的返回类型。在此,我们想得到一个Student对象,所以将resultType设置为cn.com.helloworld.Student
  • #{ }表示占位符,用于接收输入参数。输入参数的类型可以是简单类型,pojo、HashMap。如果输入参数是简单类型那么#{}的括号中可以写成value或其它名称。

在完成了映射文件的编码之后,我们再来书写Java代码

/**
 * 本文作者:谷哥的小弟
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
package cn.com.helloworld;

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;
import org.junit.Test;

public class CRUDTest {
	@Test
	public void findStudentById() throws IOException {
		String resource = "SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession sqlSession = sqlSessionFactory.openSession();
		Student student = sqlSession.selectOne("student.findStudentById", 1);
		System.out.println(student);
		sqlSession.close();
	}
}

代码详解如下:

  • 获取MyBatis的全局配置文件SqlMapConfig.xml,请参见代码第18—19行
  • 利用全局配置文件创建SqlSessionFactory,请参见代码第20行
  • 利用SqlSessionFactory创建SqlSession,请参见代码第21行
  • 利用SqlSession调用其selectOne()方法查询一条学生信息,请参见代码第22行。请注意该方法参数:第一个参数用于标识一条sql语句,其构成为:映射文件的namespace+"."+MappedStatement的id(即sql语句的id);第二参数是需要传递给sql语句的输入参数。
  • 关闭SqlSession,释放资源;请参见代码第24行

输出结果如下:

Student [id=1, name=波多结衣, gender=female, birthday=Mon Dec 11 00:00:00 CST 1995]

至此,我们走完了一个利用MyBatis查询数据的完整流程。

刚才这个例子是查询出来了单条记录,如果要查询多条记录又该怎么做呢?
比如查询出学生名字中带有"结"这个字的所有学生,请看如下代码:

<select id="findStudentByName" parameterType="java.lang.String" resultType="cn.com.helloworld.Student">
		SELECT * FROM student WHERE name LIKE '%${value}%'
	</select>

在该映射文件中采用${ }表示拼接,它所接收的输入参数类型可以是简单类型,pojo,HashMap。如果接收简单类型,${}中只能写成value。当${}接收pojo对象值时可通过OGNL读取对象中的属性值;即利用属性.属性.属性…的方式获取对象属性值

在完成映射文件的编写之后,我们再来看Java代码:

@Test
	public void findStudentByName() throws IOException {
		String resource = "SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession sqlSession = sqlSessionFactory.openSession();
		List<Student> list = sqlSession.selectList("student.findStudentByName", "结");
		for(Student student:list){
			System.out.println(student);
		}
		sqlSession.close();
	}

在此利用了qlSession.selectList( )方法返回一个查询后的集合。

输出结果如下:

Student [id=1, name=波多结衣, gender=female, birthday=Mon Dec 11 00:00:00 CST 1995]
Student [id=2, name=波少结衣, gender=female, birthday=Tue Nov 12 00:00:00 CST 1996]

在完成查询操作后,我们向数据库插入一条新数据,并得到新数据被插入到数据库后它的主键值。

<insert id="insertStudent" parameterType="cn.com.helloworld.Student">
		<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
			SELECT LAST_INSERT_ID()
		</selectKey>
		INSERT INTO student (name,gender,birthday) value (#{name},#{gender},#{birthday})
	</insert>

我们在<insert></insert>标签中使用了标签<selectKey></selectKey>
获取插入数据的主键并将其设置到Student对象中.

  • SELECT LAST_INSERT_ID():得到insert记录的主键值,只适用与自增主键
  • keyProperty:用于指明将查询到的主键值设置到parameterType指定的对象的哪个属性
  • order:表示SELECT LAST_INSERT_ID()相对于insert语句的执行顺序。在该例子中用AFTER表示执行完该insert语句后再执行SELECT LAST_INSERT_ID()
  • resultType:指定SELECT LAST_INSERT_ID()的结果的类型
@Test
	public void insertStudent() throws IOException {
		String resource = "SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession sqlSession = sqlSessionFactory.openSession();
		Student student=new Student();
		student.setName("右右木希");
		student.setGender("female");
		student.setBirthday(new Date());
		sqlSession.insert("student.insertStudent",student);
		sqlSession.commit();
		sqlSession.close();
		System.out.println(""+student.getId());
	}

代码解析如下:

  • 利用sqlSession.insert()将数据插入数据库,请参见代码第11行
  • 利用sqlSession.commit()提交事务,请参见代码第12行
  • 获取到新插入数据的主键值,请参见代码第14行

继续来看删除数据的操作

<delete id="deleteStudent" parameterType="java.lang.Integer">
		DELETE FROM student where id=#{id}
</delete>

Java代码如下:

@Test
	public void deleteStudent() throws IOException {
		String resource = "SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession sqlSession = sqlSessionFactory.openSession();
		sqlSession.delete("student.deleteStudent", 1);
		sqlSession.commit();
		sqlSession.close();
	}

最后来瞅瞅更新操作

<update id="updateStudent" parameterType="cn.com.helloworld.Student">
	    UPDATE student set name=#{name},gender=#{gender},birthday=#{birthday} where id=#{id}
	</update>

Java代码如下:

  @Test
	public void updateStudent() throws IOException {
		String resource = "SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession sqlSession = sqlSessionFactory.openSession();
		Student student=new Student();
		student.setId(3);
		student.setName("中中木希");
		student.setGender("female");
		student.setBirthday(new Date());
		sqlSession.update("student.updateStudent", student);
		sqlSession.commit();
		sqlSession.close();
	}

嗯哼,至此我们关于MyBatis的入门示例就已经全部完成了。

项目结构图如下所示:

这里写图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

谷哥的小弟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值