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