Mybatis入门例子

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介:

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;
本文转自博客园xingoo的博客,原文链接:Mybatis入门例子,如需转载请自行联系原博主。
相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
5月前
|
SQL Java 数据库连接
MyBatis 框架入门理论与实践
MyBatis 框架入门理论与实践
66 6
|
4月前
|
XML Java 数据库连接
MyBatis入门——MyBatis XML配置文件(3)
MyBatis入门——MyBatis XML配置文件(3)
56 6
|
4月前
|
Java 关系型数据库 数据库连接
MyBatis入门(1)
MyBatis入门(1)
59 2
|
5月前
|
Java 数据库连接 测试技术
MyBatis-Plus入门
MyBatis-Plus入门
|
2月前
|
SQL Java 数据库连接
Spring Boot联手MyBatis,打造开发利器:从入门到精通,实战教程带你飞越编程高峰!
【8月更文挑战第29天】Spring Boot与MyBatis分别是Java快速开发和持久层框架的优秀代表。本文通过整合Spring Boot与MyBatis,展示了如何在项目中添加相关依赖、配置数据源及MyBatis,并通过实战示例介绍了实体类、Mapper接口及Controller的创建过程。通过本文,你将学会如何利用这两款工具提高开发效率,实现数据的增删查改等复杂操作,为实际项目开发提供有力支持。
61 0
|
4月前
|
Java 关系型数据库 数据库连接
技术好文共享:第一讲mybatis入门知识
技术好文共享:第一讲mybatis入门知识
32 6
|
4月前
|
Java 关系型数据库 MySQL
Mybatis入门之在基于Springboot的框架下拿到MySQL中数据
Mybatis入门之在基于Springboot的框架下拿到MySQL中数据
39 4
|
4月前
|
Java 程序员
浅浅纪念花一个月完成Springboot+Mybatis+Springmvc+Vue2+elementUI的前后端交互入门项目
浅浅纪念花一个月完成Springboot+Mybatis+Springmvc+Vue2+elementUI的前后端交互入门项目
45 1
|
4月前
|
SQL Java 数据库连接
MyBatis入门——MyBatis的基础操作(2)
MyBatis入门——MyBatis的基础操作(2)
25 4
|
4月前
|
Java 数据库连接 数据库
Spring日志完结篇,MyBatis操作数据库(入门)
Spring日志完结篇,MyBatis操作数据库(入门)
下一篇
无影云桌面