首页 > 编程语言 >MyBatis入门到掌握(JAVA)

MyBatis入门到掌握(JAVA)

时间:2024-04-04 11:05:00浏览次数:25  
标签:JAVA 入门 userInfo import MyBatis Integer password id userinfo

建立连接可能涉及到的问题(只需要自己改一下就行)

1、MyBatis是⼀款优秀的 持久层 框架,⽤于简化JDBC的开发

2、数据库连接配置

(1)yml配置

# 数据库连接配置
spring:
 datasource:
 url: jdbc:mysql://127.0.0.1:3306/mybatis_test?
characterEncoding=utf8&useSSL=false
 username: root
 password: root
 driver-class-name: com.mysql.cj.jdbc.Driver

(2)properties配置

#驱动类名称
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#数据库连接的url
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mybatis_test?
characterEncoding=utf8&useSSL=false
#连接数据库的⽤⼾名
spring.datasource.username=root
#连接数据库的密码
spring.datasource.password=root

3、数据库建表代码

-- 创建数据库
DROP DATABASE IF EXISTS mybatis_test;
CREATE DATABASE mybatis_test DEFAULT CHARACTER SET utf8mb4;
-- 使⽤数据数据
USE mybatis_test;
-- 创建表[⽤⼾表]
DROP TABLE IF EXISTS userinfo;
CREATE TABLE `userinfo` (
 `id` INT ( 11 ) NOT NULL AUTO_INCREMENT,
 `username` VARCHAR ( 127 ) NOT NULL,
 `password` VARCHAR ( 127 ) NOT NULL,
 `age` TINYINT ( 4 ) NOT NULL,
 `gender` TINYINT ( 4 ) DEFAULT '0' COMMENT '1-男 2-⼥ 0-默认',
 `phone` VARCHAR ( 15 ) DEFAULT NULL,
 `delete_flag` TINYINT ( 4 ) DEFAULT 0 COMMENT '0-正常, 1-删除',
 `create_time` DATETIME DEFAULT now(),
 `update_time` DATETIME DEFAULT now(),
 PRIMARY KEY ( `id` ) 
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4; 
-- 添加⽤⼾信息
INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )
VALUES ( 'admin', 'admin', 18, 1, '18612340001' );
INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )
VALUES ( 'zhangsan', 'zhangsan', 18, 1, '18612340002' );
INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )
VALUES ( 'lisi', 'lisi', 18, 1, '18612340003' );
INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )
VALUES ( 'wangwu', 'wangwu', 18, 1, '18612340004' );

4、需要引入的pom文件依赖

<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>4.0.0</version>
        </dependency>

5、数据库查询代码

(1)接口

package com.example.demo;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface UserInfoMapper {
    //访问数据库数据
    @Select("select * from userinfo")
    List<UserInfo> queryUserList();
}

(2)定义对象

package com.example.demo;
import lombok.Data;
import java.util.Date;

@Data
public class UserInfo {
    //数据库里面有什么我们这里就定义什么
    private  Integer id;
    private String username;
    private  String password;
    private Integer age;
    private Integer gender;
    private String phone;
    private Integer deleteFlag;
    private Date createTime;
    private Date updateTime;
}

(3)测试类

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class DemoApplicationTests {
    @Autowired
private UserInfoMapper userInfoMapper;
    @Test
    void contextLoads() {
        System.out.println(userInfoMapper.queryUserList());
    }
}

6、数据删除方式有两种

(1)逻辑删除:update(推荐)

(2)物理删除:delete

7、在Mybatis当中我们可以借助⽇志, 查看到sql语句的执⾏、执⾏传递的参数以及执⾏结果在配置⽂件中进⾏配置

mybatis:
 configuration: # 配置打印 MyBatis⽇志
   log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

8、生成测试(测试类上面要加@SpringBootTest)

9、单参查寻(只有一个参数时#后面的名称无所谓随便定义)

(1)接口部分代码

    @Select("select * from userinfo where id = #{userId}")
    UserInfo queryUserInfo(Integer userId);

(2)测试部分代码

void queryUserInfo() {
        log.info(userInfoMapper.queryUserInfo(1).toString());
    }

10、多参数时

(1)接口部分代码(idea上面创建的代码)阿里云创建的不能应用此方法

@Select("select * from userinfo where id = #{userId} and delete_flag = #{deleteFlag}")
    UserInfo queryUserInfo( Integer userId, Integer deleteFlag);

(1)接口部分代码(阿里云创建的项目代码)

    @Select("select * from userinfo where id = #{param1} and delete_flag = #{param2}")
    UserInfo queryUserInfo(Integer id, Integer deleteFlag);

(2)测试部分代码

 void testQueryUserInfo() {
        log.info(userInfoMapper.queryUserInfo(1,0).toString());
    }

11、参数重命名(重命名之后不能用之前的)

(1)接口部分代码

    @Select("select * from userinfo where id = #{id} and delete_flag = #{param2}")
    UserInfo queryUserInfo(@Param("id") Integer id, Integer deleteFlag);

(2)测试部分代码

void testQueryUserInfo() {
        log.info(userInfoMapper.queryUserInfo(1,0).toString());
    }

12、web调用查询代码(三层架构模式)

(1)Controller代码

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/queryAllUser")
    public List<UserInfo> queryAllUser(){
        return userService.queryAllUser();
    }
}

(2)Service代码

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    public List<UserInfo> queryAllUser(){
        return userInfoMapper.queryUserList();
    }
}

(3)Mapper代码

package com.example.demo;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface UserInfoMapper {
    //访问数据库数据
    @Select("select * from userinfo")
    List<UserInfo> queryUserList();
}

(4)查询结果

13、插入数据

(1)接口部分代码

 @Select("insert into userinfo (username,password,age,gender,phone) values(#{username},#{password},#{age},#{gender},#{phone})")
    Integer insert(UserInfo userInfo);

(2)测试部分代码

    @Test
    void insert() {
        UserInfo userInfo=new UserInfo();
        userInfo.setUsername("zhangsan");
        userInfo.setPassword("123456");
        userInfo.setAge(18);
        userInfo.setGender(0);
        userInfo.setPhone("18330322");
        userInfoMapper.insert(userInfo);
    }

(3)重命名的方式

@Select("insert into userinfo (username,password,age,gender,phone) " +
            "values(#{userInfo.username},#{userInfo.password},#{userInfo.age},#{userInfo.gender},#{userInfo.phone})")
    Integer insert(@Param("userInfo") UserInfo userInfo);

(4)获得自增的数据,比如我们买东西我们可以看我们买了多少东西,这样有个数

(4.1)接口部分代码

@Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into userinfo (username,password,age,gender,phone) " +
            "values(#{username},#{password},#{age},#{gender},#{phone})")
    Integer insert(UserInfo userInfo);

(4.2)测试部分代码

   @Test
    void insert() {
        UserInfo userInfo=new UserInfo();
        userInfo.setUsername("zhangsan");
        userInfo.setPassword("123456");
        userInfo.setAge(18);
        userInfo.setGender(0);
        userInfo.setPhone("18330322");
        Integer result= userInfoMapper.insert(userInfo);
        log.info("插入了几条数据"+result+"自增Id是"+userInfo.getId());
    }

14、删除数据

(1)接口部分代码

 @Delete("delete from userinfo where id=#{id}")
    Integer delete(@Param("id") Integer id);

(2)测试部分代码

    @Test
    void delete() {
       userInfoMapper.delete(11);
    }

15、更改数据

(1)接口部分代码(idea创建的项目)

 @Update("update userinfo set password=#{password} where id=#{id}")
    Integer update(String password,Integer id);

(1)接口部分代码(阿里云创建的项目)

@Update("update userinfo set password=#{param1} where id=#{param2}")
    Integer update(String password,Integer id);

(2)测试部分代码

  @Test
    void update() {
        userInfoMapper.update("777777",12);
    }

15.1、放在对象里更新

(1)接口部分代码

 @Update("update userinfo set username=#{username},password=#{password},age=#{age} where id=#{id}")
 Integer update(UserInfo userInfo);

(2)测试部分代码

@Test
  void update() {
       UserInfo userInfo=new UserInfo();
       userInfo.setUsername("lisi");
       userInfo.setPassword("987654");
       userInfo.setAge(10);
       userInfo.setId(12);
       userInfoMapper.update(userInfo);
 }

16、mybatis赋值失败原因

(1)解决办法

(1.1)改别名 用as的方法

@Select("select id,username,password,age,phone," +
 "delete_flag as deleteFlag,create_time as createTime,update_time as updateTime from userinfo")
    List<UserInfo> queryUserList();

(1.2)注解方式

  @Results({
            @Result(column = "delete_flag",property = "deleteFlag"),
            @Result(column = "create_time",property = "createTime"),
    })
    @Select("select * from userinfo")
    List<UserInfo> queryUserList();

(1.3)1.2的@Results的复用

 @Results(id = "base",value = {
      @Result(column = "delete_flag",property = "deleteFlag"),
      @Result(column = "create_time",property = "createTime"),
  })
 @Select("select * from userinfo")
 List<UserInfo> queryUserList();
 @ResultMap(value = "base")
 @Select("select id,username,password,age,phone,delete_flag ,create_time,update_time from userinfo")
 UserInfo queryUserInfo( Integer userId, Integer deleteFlag);

♥(1.4)开启驼峰命名(推荐)

直接配置yml文件

mybatis:
 configuration:
   map-underscore-to-camel-case: true

标签:JAVA,入门,userInfo,import,MyBatis,Integer,password,id,userinfo
From: https://blog.csdn.net/m0_69134284/article/details/137203120

相关文章

  • 使用Java通过键盘输入获取菱形图案
    简介:在这篇文章中,我们将学习如何使用Java编程语言通过键盘输入获取用户指定的行数,然后输出菱形图案。菱形图案是一种经典的图形,通过控制空格和星号的数量可以打印出美观的图案。步骤:引入Scanner类:在Java中,我们可以使用Scanner类来接收用户的键盘输入。首先需要引入java.ut......
  • Python爬虫如何快速入门
    写了几篇网络爬虫的博文后,有网友留言问Python爬虫如何入门?今天就来了解一下什么是爬虫,如何快速的上手Python爬虫。一、什么是网络爬虫网络爬虫,英文名称为WebCrawler或Spider,是一种通过程序在互联网上自动获取信息的技术。它根据指定的规则,从互联网上下载网页、图片、视......
  • Java面试题:Java集合框架:请简述Java集合框架的主要组成部分,并解释它们之间的关系。
    Java集合框架(JavaCollectionsFramework)是一组用来表示和操作集合的类的集合,它提供了用于存储不同类型对象的标准化接口和类。Java集合框架的主要组成部分包括以下几个部分:集合接口(CollectionInterface):这是所有集合类的根接口,定义了集合的基本操作,如添加、删除、判断存在......
  • Java面试题:解释Java泛型的主要用途,并说明泛型擦除的概念。
    Java泛型(Generics)的主要用途是提供一种编写可重用且类型安全的代码的方法。它们允许在编程时使用类型参数,这些类型参数可以在运行时被具体的类或接口替换。泛型的主要优点包括:类型安全:泛型编译时会进行类型检查,确保在运行时使用的是正确的类型,从而减少类型转换错误。代码复......
  • Java面试题:简述数据库性能优化的常见手段,如索引优化、SQL语句优化等。
    数据库性能优化是确保数据库系统高效运行的关键步骤。以下是一些常见的数据库性能优化手段:1.索引优化:创建索引:为经常用于查询条件的字段创建索引,可以大大加快查询速度。避免过多索引:虽然索引可以加快查询,但过多索引会减慢写操作,并占用额外空间。使用复合索引:当查询条件包......
  • Java面试题:解释微服务架构的概念及其优缺点,讨论微服务拆分的原则。
    微服务架构的概念:微服务架构是一种设计方法,它将应用程序分解成一组独立的、可协作的服务,每个服务对应一个具体的业务功能。这些服务可以独立部署、扩展和维护,通常通过轻量级的通信机制(如HTTPRESTfulAPI)相互协作。微服务架构使得服务变得更加模块化,各服务之间相互独立,不受......
  • 前端入门系列-HTML-HTML结构
    ......
  • Java后端对 前端的学习了解 ,基础知识和各框架功能发展概述,以及了解前后端的分离史
    前端的框架太多,杂乱,后端只需要掌握简单的即可 (基础的和vue框架后面详细有笔记)一.前端三要素1.HTML(结构):超文本标记语言,决定网页的结构和内容(最基础)2.CSS(表现) :层叠样式表,设定页面的修饰,相当于化妆品3.JavaScript(行为):是一种弱类型的脚本语言,源代......
  • Golang vs Java: 一场编程语言的较量
    在IT行业飞速发展的过程中,编程语言扮演着至关重要的角色。作为开发人员,选择合适的编程语言对于构建高效、可靠和可维护的应用程序至关重要。在这场编程语言的较量中,Golang和Java无疑是两个备受青睐的选择。我们现在将对这两种语言进行全面对比,探讨它们在性能、简洁性、并发......
  • 如何查看java代码编写的soap请求报文头信息
    在浏览器中打开接口地址,点击浏览器中的插件查看接口点击具体方法之后可以看到请求报文头工具如下: ......