首页 > 其他分享 >面向接口的方式进行CRUD

面向接口的方式进行CRUD

时间:2023-06-03 13:32:43浏览次数:37  
标签:String car CRUD 接口 public sqlSession 面向 Car id

1. 代码   65-66 

main中com.powernode.mybatis.mapper

接口CarMapper

package com.powernode.mybatis.mapper;

import com.powernode.mybatis.pojo.Car;

import java.util.List;

//接口
//面向接口的方式进行CRUD   65
// 一般使用mybatis的话,一般不叫做XXXDao了。一般都是XXXMapper。
public interface CarMapper { //CarDao。

    /**
     * 新增Car
     * @param car
     * @return
     */
    int insert(Car car);

    /**
     * 根据id删除Car
     * @param id
     * @return
     */
    int deleteById(Long id);

    /**
     * 修改汽车信息
     * @param car
     * @return
     */
    int update(Car car);

    /**
     * 根据id查询汽车信息
     * @param id
     * @return
     */
    Car selectById(Long id);

    /**
     * 获取所有的汽车信息。
     * @return
     */
    List selectAll();

}

com.powernode.mybatis.pojo

javabean    Car

package com.powernode.mybatis.pojo;

/**
 * 封装汽车相关信息的pojo类。普通的java类。   65
 */
public class Car {
    // 数据库表当中的字段应该和pojo类的属性一一对应。
    // 建议使用包装类,这样可以防止null的问题。
    private Long id;
    private String carNum;
    private String brand;
    private Double guidePrice;
    private String produceTime;
    private String carType;

    @Override
    public String toString() {
        return "Car{" +
                "id=" + id +
                ", carNum='" + carNum + '\'' +
                ", brand='" + brand + '\'' +
                ", guidePrice=" + guidePrice +
                ", produceTime='" + produceTime + '\'' +
                ", carType='" + carType + '\'' +
                '}';
    }

    public Long getId() {
        return id;
    }

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

    public String getCarNum() {
        return carNum;
    }

    /*public String getXyz() {
        return carNum;
    }*/

    public void setCarNum(String carNum) {
        this.carNum = carNum;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public Double getGuidePrice() {
        return guidePrice;
    }

    public void setGuidePrice(Double guidePrice) {
        this.guidePrice = guidePrice;
    }

    public String getProduceTime() {
        return produceTime;
    }

    public void setProduceTime(String produceTime) {
        this.produceTime = produceTime;
    }

    public String getCarType() {
        return carType;
    }

    public void setCarType(String carType) {
        this.carType = carType;
    }

    public Car(Long id, String carNum, String brand, Double guidePrice, String produceTime, String carType) {
        this.id = id;
        this.carNum = carNum;
        this.brand = brand;
        this.guidePrice = guidePrice;
        this.produceTime = produceTime;
        this.carType = carType;
    }

    public Car() {
    }
}

com.powernode.mybatis.utils

工具类SqlSessionUtil

package com.powernode.mybatis.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;

/**
 * MyBatis工具类
 */
public class SqlSessionUtil {

    private SqlSessionUtil(){}

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 全局的,服务器级别的,一个服务器当中定义一个即可。
    // 为什么把SqlSession对象放到ThreadLocal当中呢?为了保证一个线程对应一个SqlSession。
    private static ThreadLocal local = new ThreadLocal<>();

    /**
     * 获取会话对象。
     * @return 会话对象
     */
    public static SqlSession openSession(){
        SqlSession sqlSession = local.get();
        if (sqlSession == null) {
            sqlSession = sqlSessionFactory.openSession();
            // 将sqlSession对象绑定到当前线程上。
            local.set(sqlSession);
        }
        return sqlSession;
    }

    /**
     * 关闭SqlSession对象(从当前线程中移除SqlSession对象。)
     * @param sqlSession
     */
    public static void close(SqlSession sqlSession){
        if (sqlSession != null) {
            sqlSession.close();
            // 注意移除SqlSession对象和当前线程的绑定关系。
            // 因为Tomcat服务器支持线程池。也就是说:用过的线程对象t1,可能下一次还会使用这个t1线程。
            local.remove();
        }
    }

}

test中com.powernode.mybatis

CarMapperTest

package com.powernode.mybatis;

import com.powernode.mybatis.mapper.CarMapper;
import com.powernode.mybatis.utils.SqlSessionUtil;
import com.powernode.mybatis.pojo.Car;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;


//面向接口的方式进行CRUD   66
public class CarMapperTest {
    @Test
    public void testInsert(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        // 面向接口获取接口的代理对象
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        Car car = new Car(null, "4444", "奔驰C200", 32.0, "2000-10-10", "新能源");
        int count = mapper.insert(car);
        System.out.println(count);
        sqlSession.commit();
    }
    @Test
    public void testDeleteById(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        int count = mapper.deleteById(39L);
        System.out.println(count);
        sqlSession.commit();
    }
    @Test
    public void testUpdate(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        Car car = new Car(12L, "2222", "凯美瑞222", 3.0, "2000-10-10", "新能源");
        mapper.update(car);
        sqlSession.commit();
    }
    @Test
    public void testSelectById(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        Car car = mapper.selectById(38L);
        System.out.println(car);
    }
    @Test
    public void testSelectAll(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        List cars = mapper.selectAll();
        cars.forEach(car -> System.out.println(car));
    }
}

CarMapper.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="com.powernode.mybatis.mapper.CarMapper">

    <insert id="insert">
        insert into t_car values(null, #{carNum},#{brand},#{guidePrice},#{produceTime},#{carType})
    </insert>
    <delete id="deleteById">
        delete from t_car where id = #{id}
    </delete>
    <update id="update">
        update t_car set
        car_num=#{carNum},brand=#{brand},guide_price=#{guidePrice},produce_time=#{produceTime},car_type=#{carType}
        where id = #{id}
    </update>
    <select id="selectById" resultType="com.powernode.mybatis.pojo.Car">
        select
            id,
            car_num as carNum,
            brand,
            guide_price as guidePrice,
            produce_time as produceTime,
            car_type as carType
        from t_car where id = #{id}
    </select>
    <select id="selectAll" resultType="com.powernode.mybatis.pojo.Car">
        select
            id,
            car_num as carNum,
            brand,
            guide_price as guidePrice,
            produce_time as produceTime,
            car_type as carType
        from t_car
    </select>

</mapper>

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>
    <properties resource="jdbc.properties" />
    <environments default="powernodeDB">
        <environment id="powernodeDB">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="CarMapper.xml"/>
    </mappers>
</configuration>

logback.xml

<?xml version="1.0" encoding="UTF-8"?>

<configuration debug="false">
    <!-- 控制台输出 -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
            <pattern>[%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
    </appender>

    <!--mybatis log configure-->
    <logger name="com.apache.ibatis" level="TRACE"/>
    <logger name="java.sql.Connection" level="DEBUG"/>
    <logger name="java.sql.Statement" level="DEBUG"/>
    <logger name="java.sql.PreparedStatement" level="DEBUG"/>

    <!-- 日志输出级别,logback日志级别包括五个:TRACE < DEBUG < INFO < WARN < ERROR -->
    <root level="DEBUG">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="FILE"/>
    </root>

</configuration>

jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/powernode
jdbc.username=root
jdbc.password=lzl

pom.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.powernode</groupId>
    <artifactId>course12</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>jar</packaging>

    <dependencies>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.10</version>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.30</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <!--logback-->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.11</version>
        </dependency>
    </dependencies>

    <properties>
        <!--    编译代码使用的jdk版本-->
        <maven.compiler.source>1.8</maven.compiler.source>
        <!--    运行程序使用的jdk版本-->
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

</project>

面向接口的方式进行CRUD_getMapper方法

面向接口的方式进行CRUD_sql_02

面向接口的方式进行CRUD_CRUD_03

标签:String,car,CRUD,接口,public,sqlSession,面向,Car,id
From: https://blog.51cto.com/u_15784725/6407832

相关文章

  • 一个多功能(聚合)查询接口,实现模糊、分页、主键、排序以及多条件查询
    一个多功能(聚合)查询接口,实现模糊、分页、主键、排序以及多条件查询前言写的啰嗦了点,看效果请直接忽略中间,直接看后半部分。引个流,公众号:小简聊开发概念瞎编的名字,哈哈哈,我就勉强称之为聚合查询吧,不知道概念符不符合。大家好,我是小简,很久没写文章了,确实是太忙了,今天我......
  • 接口并发解决方案
    设定一个场景,假如一个商品接口在某段时间突然上升,会怎么办?生活中的例子来说,假设冰墩墩在当天晚上上热搜之后,迅速有十几万人去淘宝下单购买,此时并没有做好对该商品的缓存预热以及准备,如何操作?对于这个问题,在电商高并发系统中,对接口的保护一般采用:缓存、限流、降级来操作。假设该接......
  • 5.24 面向对象案例分析六
    classBook{//类的名称要以class开头,否则报错,并且提示不到这行代码!!!privateintbid;privateStringtitle;privatedoubleprice;privatestaticintcount=0;publicBook(Stringtitle,doubleprice){count++;this.bid=count;......
  • 接口基础
    服务器地址-接口地址api.keyou.site:8000/configures接口分类1、硬件接口:指的是两个硬件设备之间的连接方式(比如:鼠标和电脑通过usb接口进行连接)2、软件接口:简单来说就说软件程序之间数据交互的通道软件接口分类:1、程序内部接口:是客户端与服务器的接口,用来实现客户端和服务......
  • 5.23 面向对象案例分析五
    用static,引入计数器案例classUser{privateStringuid;privateStringpassword;privatestaticintcount=0;publicUser(){this("NOID","mldn");}publicUser(Stringuid){this(uid,"mldnjava&q......
  • 5.21 面向对象案例分析三
    狗的一个类,包括名字,颜色,年龄;典型的java类的一段代码classDog{privateStringname;privateStringcolor;privateintage;publicDog(){}publicDog(Stringname,Stringcolor,intage){this.name=name;this.color=color;......
  • 5.20 面向对象案例分析二
    classEmployee{privatelongempno;privateStringename;privatedoublesalary;privatedoublerate;publicEmployee(){}publicEmployee(longempno,Stringename,doublesalary,doublerate){this.empno=empno;this......
  • 5.19 面向对象案例分析一
    classAddress{privateStringcountry;privateStringprovince;privateStringcity;privateStringstreet;privateStringzipcode;publicAddress(){}publicAddress(Stringcountry,Stringprovince,Stringcity,Stringstr......
  • C++面向对象
    文章目录C++类&对象C++类定义定义C++对象访问数据成员类&对象\详解类成员函数类访问修饰符构造函数&析构函数C++拷贝构造函数C++友元函数C++内联函数C++中的this指针C++中指向类的指针C++类的静态成员继承基类&派生类访问控制和集成继承类型多继承继承顺序重载运算符和重载函数C++......
  • 存储接口测试简介与测试方法
    本文分享自天翼云开发者社区《存储接口测试简介与测试方法》,作者:杨****鹏 1、接口测试的概念接口测试原理是通过测试程序模拟客户端向服务器发送请求报文,服务端接收报文并处理后再把应答报文发送回客户端,客户端接收应答报文的过程测试接口目的就是保证接口调用的正确性和稳......