Mybatis 教程之Mybatis注解开发

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis 教程之Mybatis注解开发相关的知识,希望对你有一定的参考价值。

参考技术A

mybatis最初配置信息是基于 XML ,映射语句(SQL)也是定义在 XML 中的。而到了 MyBatis 3提供了新的基于注解的配置。

这里讲述 注解开发方式:

首先我们需要获取 SqlSession :

参数设置为 true 表示开启自动提交模式。

session 在注解形式的使用方式如:

所以mybatis 的使用使用三部分:

这里主要讲解 Mapper 层的开发规则。

sql 类型主要分成 : select @Select($sql) , update @Update($sql) , insert @Insert($sql) , delete ($sql) .

@Results 用来设置table信息与bean相关字段的映射关系, 每一个字段的关系使用 @Result 控制。

默认情况下对于每一table字段,例如 name , 会调用 bean 中的 setName(..) . 如果找不到,对于新版本的 mybatis 会报错。
例如上面的 cluster_name 会调用 setCluster_name() . 但是java 中使用的 clusterName ,可以通过 Result 注解控制.

@ResultMap 可以通过Id,应用其他的 Results

还有一种更改映射的方式:

mapUnderscoreToCamelCase 设置为true, 之后会自动实现 mysql 中的unix命名方式转为java的驼峰表示法。

@MapKey 此注解应用将查询数据转为 Map<>, 注意的是MapKey()中的id最终调用bean的getId 获取数据,所以需要映射bean字段而不是table.

@Param注解用于给方法参数起一个名字。以下是笔者总结的使用原则:
在方法只接受一个参数的情况下,可以不使用@Param。
在方法接受多个参数的情况下,建议一定要使用@Param注解给参数命名。

insert 时获取自增主键的方式:

法一:

法二:

# 的作用主要是替换预编译语句(PrepareStatement)中的占位符 ? :

对于 : INSERT INTO user (name) VALUES (#name); ==> INSERT INTO user (name) VALUES (?);

$ 符号的作用是直接进行字符串替换:

对于 : INSERT INTO user (name) VALUES (\'$name\'); ==> INSERT INTO user (name) VALUES (\'tianshozhi\');

JAVAEE框架技术之10-myBatis注解式开发

Mybatis注解开发

注解开发只需要写mapper接口即可,无需再书写对应的xxMapper.xml映射文件

对于单表操作还是比较方便的,但对多表操作就维护起来就比较麻烦了

数据库准备

添加依赖

<!--lombok-->
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.18.12</version>
  <scope>provided</scope>
</dependency>

<!-- mybatis -->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.6</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.16</version>
</dependency>
<!-- 测试用例 -->
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
</dependency>
<!-- 日志 -->
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-log4j12</artifactId>
  <version>1.6.4</version>
</dependency>

核心配置文件

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>
    <!-- 引入外部的配置文件 -->
    <properties resource="jdbc.properties"/>
    <!-- 开启驼峰匹配 -->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <!-- 连接数据库相关的配置  后面不用写,spring代替-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="$driverClass"/>
                <property name="url" value="$url"/>
                <property name="username" value="$jdbc.username"/>
                <property name="password" value="$jdbc.password"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <package name="cn.yanqi.mapper"/>
    </mappers>

</configuration>

jdbc.properties

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql:///mybatis
jdbc.username=root
jdbc.password=root

单表操作

实体类

@Data
public class User 
    private Long id;
    // 用户名
    private String userName;
    // 密码
    private String password;
    // 姓名
    private String name;
    // 年龄
    private Integer age;
    // 性别,1男性,2女性
    private Integer sex;
    // 出生日期
    private Date birthday;
    // 创建时间
    private Date created;
    // 更新时间
    private Date updated;


Mapper接口

/**
 * @Auther: yanqi
 * @Date:
 * @Dese:
 */
public interface UserMapper 

    @Select("select * from tb_user where id = #id")
    User findById(int id);

    @Select("select * from tb_user")
    List<User> selectAll();

    @Insert("INSERT INTO tb_user(id, user_name, password, name, age, sex, birthday, created, updated) VALUES (null,#userName,#password,#name,#age,#sex,#birthday,#created,#updated)")
    void adduser(User user);

    @Delete("delete from tb_user where id = #id")
    void delete(int id);

    @Update("update tb_user set user_name =#userName ,  updated = #updated where id =#id")
    void updateuser(User user);
    


测试

/**
 * @Auther: yanqi
 * @Date:
 * @Dese:
 */
public class UserMapperTest 

    private UserMapper userMapper;
    private SqlSession sqlSession ;
    private SqlSessionFactory sqlSessionFactory ;


    @Before
    public void setUp() throws Exception 
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = sqlSessionFactory.openSession();
        userMapper = sqlSession.getMapper(UserMapper.class);
    

    /**
     * 查询单个
     */
    @Test
    public void select() 
        User user = this.userMapper.findById(1);
        System.out.println(user);

    

    /**
     * 查询所有
     */
    @Test
    public void selectAll() 
        List<User> users = this.userMapper.selectAll();
        for(User user : users)
            System.out.println(user);
        
    

    /**
     * 添加
     */
    @Test
    public void adduser() 
        User user = new User();
        user.setUserName("小江江");
        user.setPassword("123");
        user.setName("一燕");
        user.setAge(27);
        user.setSex(2);
        user.setBirthday(new Date());
        user.setCreated(new Date());
        user.setUpdated(new Date());

        this.userMapper.adduser(user);
        this.sqlSession.commit();
    

    /**
     * 删除
     */
    @Test
    public void delete() 
        this.userMapper.delete(114);
        this.sqlSession.commit();
    

    /**
     * 修改
     */
    @Test
    public void updateuser() 
        User user = new User();
        user.setId(118L);
        user.setUserName("哈哈2");
        user.setUpdated(new Date());

        this.userMapper.updateuser(user);
        this.sqlSession.commit();
    


一对一

实体类

/**
 * 订单表
 */
@Data
public class Order 
    private Integer id;
    private Long userId;
    private String orderNumber;

    private User user;


Mapper接口


/**
 * @Auther: yanqi
 * @Dese: OrderMapper接口 实现一对一
 */
public interface OrderMapper 

    /**
     * 查询订单,并且查询出下单人的信息
     * @param
     * @return
     */
    @Select("select * from tb_order where order_number = #orderNum")
    @Results(
            /*映射user
                column:   order表中user_id外键,传递给UserMapper.findById的id
                property: order实体类中的user字段
             */
            @Result(
                    column = "id",
                    property ="user",
                    javaType = User.class,
                    one = @One(select = "cn.yanqi.mapper.UserMapper.findById"))
    		)
    List<Order> oneToOne(String orderNum);


public interface UserMapper 

    @Select("select * from tb_user where id = #id")
    User findById(int id);
    

测试

/**
 * @Auther: yanqi
 * @Date:
 * @Dese:
 */
public class UserMapperTest 

    private UserMapper userMapper;
    private OrderMapper orderMapper;
    private SqlSession sqlSession ;
    private SqlSessionFactory sqlSessionFactory ;


    @Before
    public void setUp() throws Exception 
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = sqlSessionFactory.openSession();
        userMapper = sqlSession.getMapper(UserMapper.class);
        orderMapper = sqlSession.getMapper(OrderMapper.class);

    

    /**
     * 测试一对一
     */
    @Test
    public void oneToOne()
        List<Order> orders = this.orderMapper.oneToOne("20200921002");
        for(Order order : orders)
            System.out.println(order);
        
    

一对多

实体类

/**
 * 订单表
 * 
 */
@Data
public class Order 
    private Integer id;
    private Long userId;
    private String orderNumber;

    private User user;

	private List<Orderdetail> orderdetails;

@Data
public class Orderdetail 
    private Integer id;
    private Double totalPrice;
    private Integer status;

Mapper接口

/**
 * @Auther: yanqi
 * @Date:
 * @Dese:
 */
public interface OrderMapper 

 /**
     * 查询订单,查询出下单人信息并且查询出订单详情。
     */
    @Select("select * from tb_order where order_number = #orderNum")
    @Results(
            /*映射user*/
            @Result(column = "id",
                    property ="user",
                    javaType = User.class,
                    one = @One(select = "cn.yanqi.mapper.UserMapper.findById")),
            /*映射orderdetails*/
            @Result(column = "id",
                    property = "orderdetails",
                    javaType =List.class,
                    many = @Many(select = "cn.yanqi.mapper.OrderDetailMapper.findById"))
    )
    List<Order> oneToMany(String orderNum);

/**
 * @Auther: yanqi
 */
public interface OrderDetailMapper 
    /**
     * 根据id查询订单详情
     * @param id
     */
    @Select("select * from tb_orderdetail where id = #id")
    Orderdetail findById(int id);


测试

/**
 * @Auther: yanqi
 * @Date:
 * @Dese:
 */
public class UserMapperTest 

    private UserMapper userMapper;
    private OrderMapper orderMapper;
    private SqlSession sqlSession ;
    private SqlSessionFactory sqlSessionFactory ;


    @Before
    public void setUp() throws Exception 
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = sqlSessionFactory.openSession();
        userMapper = sqlSession.getMapper(UserMapper.class);
        orderMapper = sqlSession.getMapper(OrderMapper.class);

    

    /**
     * 测试一对多
     */
    @Test
    public void oneToMany()
        List<Order> orders = this.orderMapper.oneToMany("20200921002");
        for(Order order : orders)
            System.out.println(order);
	

多对多

实体类

/**
 * 订单详情
 */
@Data
public class Orderdetail 
    private Integer id;
    private Double totalPrice;
    private Integer status;

    //商品信息
    private Item item;

/**
 * 商品表
 */
@Data
public class Item 
    private Integer id;
    private String itemName;
    private Float itemPrice;
    private String itemDetail;

Mapper接口

public interface OrderMapper 
       /**
     * 查询订单,查询出下单人信息并且查询出订单详情中的商品数据。
     */
    @Select("select * from tb_order where order_number = #orderNum")
    @Results(
            /*映射user*/
            @Result(column = "id",
                    property ="user",
                    javaType = User.class,
                    one = @One(select = "cn.yanqi.mapper.UserMapper.findById")),
            /*映射orderdetails*/
            @Result(column = "id",
                    property = "orderdetails",
                    javaType =List.class,
                    //查询Item商品
                    many = @Many(select = "cn.yanqi.mapper.ItemMapper.findById"))
            )
    List<Order> manyToMany(String orderNum);
    

public interface ItemMapper 

    @Select("select * from tb_item where id = #id")
    List<Item> findById(Integer id);
    

测试

  /**
     * 测试多对多
     */
    @Test
    public void manyToMany() 
        List<Order> orders = this.orderMapper.manyToMany("20200921002");
        for (Order order : orders) 
            System.out.println(order);
        
    

以上是关于Mybatis 教程之Mybatis注解开发的主要内容,如果未能解决你的问题,请参考以下文章

MyBatis-08-笔记

MyBatis注解开发之一对多查询

MyBatis框架之注解开发

MyBatis注解开发之多对多查询

MyBatis注解开发之一对一查询

MyBatis应用开发应用之开发方式注解方式篇