浅入浅出MyBatis(14):使用注解

2015-01-14

该文章是《专题:浅入浅出MyBatis》系列文章的一篇。点击进入该专题目录

工具与环境:Intellij IDEA 14,JDK 1.7,MyBatis 3.2,MySQL 5.5。

浅入浅出MyBatis(01):查询id为1的用户的信息中,我们使用了xml文件配置SQL语句,xml给人的印象是略显复杂。通过注解(Annotation),我们可以减少xml配置文件的使用。注解的相关内容较多,本文只给个例子。

修改letian.mybatis.dao下的UserMapper.java

package letian.mybatis.dao;

import letian.mybatis.bean.User;
import org.apache.ibatis.annotations.*;

public interface UserMapper {

    @Select("select * from blog_db.user where id=#{id}")
    @Results(
            {
                    @Result(id = true, column = "id", property = "id"),
                    @Result(column = "name", property = "name"),
                    @Result(column = "email", property = "email"),
                    @Result(column = "password", property = "password")
            })
    User findById(int id);

    @Insert("INSERT INTO blog_db.user (name, email, password) " +
            "VALUES (#{name}, #{email}, #{password} )")
    @Options(useGeneratedKeys=true, keyProperty="id")
    void insertUser1(User user);

    @Insert("INSERT INTO blog_db.user (name, email, password) " +
            "VALUES ( #{user.name}, #{user.email}, CONCAT(#{user.password}, #{passwordSuffix}) )")
    void insertUser2(@Param("user")User user, @Param("passwordSuffix")String passwordSuffix);
}

UserMapper接口给出了两个方法,并都使用了注解来配置自己。

修改MyBatis配置

将mybatis-config.xml中的

<mappers>
    <mapper resource="letian/mybatis/mapper/UserMapper.xml"/>
</mappers>

修改为:

<mappers>
    <mapper class="letian.mybatis.dao.UserMapper" />
</mappers>

修改Main.java

import java.io.IOException;

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 letian.mybatis.bean.User;
import letian.mybatis.dao.UserMapper;


public class Main {

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

        SqlSessionFactory sessionFactory;
        sessionFactory = new SqlSessionFactoryBuilder()
                .build(Resources.getResourceAsReader("mybatis-config.xml"));

        SqlSession sqlSession = sessionFactory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        System.out.println(userMapper.findById(1));

        User user1 = new User();
        user1.setName("user1");
        user1.setEmail("user1@111.com");
        user1.setPassword("456");

        User user2 = new User();
        user2.setName("user2");
        user2.setEmail("user2@111.com");
        user2.setPassword("456");

        userMapper.insertUser1(user1);
        userMapper.insertUser2(user2, "-end");
        sqlSession.commit();

        System.out.println(user1);
        System.out.println(user2);

        sqlSession.close();

    }
}

运行结果如下:

User{id=1, name='letian', email='letian@111.com', password='123'}
User{id=31, name='user1', email='user1@111.com', password='456'}
User{id=0, name='user2', email='user2@111.com', password='456'}

查看一下user表:

mysql> select * from blog_db.user;
+----+--------+----------------+----------+
| id | name   | email          | password |
+----+--------+----------------+----------+
|  1 | letian | letian@111.com | 123      |
|  2 | xiaosi | xiaosi@111.com | 123      |
| 31 | user1  | user1@111.com  | 456      |
| 32 | user2  | user2@111.com  | 456-end  |
+----+--------+----------------+----------+
4 rows in set (0.00 sec)

更多内容

Java Persistence with MyBatis 3(中文版) 第四章 使用注解配置SQL映射器这篇翻译给出了MyBatis注解的详尽内容。

Getting Started with iBatis (MyBatis): Annotations给出了一些示例。

Mybatis 3.0.5 insert/update statement mapping with multiple inputs给出了一个xml和注解同时使用的示例。