天天看點

Spring 14: SM架構(Spring + MyBatis)初步整合開發

作者:Java碼農之路

SM整合步驟

預期項目結構

Spring 14: SM架構(Spring + MyBatis)初步整合開發

建立資料庫和資料表

  • springuser.sql腳本如下
create database ssm;

use ssm;

create table users(
  userid int primary key,
  uname varchar(20),
  upass varchar(20)
);

create table accounts(
 aid  int primary key,
 aname varchar(20),
 acontent varchar(50)
);
           

建立項目

  • 建立maven項目
  • 選擇quickstart模闆
  • 修改項目目錄,删除自動生成的類和對應測試類

修改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.example</groupId>
  <artifactId>ch09-spring-sm</artifactId>
  <version>1.0.0</version>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <!-- 添加單元測試的依賴 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
    </dependency>

    <!-- 添加spring-context依賴 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.22</version>
    </dependency>

    <!-- 添加spring-aspects依賴 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>5.3.22</version>
    </dependency>

    <!-- 添加spring-tx依賴,用于事務管理 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.3.22</version>
    </dependency>

    <!-- 添加spring-jdbc依賴 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.3.22</version>
    </dependency>

    <!-- 添加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>

    <!-- 添加mybatis和spring的整合依賴-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.7</version>
    </dependency>

    <!-- 添加資料庫連接配接池 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.2.11</version>
    </dependency>
  </dependencies>

  <build>
    <!-- 添加資源檔案指定 -->
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
  </build>
</project>
           

添加模闆檔案

分别添加MyBatis相應配置檔案的模闆(SqlMapConfig.xml和XXXXMapper.xml檔案,友善以後使用)
  • 如何添加模闆檔案
Spring 14: SM架構(Spring + MyBatis)初步整合開發
  • SqlMapConfig.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="db.properties"></properties>
    
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    
    <typeAliases>
        <package name="com.example.pojo"></package>
    </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://ip:port/dataBaseName?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true"/>
                <property name="username" value="userName"/>
                <property name="password" value="passWord"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name=""></package>
    </mappers>
</configuration>
           
  • XXXXMapper.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>
           

jdbc.properties

  • 添加jdbc.properties檔案至src/main/resources目錄下
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://自己的伺服器ip或localhost:3306/要連接配接的資料庫名稱?useUnicode=true&characterEncoding=utf8
jdbc.username=XXXX
jdbc.password=YYYY
           

SqlMapConfig.xml

  • 添加SqlMapConfig.xml檔案至src/main/resources目錄下:選擇我們自己添加的模闆檔案(該狀态下idea無法電腦截圖,手機拍攝,包涵包涵)
Spring 14: SM架構(Spring + MyBatis)初步整合開發

Spring核心配置檔案

  • 由于分層開發,需要添加兩個配置檔案:applicationContext_mapper.xml和applicationContext_service.xml。添加操作見下
Spring 14: SM架構(Spring + MyBatis)初步整合開發
  • applicationContext_mapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 讀取資料庫連接配接檔案 jdbc.properties -->
    <context:property-placeholder location="jdbc.properties"/>

    <!-- 建立資料源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!-- 配置SqlSessionFactoryBean類 -->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 配置資料源 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 配置MyBatis的核心配置檔案 -->
        <property name="configLocation" value="SqlMapConfig.xml"/>
        <!-- 注冊實體類的别名 -->
        <property name="typeAliasesPackage" value="com.example.pojo"/>
    </bean>

    <!-- 注冊mapper.xml檔案 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.example.mapper"/>
    </bean>
</beans>
           
  • applicationContext_service.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 導入applicationContext_mapper.xml檔案-->
    <import resource="applicationContext_mapper.xml"/>

    <!-- sm架構是基于注解開發的,要添加包掃描 -->
    <context:component-scan base-package="com.example.service.impl"/>

    <!-- 添加事務處理,此時先不管-->
    
</beans>
           

添加實體類

  • 依據users資料表的字段,建立User實體類
package com.example.pojo;

public class User {
    private Integer userid;
    private String uname;
    private String upass;

    @Override
    public String toString() {
        return "User{" +
                "userid=" + userid +
                ", uname='" + uname + '\'' +
                ", upass='" + upass + '\'' +
                '}';
    }

    public Integer getUserid() {
        return userid;
    }

    public void setUserid(Integer userid) {
        this.userid = userid;
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public String getUpass() {
        return upass;
    }

    public void setUpass(String upass) {
        this.upass = upass;
    }

    public User(String uname, String upass) {
        this.uname = uname;
        this.upass = upass;
    }

    public User(Integer userid, String uname, String upass) {
        this.userid = userid;
        this.uname = uname;
        this.upass = upass;
    }

    public User() {
    }
}
           

資料通路層

  • 添加UserMapper接口
package com.example.mapper;


import com.example.pojo.User;

/**
 * 資料通路層的接口
 */
public interface UserMapper {
    int insert(User user);
}
           
  • 添加UserMapper.xml,先選擇我們自己添加的XXXMapper.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.example.mapper.UserMapper">

    <!--
        int insert(User user);

        private Integer userid;
        private String uname;
        private String upass;
    -->
    <insert id="insert" parameterType="user">
        insert into users values (#{userid}, #{uname}, #{upass})
    </insert>
</mapper>
           

業務邏輯層

  • 添加UserService接口
package com.example.service;

import com.example.pojo.User;

/**
 * 業務邏輯層接口
 */
public interface UserService {
    int insert(User user);
}
           
  • 添加UserServiceImpl實作類
package com.example.service.impl;

import com.example.mapper.UserMapper;
import com.example.pojo.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 業務實作類
 */
@Service
public class UserServiceImpl implements UserService {
    //業務邏輯層實作類持有資料通路層的接口類型的變量
    @Autowired
    UserMapper userMapper;

    @Override
    public int insert(User user) {
        return userMapper.insert(user);
    }
}
           

測試

package com.example.test;

import com.example.pojo.User;
import com.example.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestUserInsert {

    //測試使用者資訊導入
    @Test
    public void testUserInsert(){
        //建立Spring容器并啟動
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext_service.xml");
        //擷取業務邏輯實作類的對象
        UserService userService = (UserService) ac.getBean("userServiceImpl");
        //調用業務功能
        int num = userService.insert(new User(1, "王小涵", "hanzhanghan"));
        if(num == 1){
            System.out.println("使用者資訊導入成功!");
        }else{
            System.out.println("使用者資訊導入失敗!");
        }
    }
}
           

測試輸出

  • 控制台輸出
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@475835b1] was not registered for synchronization because synchronization is not active
Aug 28, 2022 10:31:31 AM com.alibaba.druid.support.logging.JakartaCommonsLoggingImpl info
INFO: {dataSource-1} inited
JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@4d4d8fcf] will not be managed by Spring
==>  Preparing: insert into users values (?, ?, ?)
==> Parameters: 1(Integer), 王小涵(String), hanzhanghan(String)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@475835b1]
使用者資訊導入成功!

Process finished with exit code 0
           
  • 資料表變化
Spring 14: SM架構(Spring + MyBatis)初步整合開發