06 mybatis </sql>

文章目录

products.sql

sql 复制代码
create table products
(
    product_id       int auto_increment comment '产品ID'
        primary key,
    product_name     varchar(100)   null comment '产品名称',
    brand            varchar(50)    null comment '品牌',
    price            decimal(10, 2) null comment '价格',
    color            varchar(20)    null comment '颜色',
    storage_capacity varchar(10)    null comment '存储容量',
    description      text           null comment '描述'
)
    comment '手机产品表';

pom.xml

xml 复制代码
<?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>com.aistat</groupId>
    <artifactId>mybatis_tech</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--打包类型-->
    <packaging>jar</packaging>

    <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>

<!--        MySQL驱动-->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>8.0.31</version>
        </dependency>

<!--        mybatis依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.15</version>
        </dependency>

        <!--测试环境-->

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.14.8</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

</project>

mybatis-config.xml

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="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <typeAliases>
        <package name="com.aistart.tech.pojo"/>
    </typeAliases>

<!--    <typeAliases>-->
<!--        <typeAlias alias="Products" type="com.aistart.tech.pojo.Products"/>-->

<!--    </typeAliases>-->
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatisdb"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
                <property name="poolMaximumActiveConnections" value="1"/>
            </dataSource>
        </environment>

        <environment id="testdevelopment">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/ProductsMapper.xml"></mapper>
    </mappers>
</configuration>

ProductsMapper.xml

xml 复制代码
<?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="mapper.ProductsMapper">
    
    <sql id="all">
        product_id, product_name, brand, price, color, storage_capacity, description
    </sql>

    <sql id="select">
        select <include refid="all"></include> from products
        where
    </sql>

    <!--id作为这个sql的唯一id,调用也是通过它-->
    <insert id="insertOne" parameterType="Products">
        insert into products (product_name,color,price)
        values (#{productName},#{color},#{price})
    </insert>

    <delete id="deleteOneById">
        delete from products where product_id = #{askdksad}
    </delete>

    <update id="updateProductName" parameterType="Products">
        update products set product_name = #{productName} where product_id = #{productId}
    </update>

    <select id="selectOneById" parameterType="int" resultType="com.aistart.tech.pojo.Products">

/*
参数名一个时虽然可以随便写,但是不推荐

*/
        select 
            <include refid="all"></include>
        from products where product_id = #{productId}

/*默认调用了get函数,利用反射,根据get+param()的形式找函数并且执行*/

    </select>


    <!--

    JDBC>>>>sql>>>>resultSet>>>获取列并遍历>>>>>>

    -->
    <select id="selectAll" resultType="com.aistart.tech.pojo.Products">
        select 
            <include refid="all"></include>
        from products
    </select>

    <select id="selectOneBynName" resultType="Products">
        <include refid="select"></include>
        product_name = #{name}
    </select>
</mapper>

ProductsMapperImpl.java

java 复制代码
package com.aistart.tech.mapper.impl;

import com.aistart.tech.mapper.ProductsMapper;
import com.aistart.tech.pojo.Products;
import com.aistart.tech.utils.DButil;
import org.apache.ibatis.session.SqlSession;


public class ProductsMapperImpl implements ProductsMapper {
    @Override
    public int insertOne(String name) {

        SqlSession sqlSession = DButil.getSqlSession();

        Products products = new Products();
//
//        products.setProductName(name);
//        products.setColor("黑色");
//        products.setPrice(19999.99);

        int rows = sqlSession.insert("insertOne",products );

        sqlSession.commit();

        //关闭掉
        sqlSession.close();

        return rows;
    }

    @Override
    public Products selectOneById(int id) {

        SqlSession sqlSession = DButil.getSqlSession();

        Products one =(Products) sqlSession.selectOne("selectOneById", id);

        sqlSession.close();

        return one;
    }
}

Products.java

java 复制代码
package com.aistart.tech.pojo;


import lombok.*;


@Data
@AllArgsConstructor
@NoArgsConstructor
public class Products {
  private Integer productId;
  private String productName;
  private String brand;
  private Double price;
  private String color;
  private String storageCapacity;
  private String description;

}

DButil.java

java 复制代码
package com.aistart.tech.utils;

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;


public class DButil {

    private static SqlSessionFactory sqlSessionFactory = null;
    //测试环境下的工厂
    private static SqlSessionFactory sqlSessionFactoryTest = null;

    static {
        //1.builder  一旦创建了 SqlSessionFactory,就不再需要它了
//        SqlSessionFactoryBuilder sqlSessionFactoryBuilder =

        //2.获取工厂

        // 获取资源 org.apache.ibatis.io.Resources;
        try {

            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            //根据资源文件创建工厂
            sqlSessionFactory  = new SqlSessionFactoryBuilder().build(inputStream);

            //测试环境的创建工厂
//            sqlSessionFactoryTest  = new SqlSessionFactoryBuilder().build(inputStream,"testdevelopment");

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    public static SqlSession getSqlSession(){

        //获得Sqlsession
        return sqlSessionFactory.openSession();

    }

    public static void close(SqlSession session){

        session.close();

    }


}

ProductsMapperImplTest.java

java 复制代码
package com.aistart.tech.mapper.impl;

import com.aistart.tech.mapper.ProductsMapper;
import com.aistart.tech.pojo.Products;
import org.junit.Test;


public class ProductsMapperImplTest {

    ProductsMapper mapper = new ProductsMapperImpl();

    @Test
    public void test(){
        Products products = mapper.selectOneById(1);

        System.out.println(products);


    }
}

MapperTest.java

java 复制代码
import com.aistart.tech.pojo.Products;
import com.aistart.tech.utils.DButil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.HashMap;
import java.util.List;


public class MapperTest {

    @Test
    public void selectAllTest(){
        SqlSession sqlSession = DButil.getSqlSession();


        /*
         查取多个时,调用的是selectAll,必须使用selectList函数
         查取单个时,调用的是selectOne,必须使用selectOne函数
        */
        List<Products> list = sqlSession.selectOne("mapper.ProductsMapper.selectAll");

        //默认通过反射直接向属性放值
        for (Products o : list) {
            System.out.println(o);
        }

    }

    @Test
    public void deleteTest(){

        try(SqlSession sqlSession = DButil.getSqlSession()){

            HashMap<String, Object> map = new HashMap<>();


            map.put("productName","小米");
            map.put("price",1999.9);
            int rows = sqlSession.insert("insertOne", map);

            sqlSession.commit();
            System.out.println(rows);
        }catch (Exception e){

        }




    }

    @Test
    public void insertTest(){

        SqlSession sqlSession = DButil.getSqlSession();

        Products products = new Products();

        products.setProductName("getterTest");
        //默认调用的时get()函数,

        sqlSession.insert("insertOne",products);

        sqlSession.commit();
    }

    @Test
    public void updateTest(){
        SqlSession sqlSession = DButil.getSqlSession();

        Products products = new Products();

        products.setProductId(17);
        products.setProductName("updateTest");

        sqlSession.update("mapper.ProductsMapper.updateProductName",products);

        sqlSession.commit();
    }

    @Test
    public void selectOneBynNameTest(){
        SqlSession sqlSession = DButil.getSqlSession();
        Object o = sqlSession.selectOne("selectOneBynName", "小米");


    }
}
相关推荐
小桥流水人家jjh3 小时前
Mybatis执行自定义SQL并使用PageHelper进行分页
java·数据库·spring boot·sql·mybatis
黑马师兄3 小时前
Mybatis
java·mybatis
Neoest1 天前
场景解决之mybatis当中resultType= map时,因某个字段为null导致返回的map的key不存在怎么处理
mybatis
ZWZhangYu1 天前
【MyBatis源码】深入分析TypeHandler原理和源码
数据库·oracle·mybatis
小鸡脚来咯2 天前
springboot 整合mybatis
java·spring boot·mybatis
种树人202408192 天前
MyBatis xml 文件中 SQL 语句的小于号未转义导致报错
mybatis
码农派大星。2 天前
MyBatis操作--进阶
mybatis
爱读源码的大都督2 天前
MyBatis中的LanguageDriver的作用是什么
java·spring boot·mybatis
鹿屿二向箔2 天前
基于SSM(Spring + Spring MVC + MyBatis)框架的快递管理系统
spring·mvc·mybatis
2的n次方_2 天前
MyBatis——增删查改(XML 方式)
xml·数据库·mybatis