@Select

1、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>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <setting name="useGeneratedKeys" value="true"/>
    </settings>

    <typeAliases>
        <package name="com.forest.owl.entity"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC">
                <property name="" value=""/>
            </transactionManager>
            <dataSource type="UNPOOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/forest?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <package name="com.forest.owl.mapper"/>
    </mappers>
</configuration>

2、编写UserMapper接口

package com.forest.owl.mapper;

import com.forest.owl.entity.User;
import org.apache.ibatis.annotations.Select;

public interface UserMapper {
    @Select("SELECT * FROM user WHERE id=#{id}")
    User selectUserById(Long id);
}

3、测试

    @Test
    public void UserMapperTest(){
        SqlSession sqlSession = getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.selectUserById((long) 2);
        System.out.println(user.getUserName());
        System.out.println(user.getHeadImg());
        System.out.println(user.getCreateTime());
    }

4、关联查询

    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "userName", column = "user_name"),
            @Result(property = "userPassword", column = "user_password"),
            @Result(property = "userPhone", column = "user_phone"),
            @Result(property = "userEmail", column = "user_email"),
            @Result(property = "headImg", column = "head_img"),
            @Result(property = "createTime", column = "create_time"),
            @Result(property = "updateTime", column = "update_time"),
            @Result(property = "role.roleName", column = "role_name")
    })
    @Select("SELECT u.* ,r.role_name FROM user u INNER JOIN user_role ur on ur.user_id=u.id INNER JOIN role r on r.id=ur.role_id " +
            "WHERE u.id=#{id}")
    List<User> selectUserById(Long id);

关于注解形式的查询,也可以通过Provider进行sql的动态生成。如:

新建UserProvider类:

package com.forest.owl.provider;

import org.apache.ibatis.jdbc.SQL;

public class UserProvider {
    public String selectUserById(Long id){
        return new SQL(){
            {
                SELECT("u.* ,r.role_name");
                FROM("user u");
                LEFT_OUTER_JOIN("user_role ur on ur.user_id=u.id");
                LEFT_OUTER_JOIN("role r on r.id=ur.role_id");
                WHERE("u.id=#{id}");
            }
        }.toString();
    }
}

此时UserMapper可以这么写:

public interface UserMapper {
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "userName", column = "user_name"),
            @Result(property = "userPassword", column = "user_password"),
            @Result(property = "userPhone", column = "user_phone"),
            @Result(property = "userEmail", column = "user_email"),
            @Result(property = "headImg", column = "head_img"),
            @Result(property = "createTime", column = "create_time"),
            @Result(property = "updateTime", column = "update_time"),
            @Result(property = "role.roleName", column = "role_name")
    })
    @SelectProvider(type = UserProvider.class, method = "selectUserById")
    List<User> selectUserById(Long id);
}

@insert

这里介绍普通插入和返回主键方式的插入

普通插入数据

package com.forest.owl.mapper;

import com.forest.owl.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;

public interface UserMapper {
    @Insert("INSERT INTO user (user_name, user_password, user_phone, user_email, head_img, create_time, update_time) VALUES (#{userName}, #{userPassword}, #{userPhone}, #{userEmail}, #{headImg}, #{createTime}, #{updateTime})")int insertUser(User user);
}

回写主键方式的插入(注意:哪怕mybatis-config.xml配置中已经配置了useGeneratedKeys,在@Options中仍旧需要再配置一次)

package com.forest.owl.mapper;

import com.forest.owl.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;

public interface UserMapper {
    @Insert("INSERT INTO user (user_name, user_password, user_phone, user_email, head_img, create_time, update_time) VALUES (#{userName}, #{userPassword}, #{userPhone}, #{userEmail}, #{headImg}, #{createTime}, #{updateTime})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertUser(User user);
}

mybatis入门篇:Mybatis注解方式的基本用法的更多相关文章

  1. Spring Boot入门(六):使用MyBatis访问MySql数据库(注解方式)

    本系列博客记录自己学习Spring Boot的历程,如帮助到你,不胜荣幸,如有错误,欢迎指正! 本篇博客我们讲解下在Spring Boot中使用MyBatis访问MySql数据库的简单用法. 1.前期 ...

  2. SpringMVC入门(基于注解方式实现)

    ---------------------siwuxie095                             SpringMVC 入门(基于注解方式实现)         SpringMVC ...

  3. Python入门篇-类型注解

    Python入门篇-类型注解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.函数定义的弊端 1>.动态语言很灵活,但是这种特性也是弊端 Python是动态语言,变量随时可 ...

  4. MyBatis从入门到精通(五):MyBatis 注解方式的基本用法

    最近在读刘增辉老师所著的<MyBatis从入门到精通>一书,很有收获,于是将自己学习的过程以博客形式输出,如有错误,欢迎指正,如帮助到你,不胜荣幸! 1. @Select 注解 1.1 使 ...

  5. Mybatis入门篇之结果映射,你射准了吗?

    目录 前言 什么是结果映射? 如何映射? 别名映射 驼峰映射 配置文件开启驼峰映射 配置类中开启驼峰映射 resultMap映射 总结 高级结果映射 关联(association) 例子 关联的嵌套 ...

  6. 从零开始学JAVA(09)-使用SpringMVC4 + Mybatis + MySql 例子(注解方式开发)

    项目需要,继续学习springmvc,这里加入Mybatis对数据库的访问,并写下一个简单的例子便于以后学习,希望对看的人有帮助.上一篇被移出博客主页,这一篇努力排版整齐,更原创,希望不要再被移出主页 ...

  7. MyBatis入门篇

    一.什么是MyBatis MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改 ...

  8. springboot整合mybatis完整示例, mapper注解方式和xml配置文件方式实现(我们要优雅地编程)

    一.注解方式 pom <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId& ...

  9. mybatis入门篇:代码生成器(MyBatis Generator)

    这篇文章只是按照自己的需要去配置代码生成器,未对所有配置进行讲解,需要了解具体详情的,请到官网查阅文档.传送门:http://www.mybatis.org/generator/ 1.首先引入相关的依 ...

  10. mybatis入门篇:通过SqlSession.selectList进行数据查询

    作为一个java菜鸟,早就从慕课网中学到一些基本的mybatis的用法,但是一直不成体系,懵懵懂懂,既然正式入了java这个坑,就打算好好学学,所以买了本<MyBatis从入门到精通>,在 ...

随机推荐

  1. 使用min-device-pixel-ratio媒体功能实现真正的1像素border

    关于设备像素比的知识,想必做过移动端开发的都有接触,这里就不介绍啦,万一有不懂的可以看张鑫旭大神的设备像素比devicePixelRatio简单介绍 由于设备像素比存在的原因,我们在处理设计图的一些边 ...

  2. 请求转发和URL重定向的原理和区别

    一.请求转发和重定向是在java后台servlet中,由一个servlet跳转到另一个servlet/jsp要使用的技术 使用方法 请求转发  req.getResquestDispatcher(se ...

  3. 2018.5.4 Unix的五种IO模型

    阻塞非阻塞和异步同步 同步和异步关注的是消息通信机制,关注两个对象之间的调用关系. 阻塞和非阻塞关注的是程序在等待调用结果(消息,返回值)时的状态,关注单一程序. Unix的五种IO模型 以下基于Li ...

  4. python 一些方法的时间测试

    尝试一些方法的不同实现,比较一下时间,电脑比较渣,不过只是做个比较 虽然用python主要是方便,肯定是不快的,不过能快一点还是快一点好 numpy中大量使用同样 shape 的全 0 array,可 ...

  5. python leetcode 颠倒二进制数

    我的做法,,这个题在于必须补0 def reverseBits(n): num=32-len(bin(n)[2:]) m = bin(n)[2:][::-1] if num > 0: for i ...

  6. Python_day_01

    python                                                       (1024程序员节) 语言分为很多种,但是如果要想和计算机交流,就必须知道计算 ...

  7. Networked Graphics: Building Networked Games and Virtual Environments (Anthony Steed / Manuel Fradinho Oliveira 著)

    PART I GROUNDWORK CHAPTER 1 Introduction CHAPTER 2 One on One (101) CHAPTER 3 Overview of the Intern ...

  8. openstack--10--知识点补充

    关于uuid和Fernet方式比较 提供令牌有四种方式[fernet|pkiz|pki|uuid]默认是uuid.

  9. Python之print()函数

    1. 输出字符串 >>> str = 'Hello World' >>> print (str) Hello World 2. 格式化输出整数 支持参数格式化 &g ...

  10. 【Jmeter】Address already in use : connect &&Permission denied: connect 解决方案

    Address already in use : connect   该问题的原因为: Windows 提供给 TCP/IP链接的端口为 1024-5000,并且要四分钟来循环回收他们.就导致我们在短 ...