需求介绍-MyBatis入门

首先就是安装Mysql Server 和Mysql Workbench

SqlSessionFactory:用于创建SqlSession的工厂类

SqlSessionMyBatis的核心组件用于向数据库执行SQL

XML文件:对MyBatis底层做一些配置。

Mapper接口:也就是DAO接口,常称为Mapper

Mapper映射器:用于编写SQL,并且将SQL和实体类映射的组件采用XML,注解都可以实现。

编写一些操作用户数据的代码。

代码

首先要引用MyBatisMysql的依赖,在pom.xml文件里。

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>

  

然后配置一下Mysql

# DataSourceProperties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/community?characterEncoding=utf-8&useSSL=false&serverTimezone=Hongkong
spring.datasource.username=root
spring.datasource.password=****
# 数据库连接池
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.maximum-pool-size=15
#最小空闲连接
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.idle-timeout=30000 # MybatisProperties
# mapper目录下
mybatis.mapper-locations=classpath:mapper/*.xml
# 实体类包名
mybatis.type-aliases-package=com.nowcoder.community.entity
mybatis.configuration.useGeneratedKeys=true
# 使得eg:header_url 和 headerUrl 形式匹配
mybatis.configuration.mapUnderscoreToCamelCase=true

  

User表进行数据处理,首先要写个实体类对应表,封装表里面的数据,方便我们去处理,写在entity下面:

User

package com.nowcoder.community.entity;

import java.util.Date;

public class User {
private int id;
private String username;
private String password;
private String salt;
private String email;
private int type;
private int status;
private String activationCode;
private String headerUrl;
private Date createTime; public void setId(int id) {
this.id = id;
} public void setUsername(String username) {
this.username = username;
} public void setPassword(String password) {
this.password = password;
} public void setSalt(String salt) {
this.salt = salt;
} public void setEmail(String email) {
this.email = email;
} public void setType(int type) {
this.type = type;
} public void setStatus(int status) {
this.status = status;
} public void setActivationCode(String activationCode) {
this.activationCode = activationCode;
} public void setHeaderUrl(String headerUrl) {
this.headerUrl = headerUrl;
} public void setCreateTime(Date createTime) {
this.createTime = createTime;
} public int getId() {
return id;
} public String getUsername() {
return username;
} public String getPassword() {
return password;
} public String getSalt() {
return salt;
} public String getEmail() {
return email;
} public int getType() {
return type;
} public int getStatus() {
return status;
} public String getActivationCode() {
return activationCode;
} public String getHeaderUrl() {
return headerUrl;
} public Date getCreateTime() {
return createTime;
} @Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", salt='" + salt + '\'' +
", email='" + email + '\'' +
", type=" + type +
", status=" + status +
", activationCode='" + activationCode + '\'' +
", headerUrl='" + headerUrl + '\'' +
", createTime=" + createTime +
'}';
}
}

  

然后再DAO层写一个接口(组件),写一些操作数据的方法的声明

package com.nowcoder.community.dao;

import com.nowcoder.community.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param; @Mapper
public interface UserMapper { User selectById(int id); User selectByName(String username); User selectByEmail(String email); int insertUser(User user);
int updateStatus(@Param("id") int id, @Param("status") int status);
int updateHeader(@Param("id") int id, @Param("headerUrl") String headerUrl);
int updatePassword(@Param("id") int id, @Param("password") String password);
}

  

然后我们就需要去写具体实现数据操作的xml文件了,就去mapper文件夹下面写,

首先你要在<mapper>里面写你写的这个是为哪个Mapper服务的,具体实现的时候就是写sql语句,你需要写id对应着你接口写的那个方法,才能够真正的去实现接口声明的方法才可以。

有个问题就是在接口声明方法的时候是有参数的嘛,你要确定这个是个什么参数,如果是java自带的参数类型就不用去管它,但是如果是复杂的参数比方说是个bean就需要声明另一个参数,具体见insertUser实现的那块,如果有对应到数据表的列名是数据库自己生成的话就不需要传进去需要另外取一个参数。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.nowcoder.community.dao.UserMapper"> <sql id="insertFields">
username, password, salt, email, type, status, activation_code, header_url, create_time
</sql> <sql id="selectFields">
id, username, password, salt, email, type, status, activation_code, header_url, create_time
</sql> <select id="selectById" resultType="User">
select <include refid="selectFields"></include>
from user
where id = #{id}
</select> <select id="selectByName" resultType="User">
select <include refid="selectFields"></include>
from user
where username = #{username}
</select> <select id="selectByEmail" resultType="User">
select <include refid="selectFields"></include>
from user
where email = #{email}
</select> <insert id="insertUser" parameterType="User" keyProperty="id">
insert into user (<include refid="insertFields"></include>)
values(#{username}, #{password}, #{salt}, #{email}, #{type}, #{status}, #{activationCode}, #{headerUrl}, #{createTime})
</insert> <update id="updateStatus">
update user set status = #{status} where id = #{id}
</update> <update id="updateHeader">
update user set header_url = #{headerUrl} where id = #{id}
</update> <update id="updatePassword">
update user set password = #{password} where id = #{id}
</update> </mapper>

  

然后写一个测试方法,看我们写的对不对,就去测试类里面实现:

MapperTest

package com.nowcoder.community;

import com.nowcoder.community.dao.UserMapper;
import com.nowcoder.community.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner; import java.util.Date; @RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class MapperTests { @Autowired
private UserMapper userMapper; @Test
public void testSelectUser() {
User user = userMapper.selectById(101);
System.out.println(user); user = userMapper.selectByName("liubei");
System.out.println(user); user = userMapper.selectByEmail("nowcoder101@sina.com");
System.out.println(user);
} @Test
public void testInsertUser() {
User user = new User();
user.setUsername("test");
user.setPassword("123456");
user.setSalt("abc");
user.setEmail("test@qq.com");
user.setHeaderUrl("http://www.nowcoder.com/101.png");
user.setCreateTime(new Date()); int rows = userMapper.insertUser(user);
System.out.println(rows);
System.out.println(user.getId());
} @Test
public void updateUser() {
int rows = userMapper.updateStatus(150, 1);
System.out.println(rows); rows = userMapper.updateHeader(150, "http://www.nowcoder.com/102.png");
System.out.println(rows); rows = userMapper.updatePassword(150, "hello");
System.out.println(rows);
} }

  

SpringBoot开发四-MyBatis入门的更多相关文章

  1. 【转载】 mybatis入门系列四之动态SQL

    mybatis 详解(五)------动态SQL 目录 1.动态SQL:if 语句 2.动态SQL:if+where 语句 3.动态SQL:if+set 语句 4.动态SQL:choose(when, ...

  2. 在springboot中集成mybatis开发

    在springboot中利用mybatis框架进行开发需要集成mybatis才能进行开发,那么如何在springboot中集成mybatis呢?按照以下几个步骤就可以实现springboot集成myb ...

  3. mybatis入门基础(二)----原始dao的开发和mapper代理开发

    承接上一篇 mybatis入门基础(一) 看过上一篇的朋友,肯定可以看出,里面的MybatisService中存在大量的重复代码,看起来不是很清楚,但第一次那样写,是为了解mybatis的执行步骤,先 ...

  4. SpringBoot(四)thymeleaf+MyBatis+MySql

    接着上一节 1.第一步:在pom文件中添加 <!-- MyBatis --> <dependency> <groupId>org.mybatis.spring.bo ...

  5. mybatis入门(四)

    mybatis入门 需求:根据id查询用户的信息 mysql数据库: CREATE TABLE `user` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `us ...

  6. SpringBoot开发快速入门

    SpringBoot开发快速入门 目录 一.Spring Boot 入门 1.Spring Boot 简介 2.微服务 3.环境准备 1.maven设置: 2.IDEA设置 4.Spring Boot ...

  7. SpringBoot开发二十-Redis入门以及Spring整合Redis

    安装 Redis,熟悉 Redis 的命令以及整合Redis,在Spring 中使用Redis. 代码实现 Redis 内置了 16 个库,索引是 0-15 ,默认选择第 0 个 Redis 的常用命 ...

  8. SpringBoot系列四:SpringBoot开发(改变环境属性、读取资源文件、Bean 配置、模版渲染、profile 配置)

    声明:本文来源于MLDN培训视频的课堂笔记,写在这里只是为了方便查阅. 1.概念 SpringBoot 开发深入 2.具体内容 在之前已经基本上了解了整个 SpringBoot 运行机制,但是也需要清 ...

  9. Springboot 完整搭建快速入门,必看!

    前言 手把手教你Springboot微服务项目搭建快速入门,通过本文学习Springboot的搭建快速入门,掌握微服务大致的配置服务,后续将会继续将核心组件引入到项目中,欢迎关注,点赞,转发. Spr ...

随机推荐

  1. Vue:node.js与vue安装配置

    下载node.js 官网: https://nodejs.org/zh-cn/ 查看node版本 node -v 配置淘宝NPM镜像源(下载速度快) npm install -g cnpm --reg ...

  2. 大数据-Hadoop 本地运行模式

    Grep案例 1. 创建在hadoop-2.7.2文件下面创建一个input文件夹 [atguigu@hadoop101 hadoop-2.7.2]$ mkdir input 2. 将Hadoop的x ...

  3. java.io.CharConversionException: Not an ISO 8859-1 character: [留]

    笔记一下 问题代码如下: response.setContentType("text/html;charset=utf-8");ServletOutputStream out = ...

  4. abp知识

    领域驱动开发的特点:1.分层更多,前期代码量大,后期维护方便2.业务进行了专业的领域划分,业务逻辑更加清晰,便于业务扩展.3.代码工程高内聚,更加精简.4.主要是解决复杂业务逻辑编写问题 为什么要使用 ...

  5. 【保姆级】Python项目(Flask网页)部署到Docker的完整过程

    大家好,我是辰哥~ 前提:相信看到这篇文章的读者应该已经学会了Docker的安装以及Docker的基本使用,如果还不会的可以参考我之前的文章进行详细学习! 1.安装版:2300+字!在不同系统上安装D ...

  6. Filter+Listener核心技术

    一.filter过滤器 javaweb三大组件:filter.listener.servlet. 过滤器是向web应用程序的请求和响应处理添加功能的web服务组件,可以在访问资源之前对请求和响应进行修 ...

  7. Python - 基本数据类型_Number 数字、bool 布尔、complex 复数

    Number 数字,是一个大的分类,细分四小类 整数:int 浮点数:float 布尔:bool 复数:complex int 的栗子 print(type(-1)) print(type(1)) p ...

  8. Command 'ifconfig' not found, but can be installed with: sudo apt install net-tools VM Ubuntu 解决方案

    VMware下安装的Ubuntu 一开始由于Firefox连不上网,然后通过看了https://www.bbsmax.com/A/VGzlEGYJbq/这个文章之后,自己也测了一下,确实好用 但是if ...

  9. 【16位RAW图像处理三】直方图均衡化及局部直方图均衡用于16位图像的细节增强。

    通常我们生活中遇到的图像,无论是jpg.还是png或者bmp格式,一般都是8位的(每个通道的像素值范围是0-255),但是随着一些硬件的发展,在很多行业比如医疗.红外.航拍等一些场景下,拥有更宽的量化 ...

  10. Leetcode13. 罗马数字转整数Leetcode14. 最长公共前缀Leetcode15. 三数之和Leetcode16. 最接近的三数之和Leetcode17. 电话号码的字母组合

    > 简洁易懂讲清原理,讲不清你来打我~ 输入字符串,输出对应整数 ![在这里插入图片描述](https://img-blog.csdnimg.cn/63802fda72be45eba98d9e4 ...