您的位置:

Mybatis入门指南

一、什么是Mybatis

Mybatis是一款基于Java的持久化框架,它通过XML描述符或注解方式将Java对象映射到关系型数据库中。

它相对于Hibernate等ORM框架,提供了更为细致的SQL语句控制和数据库访问效率调优,更加适合针对特定场景进行开发。

二、搭建环境

开发环境:IntelliJ IDEA + Maven

首先,在pom.xml文件中添加Mybatis和MySQL驱动的依赖:

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.5</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.23</version>
    </dependency>
</dependencies>

创建数据库表user:

CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

在conf文件夹下创建mybatis-config.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.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="password"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

三、使用Mybatis

接下来,通过一个简单的示例来展示如何使用Mybatis实现对数据库表的增删改查操作。

1.创建POJO类

在Java源文件夹下创建一个User类:

public class User {
    private Long id;
    private String name;
    private Integer age;

    public User() {}

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    // getter、setter方法
}

2.创建Mapper映射文件

在resources文件夹下创建一个userMapper.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="org.example.dao.UserMapper">

    <resultMap id="UserMap" type="User">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="age" column="age"/>
    </resultMap>

    <!-- 查询数据 -->
    <select id="getUserById" resultMap="UserMap" parameterType="java.lang.Long">
        SELECT * FROM user WHERE id = #{id}
    </select>

    <select id="getAllUser" resultMap="UserMap">
        SELECT * FROM user
    </select>

    <!-- 插入数据 -->
    <insert id="insertUser" parameterType="User" keyProperty="id">
        INSERT INTO user (name, age) VALUES (#{name}, #{age})
    </insert>

    <!-- 更新数据 -->
    <update id="updateUser" parameterType="User">
        UPDATE user SET name=#{name}, age=#{age} WHERE id=#{id}
    </update>

    <!-- 删除数据 -->
    <delete id="deleteUserById" parameterType="java.lang.Long">
        DELETE FROM user WHERE id=#{id}
    </delete>

</mapper>

3.创建DAO层

使用Mybatis的SqlSession进行增删改查操作:

public class UserMapperImpl implements UserMapper {

    private final SqlSessionFactory sessionFactory;

    public UserMapperImpl(SqlSessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public User getUserById(Long id) {
        try(SqlSession sqlSession = sessionFactory.openSession()) {
            return sqlSession.selectOne("org.example.dao.UserMapper.getUserById", id);
        }
    }

    public List<User> getAllUser() {
        try(SqlSession sqlSession = sessionFactory.openSession()) {
            return sqlSession.selectList("org.example.dao.UserMapper.getAllUser");
        }
    }

    public Long insertUser(User user) {
        try(SqlSession sqlSession = sessionFactory.openSession(true)) {
            sqlSession.insert("org.example.dao.UserMapper.insertUser", user);
            return user.getId();
        }
    }

    public boolean updateUser(User user) {
        try(SqlSession sqlSession = sessionFactory.openSession(true)) {
            return sqlSession.update("org.example.dao.UserMapper.updateUser", user) == 1;
        }
    }

    public boolean deleteUserById(Long id) {
        try(SqlSession sqlSession = sessionFactory.openSession(true)) {
            return sqlSession.delete("org.example.dao.UserMapper.deleteUserById", id) == 1;
        }
    }
}

四、使用Mybatis注解

除了使用XML描述符方式,还可以使用注解方式操作数据库。两种方式是可以共存的。

1.创建UserDao接口

public interface UserDao {

    @Select("SELECT * FROM user WHERE id = #{id}")
    User getUserById(Long id);

    @Select("SELECT * FROM user")
    List<User> getAllUser();

    @Insert("INSERT INTO user(name, age) VALUES (#{name}, ${age})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insertUser(User user);

    @Update("UPDATE user SET name=#{name}, age=#{age} WHERE id=#{id}")
    boolean updateUser(User user);

    @Delete("DELETE FROM user WHERE id=#{id}")
    boolean deleteUserById(Long id);
}

2.创建UserDaoImpl类

使用注解完成SQL语句的工作

public class UserDaoImpl implements UserDao {

    private final SqlSessionFactory sessionFactory;

    public UserDaoImpl(SqlSessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public User getUserById(Long id) {
        try(SqlSession sqlSession = sessionFactory.openSession()) {
            return sqlSession.getMapper(UserDao.class).getUserById(id);
        }
    }

    public List<User> getAllUser() {
        try(SqlSession sqlSession = sessionFactory.openSession()) {
            return sqlSession.getMapper(UserDao.class).getAllUser();
        }
    }

    public void insertUser(User user) {
        try(SqlSession sqlSession = sessionFactory.openSession(true)) {
            sqlSession.getMapper(UserDao.class).insertUser(user);
        }
    }

    public boolean updateUser(User user) {
        try(SqlSession sqlSession = sessionFactory.openSession(true)) {
            return sqlSession.getMapper(UserDao.class).updateUser(user);
        }
    }

    public boolean deleteUserById(Long id) {
        try(SqlSession sqlSession = sessionFactory.openSession(true)) {
            return sqlSession.getMapper(UserDao.class).deleteUserById(id);
        }
    }
}

总结

Mybatis是一款非常适合特定场景快速开发的Java持久化框架,通过XML描述符或注解方式实现Java对象和数据库表的映射,可有效提高开发效率和数据库访问效率。

在实际开发中,根据业务需求灵活选择使用XML或注解方式,结合Mybatis提供的丰富功能,进行更为细致的SQL语句控制和数据库访问效率调优。