后台(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并为其插入数据。
/**
* 本文作者:谷哥的小弟
* 博客地址: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包并存放至工程的lib目录。
在有了数据库和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所采用的事务和数据库连接池
刚才我们编写了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行
在完成了之上的准备工作后,我们来利用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语句,请注意
在完成了映射文件的编码之后,我们再来书写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();
}
}
代码详解如下:
输出结果如下:
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对象中.
@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());
}
代码解析如下:
继续来看删除数据的操作
<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的入门示例就已经全部完成了。
项目结构图如下所示:
网友评论