MYBATIS教程 – 注解方式

前面章节介绍了使用xml方式编写sql映射语句,实现对数据库的增删改查操作。本章将介绍另外一种方式,使用Java注解编写sql映射语句。

准备数据

MYBATIS教程 – 环境搭建中,我们创建好了数据库,数据库中包含了一个用户表。

CREATE DATABASE IF NOT EXISTS `qikegu_mybatis` 
USE `qikegu_mybatis`;

CREATE TABLE IF NOT EXISTS `user` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COMMENT='用户表';

INSERT INTO `user` (`id`, `name`) VALUES
    (1, 'user1'),
    (2, 'user2'),
    (3, 'user3'),
    (4, 'user4'),
    (5, 'user5');

User 类

创建一个对应的Java类:User.java

public class User {
    private long id;
    private String name;

    public User(String name) {
        super();
        this.name = name;
    }

    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

UserMapper.java

在前面章节中,使用xml方式编写sql映射语句,映射文件是UserMapper.xml,类似的,使用注解方式,映射文件可命名为UserMapper.java。

UserMapper是一个接口,我们通过给接口函数加注解编写sql映射语句。

可比较一下注解方式与xml方式编写sql映射语句的异同

UserMapper.java


public interface UserMapper { final String getAll = "SELECT * FROM User"; final String getById = "SELECT * FROM User WHERE id = #{id}"; final String deleteById = "DELETE from User WHERE id = #{id}"; final String insert = "INSERT INTO User (name) VALUES (#{name})"; final String update = "UPDATE User SET name = #{name} WHERE id = #{id}"; @Select(getAll) @Results(value = { @Result(property = "id", column = "id"), @Result(property = "name", column = "name") }) List<User> getAll(); @Select(getById) @Results(value = { @Result(property = "id", column = "ID"), @Result(property = "name", column = "NAME") }) User getById(long id); @Update(update) void update(User user); @Delete(deleteById) void delete(long id); @Insert(insert) @Options(useGeneratedKeys = true, keyProperty = "id") void insert(User user); }

修改MybatisConfig.xml中的mapper标签

MybatisConfig.xml中的<mapper>指向映射文件位置,按如下修改:

   <mappers>
      <mapper class = "com.qikegu.demo.mapper.UserMapper"/>
   </mappers>

App.java

应用程序main类文件。

package com.qikegu.demo;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

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 com.qikegu.demo.mapper.UserMapper;

public class App {

    public static void main(String args[]) throws IOException {

        Reader reader = Resources.getResourceAsReader("MybatisConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        SqlSession session = sqlSessionFactory.openSession();

        UserMapper mapper = session.getMapper(UserMapper.class); 

        System.out.println("------------ 数据插入 -----------");
        // 创建用户对象
        User user = new User("newUser100");

        // 插入新用户到数据库
        mapper.insert(user);
        session.commit();
        System.out.println("数据插入成功");

        System.out.println("------------ 读取用户列表 -----------");
        List<User> userList = mapper.getAll();

        for (User u : userList) {
            System.out.println(u.getId());
            System.out.println(u.getName());
        }

        System.out.println("读取用户列表成功");

        System.out.println("------------ 读取用户详情 -----------");
        User user1 = (User) mapper.getById(user.getId());

        System.out.println(user1.getId());
        System.out.println(user1.getName());

        System.out.println("读取用户详情成功");

        System.out.println("------------ 修改用户 -----------");
        user1.setName("userNameUpdated");
        mapper.update(user1);
        session.commit();

        // 查询修改后的用户详情
        User user2 = (User) mapper.getById(user.getId());

        System.out.println(user2.getId());
        System.out.println(user2.getName());
        System.out.println("修改用户成功");

        System.out.println("------------ 删除用户 -----------");
        mapper.delete(user.getId());
        System.out.println("删除用户成功");

        session.commit();
        session.close();
    }

}

运行

运行结果:

------------ 数据插入 -----------
数据插入成功
------------ 读取用户列表 -----------
1
user1
2
userNameUpdated
3
user3
4
user4
5
user5
6
newUser100
8
newUser100
9
newUser100
10
newUser100
11
newUser100
12
newUser100
13
newUser100
14
newUser100
读取用户列表成功
------------ 读取用户详情 -----------
14
newUser100
读取用户详情成功
------------ 修改用户 -----------
14
userNameUpdated
修改用户成功
------------ 删除用户 -----------
删除用户成功

例子源码

mybatis-demo2



浙ICP备17015664号 浙公网安备 33011002012336号 联系我们 网站地图  
@2019 qikegu.com 版权所有,禁止转载