mybatis入门篇:Mybatis注解方式的基本用法
@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注解方式的基本用法的更多相关文章
- Spring Boot入门(六):使用MyBatis访问MySql数据库(注解方式)
本系列博客记录自己学习Spring Boot的历程,如帮助到你,不胜荣幸,如有错误,欢迎指正! 本篇博客我们讲解下在Spring Boot中使用MyBatis访问MySql数据库的简单用法. 1.前期 ...
- SpringMVC入门(基于注解方式实现)
---------------------siwuxie095 SpringMVC 入门(基于注解方式实现) SpringMVC ...
- Python入门篇-类型注解
Python入门篇-类型注解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.函数定义的弊端 1>.动态语言很灵活,但是这种特性也是弊端 Python是动态语言,变量随时可 ...
- MyBatis从入门到精通(五):MyBatis 注解方式的基本用法
最近在读刘增辉老师所著的<MyBatis从入门到精通>一书,很有收获,于是将自己学习的过程以博客形式输出,如有错误,欢迎指正,如帮助到你,不胜荣幸! 1. @Select 注解 1.1 使 ...
- Mybatis入门篇之结果映射,你射准了吗?
目录 前言 什么是结果映射? 如何映射? 别名映射 驼峰映射 配置文件开启驼峰映射 配置类中开启驼峰映射 resultMap映射 总结 高级结果映射 关联(association) 例子 关联的嵌套 ...
- 从零开始学JAVA(09)-使用SpringMVC4 + Mybatis + MySql 例子(注解方式开发)
项目需要,继续学习springmvc,这里加入Mybatis对数据库的访问,并写下一个简单的例子便于以后学习,希望对看的人有帮助.上一篇被移出博客主页,这一篇努力排版整齐,更原创,希望不要再被移出主页 ...
- MyBatis入门篇
一.什么是MyBatis MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改 ...
- springboot整合mybatis完整示例, mapper注解方式和xml配置文件方式实现(我们要优雅地编程)
一.注解方式 pom <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId& ...
- mybatis入门篇:代码生成器(MyBatis Generator)
这篇文章只是按照自己的需要去配置代码生成器,未对所有配置进行讲解,需要了解具体详情的,请到官网查阅文档.传送门:http://www.mybatis.org/generator/ 1.首先引入相关的依 ...
- mybatis入门篇:通过SqlSession.selectList进行数据查询
作为一个java菜鸟,早就从慕课网中学到一些基本的mybatis的用法,但是一直不成体系,懵懵懂懂,既然正式入了java这个坑,就打算好好学学,所以买了本<MyBatis从入门到精通>,在 ...
随机推荐
- Python学习之路基础篇--03Python基础+万恶的运算符
1 格式化输出% 用%s(用来表示str数据类型) 和 %d (用来表示int数据类型),如果要用%号的话,就要使用两个%%,这样即可输出. 2 初识编码 电脑的传输数据,储存都是用的 0101010 ...
- 解决eclipse使用tomcat启动项目后访问项目404的问题
今天启动项目的时候发现项目启动没有问题,但是一直访问不到页面,F12发现根本没有交互,百度后解决了,故记下来为以后提供方法,若有不同的解决方法,欢迎指教 1.首先要确保你的tomcat下没有项目,怎么 ...
- 零基础学习python(2)
再讲新知识之前,先将一些之前没提的东西再介绍一下: (1) 命令行模式 在Windows开始菜单选择“命令提示符”(或者是在搜索栏中输入“cmd”),就进入到命令行模式,它的提示符类似C:\>: ...
- webpack打包和gulp打包工具详细教程
30分钟手把手教你学webpack实战 阅读目录 一:什么是webpack? 他有什么优点? 二:如何安装和配置 三:理解webpack加载器 四:理解less-loader加载器的使用 五:理解ba ...
- python 第三方库
1.tqdm 进度条 from tqdm import tqdm for i in tqdm(range(10000)): pass 2.fire 自动创建命令行接口(command line int ...
- centos7下安装nginx
1.yum install epel-release(安装epel(Extra Packages for Enterprise Linux)) 2.yum repolist(确保epel添加到yum的 ...
- 《DenseNet Models for Tiny ImageNet Classification》课程设计论文
paper : <DenseNet Models for Tiny ImageNet Classification> https://arxiv.org/ftp/arxiv/pap ...
- Azure DevOps Server/Team Foundation Server
TFS wasn't designed specifically to support a requirements management process. Epics are like big st ...
- redis 设置分布式锁要避免死锁
1. jedis 中 setnx key value 虽然可以处理同步问题 (setnx 有返回值 1是key不存在把它设置进去,0是key已经存在了)但是 setnx设置完后 程序的下一步 有可能挂 ...
- python MySQL执行SQL查询结果返回字典
写自动化测试的时候我希望执行数据库前置任务,把数据库查询的结果作为请求的参数,但是正常返回结果为列表嵌套里面,这样就会影响到关键字准确的获取,特别的受限于SQL的查询字段的的顺序,所以希望返回的单条数 ...