当前位置: 首页 > 图灵资讯 > 技术篇> 面向接口的方式进行CRUD

面向接口的方式进行CRUD

来源:图灵教育
时间:2023-06-04 09:13:50

1.代码65-66main中com.powernode.mybatis.mapperCarMapper接口

package com.powernode.mybatis.mapper;import com.powernode.mybatis.pojo.Car;import java.util.List;CRUD///接口///面向接口   65// 一般使用mybatis,一般不叫XXXDao。一般都是XXXMaper。一般都是XXXMaper。public interface CarMapper { //CarDao。    /**     * 新增Car     * @param car     * @return     */    int insert(Car car);    /**     * Car按id删除     * @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.pojojavabeanCar

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

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对象放在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对象与当前线程的绑定关系。= null) {            sqlSession.close();            // 注意移除SqlSession对象与当前线程的绑定关系。            // 因为Tomcat服务器支持线程池。也就是说,用过的线程对象T1下次可能会用到这个T1线程。            local.remove();        }    }}

test中com.powernode.mybatisCarMapperTest

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///以面向接口的方式进行   66public 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.Driverjdbc.url=jdbc:mysql://localhost:3306/powernodejdbc.username=rootjdbc.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_sql

面向接口的方式进行CRUD_CRUD_02

面向接口的方式进行CRUD_CRUD_03

上一篇:

Bean的作用域

下一篇:

javassist动态生成类