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

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: 探索Android软键盘的疑难杂症 深入探讨Android异步精髓Handler 详解Android主流框架不可或缺的基石 站在源码的肩膀上全解Scroller工作机制Android多分...

探索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的入门示例就已经全部完成了。

项目结构图如下所示:

这里写图片描述

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
3月前
|
关系型数据库 Java 数据库连接
MyBatis-Plus简介和入门操作
【1月更文挑战第5天】 一、MyBatis-Plus简介 二、 MyBatis-Plus操作 1、准备数据库脚本 2、准备boot工程 3、导入依赖 4、配置文件和启动类 5、功能编码 6、测试和使用
105 1
|
3月前
|
SQL Java 数据库连接
JAVAEE框架技术之7-myBatis ORM框架入门基础CRUD
JAVAEE框架技术之7-myBatis ORM框架入门基础CRUD
90 0
JAVAEE框架技术之7-myBatis ORM框架入门基础CRUD
|
1月前
|
SQL JavaScript Java
mybatis-flex入门体验(一)
`shigen`,一个专注于Java、Python、Vue和Shell的博主,分享成长和认知。近期探索了`mybatis-flex`,通过官网学习了代码生成和编码体验。配置数据源和依赖后,利用示例代码生成了符合Lombok+MyBatis Plus规范的实体和Mapper。此外,展示了如何配置SQL打印,并用测试代码演示了查询、多条件查询和更新操作。`mybatis-flex`的亮点在于流畅的查询语法和连表查询功能。后续将分享更多关于连表查询的实践。一起学习,每天进步!
35 0
mybatis-flex入门体验(一)
|
1月前
|
JavaScript Java 数据库连接
Spring Boot 2.0+Mybatis+Vue的轻量级后台管理系统
Spring Boot 2.0+Mybatis+Vue的轻量级后台管理系统
|
1月前
|
Java 数据库连接 mybatis
|
2月前
|
XML Java 数据库连接
MyBatis入门配置
【2月更文挑战第9天】
MyBatis入门配置
|
3月前
|
Java 数据库连接 API
MyBatis入门操作
MyBatis入门操作
13 0
|
3月前
|
Java 数据库连接 测试技术
【MyBatis】操作数据库——入门
【MyBatis】操作数据库——入门
|
3月前
|
SQL Java 关系型数据库
一文彻底搞懂Mybatis系列(一)之mybatis入门
一文彻底搞懂Mybatis系列(一)之mybatis入门
|
4月前
|
SQL Java 数据库连接
MyBatis Plus 入门
MyBatis Plus 入门
50 0