java+SpringBoot+Mybatis+Mysql实现对数据库的增删改查


一、在pom.xml中导入依赖包

  1. pom.xml文件中添加依赖:

      在<dependencies></dependencies>中添加以下代码,引入jdbc、mybatis和mysql依赖包:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

   

Maven管理中点击Reload All Maven Projects,重新加载项目,点击clean清除项目缓存,再点击compile重新编译:

 

二、创建数据库表

数据库名:pre_test

数据库表:auto_test_date

字段:id,loginPhone,name,idCard,addTime

 

三、配置数据库连接信息

 springboot中默认的配置文件是application.properties,修改后缀名为application.yml,打开编辑配置信息:

 application.yml文件内容:

spring:
  datasource:
    url: jdbc:mysql://rm-2vcgyh64om3x3bd2beo.mysql.cn-chengdu.rds.aliyuncs.com:3306/pre_test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
    username: root
    password: pwd123456
    driver-class-name: com.mysql.cj.jdbc.Driver

  application:
    name: studb

server:
  port: 8080

mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.example.studb.entity
 

 

四、建立三层架构实现数据访问

  1、数据访问层

  结构如下:

 (1)AutoTestDateEntity类

package com.huaxi.entity;

import java.util.Date;

public class AutoTestDateEntity {
    private Long id;

    private String loginphone;

    private String name;

    private String idcard;

    private Date addtime;

    public Long getId() {
        return id;
    }

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

    public String getLoginphone() {
        return loginphone;
    }

    public void setLoginphone(String loginphone) {
        this.loginphone = loginphone == null ? null : loginphone.trim();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getIdcard() {
        return idcard;
    }

    public void setIdcard(String idcard) {
        this.idcard = idcard == null ? null : idcard.trim();
    }

    public Date getAddtime() {
        return addtime;
    }

    public void setAddtime(Date addtime) {
        this.addtime = addtime;
    }
}

(2)AutoTestDateMapper接口,dao层:

package com.huaxi.dao;

import com.huaxi.entity.AutoTestDateEntity;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface AutoTestDateMapper {
    /**
     * 插入一条数据
     * @param record
     * @return
     */
    int insert(AutoTestDateEntity record);

    /**
     * 查询对应name的数据信息
     * @param name
     * @return
     */
    AutoTestDateEntity queryAutuoTestDate(@Param("name") String name);

    /**
     * 更新对应name的电话号码loginPhone
     * @param loginPhone
     * @param name
     * @return
     */
    int updateDate(@Param("loginPhone") String loginPhone, @Param("name") String name);

    /**
     * 删除数据
     * @param name
     * @return
     */
    int deleteDate(@Param("name") String name);
}

(3)AutoTestDateMapper.xml

mapper的namespace指定了该xml文件指向的Mapper接口,里面的sql语句接受传来的name数据进行数据访问。

语句的id="queryAutuoTestDate"则是对应mapper接口中的方法,resultType="int"指定本次数据访问的数据返回类型。

<?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.huaxi.dao.AutoTestDateMapper">

  <!-- 通用查询映射结果 -->
  <resultMap id="BaseResultMap" type="com.huaxi.entity.AutoTestDateEntity">
    <result column="id" jdbcType="BIGINT" property="id" />
    <result column="loginPhone" jdbcType="VARCHAR" property="loginphone" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="idCard" jdbcType="VARCHAR" property="idcard" />
    <result column="addTime" jdbcType="TIMESTAMP" property="addtime" />
  </resultMap>

  <!-- 通用查询结果列 -->
  <sql id="Base_Column_List">
    id, loginPhone, name, idCard, addTime
  </sql>


  <!-- 插入一条数据 -->
  <insert id="insert" parameterType="com.huaxi.entity.AutoTestDateEntity">
    insert into auto_test_date (id, loginPhone, name, 
      idCard, addTime)
    values (#{id,jdbcType=BIGINT}, #{loginphone,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, 
      #{idcard,jdbcType=VARCHAR}, #{addtime,jdbcType=TIMESTAMP})
  </insert>

  <!-- 查询数据 -->
  <select id="queryAutuoTestDate" parameterType="java.lang.String" resultMap="BaseResultMap">
    SELECT
    <include refid="Base_Column_List"></include>
    FROM pre_test.auto_test_date
    WHERE name = #{name} limit 1
  </select>

  <!-- 更新数据 -->
  <update id="updateDate" parameterType="java.lang.String">
    UPDATE pre_test.auto_test_date
    SET loginPhone = #{loginPhone}
    WHERE name = #{name } limit 1
  </update>

  <!-- 删除数据 -->
  <delete id="deleteDate" parameterType="java.lang.String">
    DELETE
    FROM pre_test.auto_test_date
    WHERE name = #{name } ORDER BY id DESC limit 1
  </delete>

</mapper>

使用 Mapper 进行开发时,需要遵循以下规则:

  • mapper 映射文件中 namespace 必须与对应的 mapper 接口的完全限定名一致。
  • mapper 映射文件中 statement 的 id 必须与 mapper 接口中的方法的方法名一致
  • mapper 映射文件中 statement 的 parameterType 指定的类型必须与 mapper 接口中方法的参数类型一致。
  • mapper 映射文件中 statement 的 resultType 指定的类型必须与 mapper 接口中方法的返回值类型一致。

(4)在程序入口类中添加扫描:

@MapperScan("com.huaxi.dao")

完整的HuaxitestApplication代码:

package com.huaxi.huaxitest;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.ApplicationPidFileWriter;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.ImportResource;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@ServletComponentScan
@ImportResource(locations = {"classpath*:applicationContext*.xml"})
@EnableScheduling
@MapperScan("com.huaxi.dao")
public class HuaxitestApplication {
    
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder){
        return builder.sources(HuaxitestApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication springApplication = new SpringApplication(HuaxitestApplication.class);
        springApplication.addListeners(new ApplicationPidFileWriter());
        springApplication.run(args);
    }

}

(5)测试用例

通过@Autowired注解获得自动注入的DAO层Mapper的实现类,在test中直接调用,进行数据的增删改查

package com.huaxi.huaxitest;

import com.huaxi.base.BaseTest; import com.huaxi.dao.AutoTestDateMapper; import com.huaxi.entity.AutoTestDateEntity; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.Date; @Slf4j public class TestSQLData extends BaseTest { @Autowired AutoTestDateMapper autoTestDateMapper; @Test public void test001() throws Exception{ /**插入数据**/ AutoTestDateEntity autoTestDateEntity = new AutoTestDateEntity(); autoTestDateEntity.setId(new Long(2)); autoTestDateEntity.setLoginphone("18683571234"); autoTestDateEntity.setName("张三"); autoTestDateEntity.setIdcard("522199908086633"); autoTestDateEntity.setAddtime(new Date()); autoTestDateMapper.insert(autoTestDateEntity); } @Test public void test002() throws Exception{ /**更新数据**/ autoTestDateMapper.updateDate("18612341234","张三"); /**查询数据**/ AutoTestDateEntity sql =autoTestDateMapper.queryAutuoTestDate("张三"); log.info("打印结果:" + sql.getLoginphone() + sql.getName()); } }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM