首页 > 其他分享 >mybatis入门

mybatis入门

时间:2024-07-20 22:07:10浏览次数:17  
标签:入门 brand private sqlSession mybatis import tb String

mybatis入门

官网https://mybatis.org/mybatis-3/zh_CN/getting-started.html

1. 入门案例

image-20240605191353109

1.1 创建user表,添加数据

create database mybatis;
use mybatis;

alter database mybatis charset utf8mb4; 
# 注意:不设置可能会出现报错 “ Incorrect string value: ‘\xE7\x94\xB7‘ for 	column ‘xx‘ at row x”									
drop table if exists tb_user;

create table tb_user(
                        id int primary key auto_increment,
                        username varchar(20),
                        password varchar(20),
                        gender char(1),
                        addr varchar(30)
);

INSERT INTO tb_user VALUES (1, 'zhangsan', '123', '男', '北京');
INSERT INTO tb_user VALUES (2, '李四', '234', '女', '天津');
INSERT INTO tb_user VALUES (3, '王五', '11', '男', '西安');

select * from tb_user;

1.2 创建模块,导入坐标

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>mybatis-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.20</version>
        </dependency>
        <!-- 添加logback-classic依赖 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!-- 添加logback-core依赖 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.2.3</version>
        </dependency>

    </dependencies>

</project>

1.3 编写mybatis核心配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="userMapper.xml"/>
    </mappers>
</configuration>

1.4 编写sql映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test">
    <select id="selectAll" resultType="com.itheima.pojo.User">
        select * from tb_user
    </select>
</mapper>

1.5 编码

package com.itheima.pojo;

public class User {
    private Integer id;
    private String username;
    private String password;
    private String gender;
    private String addr;
  // get set 方法
}
package com.itheima;

import com.itheima.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;

public class MybatisDemo {
    public static void main(String[] args) throws Exception {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        List<User> users = sqlSession.selectList("test.selectAll");

        System.out.println(users);

        users.forEach(System.out::println);

        sqlSession.close();
    }
}

2. Mapper代理开发

image-20240605205817415

image-20240605205919048

2.1 步骤1

image-20240605210541559

注意:创建resources的目录,通过com/itheima/mapper创建多级目录

2.2 步骤2

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.itheima.mapper.UserMapper"> # namespace为接口的全限定类名
    <select id="selectAll" resultType="com.itheima.pojo.User">
        select * from tb_user
    </select>
</mapper>

2.3 步骤3

image-20240605211155312

image-20240605211425734

    <mappers>
   <!-- <mapper resource="com/itheima/mapper/userMapper.xml"/>-->
        <package name="com.itheima.mapper"/> 统一扫描多个mapper.xml配置文件
    </mappers

2.4 步骤4

//        List<User> users = sqlSession.selectList("test.selectAll");
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = userMapper.selectAll();

3. 核心配置文件

3.1 typeAliases

image-20240605212842654

4. 案例

image-20240605213412242

image-20240605213439070

4.1 准备工作

4.1 数据表

-- 删除tb_brand表
drop table if exists tb_brand;
-- 创建tb_brand表
create table tb_brand
(
    -- id 主键
    id           int primary key auto_increment,
    -- 品牌名称
    brand_name   varchar(20),
    -- 企业名称
    company_name varchar(20),
    -- 排序字段
    ordered      int,
    -- 描述信息
    description  varchar(100),
    -- 状态:0:禁用  1:启用
    status       int
);
-- 添加数据
insert into tb_brand (brand_name, company_name, ordered, description, status)
values ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
       ('华为', '华为技术有限公司', 100, '华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1);

SELECT * FROM tb_brand;

4.2 实体类

public class Brand {
    // id 主键
    private Integer id;
    // 品牌名称
    private String brandName;
    // 企业名称
    private String companyName;
    // 排序字段
    private Integer ordered;
    // 描述信息
    private String description;
    // 状态:0:禁用  1:启用
    private Integer status;
    
    // get set 方法
}

4.3 测试用例

image-20240605215054151

4.4 mybatisX插件

image-20240605215135873

4.2 查询所有数据

image-20240605220237745

import com.itheima.pojo.Brand;

import java.util.List;

public interface BrandMapper {
    List<Brand> selectAll();
}

<?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.itheima.mapper.BrandMapper">
    <resultMap id="brandResultMap" type="brand">
        <result column="brand_name" property="brandName" />
        <result column="company_name" property="companyName" />
    </resultMap>

    <select id="selectAll" resultMap="brandResultMap">
        select *
        from tb_brand;
    </select>
</mapper>
package com.itheima.pojo;

import lombok.Data;

@Data
public class Brand {
    // id 主键
    private Integer id;
    // 品牌名称
    private String brandName;
    // 企业名称
    private String companyName;
    // 排序字段
    private Integer ordered;
    // 描述信息
    private String description;
    // 状态:0:禁用  1:启用
    private Integer status;
}
package com.itheima.test;

import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MybatisTest {

    @Test
    public void testSelectAll() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        List<Brand> brands = brandMapper.selectAll();

        brands.forEach(System.out::println);

        sqlSession.close();
    }
}

4.3 查询某条数据

public interface BrandMapper {
    Brand selectById(int id);
}
<?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.itheima.mapper.BrandMapper">
    <resultMap id="brandResultMap" type="brand">
        <result column="brand_name" property="brandName"/>
        <result column="company_name" property="companyName"/>
    </resultMap>
	
    # parameterType="int" 可以省略
    <select id="selectById" parameterType="int" resultMap="brandResultMap">
        select * from tb_brand where id = #{id};
    </select>
</mapper>
    @Test
    public void testSelectById() throws IOException {
        int id = 2;
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        Brand brand = brandMapper.selectById(id);
        System.out.println(brand);

        sqlSession.close();
    }

4.4 条件查询

注意:数据库连接建议设置成utf-8编码,否则查询中文时容易查不出结果

<property name="url" value="jdbc:mysql:///mybatis?characterEncoding=UTF-8&amp;useSSL=false"/>
public interface BrandMapper {
    List<Brand> selectByCondition(@Param("status") int status, @Param("companyName") String companyName);
}
<select id="selectByCondition" resultMap="brandResultMap">
        select * from tb_brand
        <where>
            <if test="status != null">
                and status = #{status}
            </if>
            <if test="companyName != null ">
                and company_name like #{companyName}
            </if>
            <if test="brandName != null and brandName != '' ">
                and brand_name like #{brandName}
            </if>
        </where>
</select>
   public void testSelectByCondition() throws IOException {
        int status = 1;
        String companyName = "华为";
        String brandName = "华为";
        companyName = "%" + companyName + "%";
        brandName = "%" + brandName + "%";

        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        List<Brand> brands = brandMapper.selectByCondition(status, companyName, brandName);
        brands.forEach(System.out::println);
        sqlSession.close();
    }

4.5 添加数据

public interface BrandMapper {
    void add(Brand brand);
}
<insert id="add">
    insert into tb_brand (brand_name, company_name, ordered, description, status)
    values (#{brandName},#{companyName},#{ordered},#{description},#{status});
</insert>
   @Test
    public void testAdd() throws IOException {
        int status = 1;
        String companyName = "波导手机";
        String brandName = "波导";
        String description = "手机中的战斗机";
        int ordered = 100;


        //封装对象
        Brand brand = new Brand();
        brand.setStatus(status);
        brand.setCompanyName(companyName);
        brand.setBrandName(brandName);
        brand.setDescription(description);
        brand.setOrdered(ordered);

        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true); //设置自动提交事务

        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        brandMapper.add(brand);
        // sqlSession.commit(); // 注意提交事务
        sqlSession.close();
    }

获取主键

<insert id="add" useGeneratedKeys="true" keyProperty="id">
    insert into tb_brand (brand_name, company_name, ordered, description, status)
    values (#{brandName},#{companyName},#{ordered},#{description},#{status});
</insert>
 SqlSession sqlSession = sqlSessionFactory.openSession(true);

BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
brandMapper.add(brand);
Integer id = brand.getId();
System.out.println(id);
//sqlSession.commit();
sqlSession.close();

标签:入门,brand,private,sqlSession,mybatis,import,tb,String
From: https://www.cnblogs.com/xinmomoyan/p/18313884

相关文章

  • SpringAOP的简单介绍及入门案例
    文章目录一、AOP介绍二、使用步骤(日志案例)1.创建模块,导入依赖2.创建实体类3.创建业务层接口和实现类4.创建日志类5.配置切面6.创建配置类7.单元测试三、通知类型1.四大通知2.环绕通知四、切点表达式1.execution2.@annotation五、记录日志详情一、AOP介绍AOP(......
  • Java入门知识
    Java特性和优势简单性面向对象可移植性高性能分布式动态性多线程安全性健壮性Java三大版本JavaSE:标准版(桌面程序,控制开发....)JavaME:嵌入式开发(手机,小家电....)JavaEE:E企业级开发(web端,服务器开发...)JDK、JRE、JVMJDK:JavaDevelopmentKitJRE:JavaRuntimeE......
  • Git入门
    初始化配置配置用户名gitconfig--globaluser.name"YourName"配置邮箱gitconfig--globaluser.email"[email protected]"存储配置(存储用户名邮箱)gitconfig--globalcredential.helperstore创建仓库创建一个新的本地仓库(省略project-name则在当前目录创建)g......
  • 万字长文|LLM大模型基础入门(非常详细)从入门到精通系列之:(三)Transformer 架构
    引言在本文中,我们将介绍并解释基于Transformer的大语言模型的每个步骤。当第一次接触Transformer架构时,我被可用于理解它的大量概念和教程所淹没。一些视频或文章假设了自然语言处理(NLP)概念的先验知识,而另一些则太长且难以理解。为了掌握Transformer架构,我不得不阅......
  • 入局大模型!(非常详细)从入门到精通,值得开发者好好看一看的 AI 入门法!(内附教程)
    今年招聘市场确实是好点了,我发现群友都在讨论,得赶快学点AI大模型。他们有的是想正式转到一些新兴的AI行业,需要系统的学习训练。更多的是想跟已有的技能结合,辅助编程提效,或上手实操应用,增加自己的职场竞争力。这也可以理解,ChatGPT推出仅一年半的时间,就将生成式AI推......
  • Spring boot + Mybatis 实现数据库的增删改查(CRUD)操作
    Springboot+Mybatis实现数据库的增删改查(CRUD)操作利用Springboot,我们可以快速构建Spring框架应用。利用Mybatis为Springboot提供的依赖,我们可以快捷地连接到MySQL,实现web项目对数据库的CRUD操作。一、创建项目在IDEA中新建maven项目,并在pom.xml......
  • OpenAI入门指南 aidoczh.com 上线OpenAI Cookbook中文版
    文章目录1、网址地址(1)中文地址(2)官网地址2、OpenAICookbook介绍3、内容导航1、网址地址(1)中文地址openai-cookbook中文网址http://www.aidoczh.com/docs/openai_cookbook/openai-cookbook中文项目已经放在github上https://github.com/aidoczh/openai-cookbook-z......
  • Pandas-入门
    PandasPandas1.1Series1.1.1常用属性1.1.2常用方法2.1DataFrame2.1.1基础属性基本函数2.1.2索引相关操作2.1.3修改行名和列索引值2.1.4添加列2.1.5删除列3.1导入导出数据Pandas"""PandasDataFrame:可以把DataFrame看作由Series对象组成的字......
  • kettle从入门到精通 第七十九课 ETL之kettle kettle读取数据库BLOB字段转换为文件
     上一课我们讲解了如何将文件以二进制流的方式写入数据库,本节课我们一起学习下如何将二进制数据读取为文件。 1、将二进制流转换为文件这里主要用到了步骤【文本文件输出】。表输入步骤从表中读取blob字段,java代码定义二进制流转换为文件的全路径,文本文件输出步骤根据全路径和......
  • kettle从入门到精通 第七十八课 ETL之kettle kettle将文件写入数据库BLOB字段
    前些日子一个小伙伴私聊我咨询如何将数据库中的BLOB字段读取为文件。帮他顺利读取文件之后我在想kettle肯定支持将文件写入数据库BLOB字段。今天先来一起学习下如何将文件以二进制流的方式写进数据库。 1、创建数据表,脚本如下:CREATETABLE`file`(`id`bigintNOTNULLA......