首页 > 其他分享 >mybatis入门案例

mybatis入门案例

时间:2022-12-14 10:24:40浏览次数:53  
标签:username map 入门 put 案例 mybatis import public String

创建模块,导入坐标:

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <!--mybatis 依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
        <!--mysql 驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <!--junit 单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
        <!-- 添加slf4j日志api -->
        <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>

编写 MyBatis 核心配置文件 :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>
    <typeAliases>
        <package name="com.po.domain"/>
    </typeAliases>
    <!--environments:配置数据库连接环境信息。可以配置多个environment,通过default属性切换不同的environment-->
    <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://127.0.0.1:3306/mybatis?useSSL=false&allowPublicKeyRetrieval=true"/>
                <property name="username" value="root"/>
                <property name="password" value="wang0516"/>
            </dataSource>
        </environment>

        <environment id="test">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!--数据库连接信息-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=false&allowPublicKeyRetrieval=true"/>
                <property name="username" value="root"/>
                <property name="password" value="wang0516"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--加载sql映射文件-->
        <!-- <mapper resource="com/po/mapper/UserMapper.xml"/>-->
        <!--Mapper代理方式-->
        <package name="com.po.mapper"/>
    </mappers>
</configuration>

编写 SQL 映射文件 

<?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">
<!--namespace:名称空间-->
<mapper namespace="com.po.mapper.UserMapper">
    <!--statement-->
    <select id="selectAll" resultType="user">
        select *
        from tb_user;
    </select>
    <!--    <select id="selectById" resultType="user">
            select *
            from tb_user where id = #{id};
        </select>-->
    <select id="select" resultType="user">
        select *
        from tb_user
        where
            username = #{username}
          and password = #{param2}
    </select>
    
</mapper>

定义POJO类

package com.po.domain;


// alt + 鼠标左键 整列编辑
public class User {

    private Integer id;
    private String username;
    private String password;
    private String gender;
    private String addr;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", gender='" + gender + '\'' +
                ", addr='" + addr + '\'' +
                '}';
    }
}

usermapper

package com.po.mapper;

import com.itheima.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

public interface UserMapper {

    List<User> selectAll();

    @Select("select * from tb_user where id  = #{id}")
    User selectById(int id);

    /*

      MyBatis 参数封装:
        * 单个参数:
            1. POJO类型:直接使用,属性名 和 参数占位符名称 一致
            2. Map集合:直接使用,键名 和 参数占位符名称 一致
            3. Collection:封装为Map集合,可以使用@Param注解,替换Map集合中默认的arg键名
                map.put("arg0",collection集合);
                map.put("collection",collection集合);
            4. List:封装为Map集合,可以使用@Param注解,替换Map集合中默认的arg键名
                map.put("arg0",list集合);
                map.put("collection",list集合);
                map.put("list",list集合);
            5. Array:封装为Map集合,可以使用@Param注解,替换Map集合中默认的arg键名
                map.put("arg0",数组);
                map.put("array",数组);
            6. 其他类型:直接使用
        * 多个参数:封装为Map集合,可以使用@Param注解,替换Map集合中默认的arg键名
            map.put("arg0",参数值1)
            map.put("param1",参数值1)
            map.put("param2",参数值2)
            map.put("agr1",参数值2)
            ---------------@Param("username")
            map.put("username",参数值1)
            map.put("param1",参数值1)
            map.put("param2",参数值2)
            map.put("agr1",参数值2)

     */
    User select(@Param("username") String username,String password);
    User select(Collection collection);
}

加载核心配置文件,获取 SqlSessionFactory 对象

package com.po;

import com.po.domain.User;
import com.po.mapper.UserMapper;
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.IOException;
import java.io.InputStream;
import java.util.List;

public class MyBatisDemo {
    public static void main(String[] args) throws IOException {

       /* //1. 加载mybatis的核心配置文件,获取 SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2. 获取SqlSession对象,用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3. 执行sql
        List<User> users = sqlSession.selectList("test.selectAll");
        System.out.println(users);
        //4. 释放资源
        sqlSession.close();*/
        //1. 获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2. 获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //3. 获取Mapper接口的代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        //4. 执行方法
        List<User> user = userMapper.selectAll();
        System.out.println(user);

        //5. 释放资源
        sqlSession.close();

    }
}

[User{id=1, username='zhangsan', password='123', gender='null', addr='null'}]

  

 

标签:username,map,入门,put,案例,mybatis,import,public,String
From: https://www.cnblogs.com/popopopopo/p/16981374.html

相关文章

  • mybatis简化代码
    创建模块,导入坐标:<properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></propert......
  • Proj4.js使用初步入门
    一、基础知识在正式使用Proj4.js时,我们首先需要了解下有关各种投影的参数定义(例如:椭球长半轴、扁率、原点纬线、中央经线、两条标准纬线、东偏移量、北偏移量和单位等),具......
  • Activity7学习入门(六)
    官网地址:https://activiti.gitbook.io/activiti-7-developers-guide/components/activiti-cloud-applicationActivitiCloudApplicationActiviti云应用是由Activiti云核......
  • 前端入门教程:CSS标准盒模型和怪异盒模型区别
    理解盒模型:CSS3中的盒模型有以下两种:标准盒模型、IE盒子模型(怪异盒模型),盒模型是由4个部分组成,由内向外分别是content(下图蓝色部分)、padding、border、margin盒模型有5......
  • html学习笔记五 安利网页案例
    将整个页面分为header、nav、banner、list、footer五大部分,下图1~3为网页的html结构部分,图4~7为网页的CSS样式表部分,图8和图9为网页实际效果......
  • Activity7入门学习(三)
    官网地址:https://activiti.gitbook.io/activiti-7-developers-guide/componentsComponentsActivitiCloud提供了一套基本的构建模块,可以分为3个单独的组:.ActivitiClou......
  • Activity7入门学习(四)
    官网地址:https://activiti.gitbook.io/activiti-7-developers-guide/components/spring-cloud从Activiti框架的角度来看,我们依赖于SpringBoot/SpringCloud/SpringC......
  • Activity7入门学习(二)
    官网地址:https://activiti.gitbook.io/activiti-7-developers-guide/getting-started/getting-started-activiti-coreGettingStarted-ActivitiCoreGettingStartedw......
  • Spring Boot MyBatis 通用Mapper插件集成 good
    看本文之前,请确保你已经在SpringBoot中集成MyBatis,并能正常使用。如果没有,那么请先移步做了解后,再按本文步骤操作。使用MyBatis在我们通过xml集中配置SQL,并通过创建接口Mapp......
  • Spring boot Mybatis
    最近刚接触Springboot,正是因为他的及简配置方便开发,促使我下定决心要用它把之前写的项目重构,那么问题来了,springboot怎么整合mybatis呢,下面几个配置类来搞定。在我的代码......