@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. complex类的设计实现

    #include <iostream> #include <cmath> using namespace std; class Complex{ ,); Complex(Com ...

  2. hadoop MapReduce

    简单介绍 官方给出的介绍是hadoop MR是一个用于轻松编写以一种可靠的.容错的方式在商业化硬件上的大型集群上并行处理大量数据的应用程序的软件框架. MR任务通常会先把输入的数据集切分成独立的块(可 ...

  3. 【开发】iOS入门 - XCode快捷键

    XCode使用第一天,从熟悉快捷键开始... 搜索相关的快捷键: 搜文件.类和方法 - Command + Shift + O 搜字符串 - Command + Shift + F 定位文件 - Co ...

  4. ios-Nav右上角按钮

    右上角的设置按钮 //****************** 右上角保存按钮 ****************** UIButton *rightBtn = [UIButton buttonWithTy ...

  5. python 和python-m 的区别

    首先在python自带的,help命令中,可以看到,官方的说明是:-m mod : run library module as a script (terminates option list) 意思 ...

  6. mysql异常 : The driver has not received any packets from the server.

    异常: 结论:域名写错了或报这个异常

  7. .net core 存储base64的图片或文件

    public void SaveImageFromBase64(string base64string) { byte[] b = Convert.FromBase64String(base64str ...

  8. [转]OpenShift 集群搭建指南

    转自:http://www.cnblogs.com/zhangning/p/7251810.html OpenShift 集群搭建指南 v1.0 搭建Hyper-v虚拟机或物理机 配置物理机静态IP, ...

  9. 关于让simulink中display组件显示二进制的方法

    关于让simulink中display组件显示二进制的方法 1.首先需要配置gateway out模块,勾选propagate data type to output 2.配置display模块 fo ...

  10. golang操作memcached 转自https://blog.csdn.net/weixin_37696997/article/details/78760397

    go使用memcached需要第三方的驱动库,这里有一个库是memcached作者亲自实现的,代码质量效率肯定会有保障 1:安装 go get github.com/bradfitz/gomemcac ...