【WEEK3】 【DAY5】Basic Environment Setup for Integrating SSM Framework—Part One 【English Version】

This Part: Basic Environment Setup for Integrating SSM Framework—Part One (MyBatis Layer Implementation)
Next Part: Basic Environment Setup for Integrating SSM Framework—Part Two (Spring Layer and Spring MVC Layer Implementation)

2024.3.15 Friday

7. Integrating SSM Framework

7.1. Environment Requirements

7.1.1. Required Environment

The environment I’m going to use:

  • IDEA 2022
  • MySQL 5.5
  • Tomcat 8.5.99
  • Maven (not quite sure where to look for this…)

Environment used in the tutorial being followed:
Insert image description here

7.1.2. Prerequisites

Must be proficient in MySQL database, Spring, JavaWeb, and MyBatis knowledge, with basic frontend understanding.

7.2. Database Environment

7.2.1. Create a Database Table for Storing Book Data

CREATE DATABASE `ssmbuild`;

USE `ssmbuild`;

DROP TABLE IF EXISTS `books`;

CREATE TABLE `books` (
`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` VARCHAR(100) NOT NULL COMMENT '书名',
`bookCounts` INT(11) NOT NULL COMMENT '数量',
`detail` VARCHAR(200) NOT NULL COMMENT '描述',
KEY `bookID` (`bookID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT  INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,'Java',1,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',5,'从进门到进牢');

Run the above: Insert image description here

7.3. Basic Environment Setup

7.3.1. Create a new Maven Project called SSMbuild with web support

Insert image description here

7.3.2. Import related pom dependencies, Maven resource filtering settings

<?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>org.example</groupId>
    <artifactId>SSMbuild</artifactId>
    <version>1.0-SNAPSHOT</version>

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

    <!-- Dependencies: includes JUnit, database drivers, connection pools, Servlet, JSP, MyBatis, MyBatis-spring, Spring -->
    <dependencies>
        <!-- JUnit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!-- Database driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!-- Database connection pool: using c3p0 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>

        <!-- Servlet - JSP -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- Mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>

        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>

        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
        </dependency>

    </dependencies>
    <!-- Static resource export issue: ensure that properties and xml under java resources can be successfully exported -->
    <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>

7.3.3. Connect to the Database

Insert image description here
Enter User and Password then click on test connection, follow the settings in the image.
Insert image description here
Insert image description here

7.3.4. Establish Basic Structure and Configure Framework

7.3.4.1. As shown in the diagram

Insert image description here

7.3.4.2. MyBatis-config.xml

(Still subject to modification, see 7.3.5.2.)

<?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>

</configuration>
7.3.4.3. applicationContext.xml

(Still subject to modification, see 7.3.7.4.1.)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>

In the upper right corner of the configuration, select the create option, set the defaults and click OK.
(See details in 7.3.6.4)

7.3.5. Writing Mybatis Layer

7.3.5.1. Creating a New Database Configuration File database.properties

jdbc.driver=com.mysql.jdbc.Driver
#jdbc.driver = com.mysql.cj.jdbc.Driver cannot use this line (new version), otherwise it reports error 500
#If using MySQL version 8.0+, you also need to manually add timezone configuration: "&serverTimezone=Asia/Shanghai"
jdbc.url=jdbc:mysql://localhost:3306/SSMbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root (default is root)
jdbc.password=write your database password here

7.3.5.2. Writing the Core Configuration File of MyBatis

(Complete code in 7.3.5.6)

<?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>
    <!--Configuration of data source, delegated to Spring-->
    <typeAliases>
        <package name="P17.project"/>
    </typeAliases>
</configuration>
7.3.5.3. Creating Entity Class Books.java for the Database, Using lombok Plugin

package P17.project;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;
}
  • If lombok was not configured at the first configuration, you should now modify the pom.xml file to add the lombok dependency.
<!--lombok-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.20</version>
</dependency>
7.3.5.4. Writing the DAO Layer Interface BookDao.java

package P17.dao;

import P17.project.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface BookDao {
    // Add a book
    int addBook(Books books);

    // Delete a book by id
    int deleteBookById(@Param("bookId") int id);

    // Update book
    int updateBook(Books books);

    // Query and return a book by id
    Books queryBookById(int id);

    // Query all books, return a list collection
    List<Books> queryAllBook();
}
7.3.5.5. Writing the BookDao.xml File Corresponding to the Interface

BookDao.xml needs to be imported into MyBatis’ package (7.3.5.6)
Subject to further modification, see 7.7.3

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--One mapper corresponds to one interface-->
<mapper namespace="P17.dao.BookMapper">

    <!--Add a book-->
    <insert id="addBook" parameterType="books">
        INSERT INTO ssmbuild.books(bookName, bookCounts, detail)
        VALUES (#{bookName},#{bookCounts},#{detail});
    </insert>

    <!--Delete a book by id-->
    <delete id="deleteBookId" parameterType="int">
        DELETE FROM ssmbuild.books WHERE bookId = #{bookId}
    </delete>

    <!--Update Book-->
    <update id="updateBook" parameterType="Books">
        UPDATE ssmbuild.books
        SET bookName = #{bookName}, bookCounts = #{bookCounts}, detail = #{detail}
        WHERE bookID = #{bookID}
    </update>

    <!--Query by id, return a Book-->
    <select id="queryBookById" resultType="Books">
        SELECT * FROM ssmbuild.books
        WHERE bookID = #{bookId}
    </select>

    <!--Query all Books-->
    <select id="queryAllBook" resultType="Books">
        SELECT * FROM ssmbuild.books
    </select>
    
</mapper>
  • Note: When configuring mappers in mybatis-confi, if you are using class or name, ensure that the interface and xml have the same name and package. If using resource, specify the location of the xml.
  • If no prompt appears when entering SQL statements, the method to open it is: In settings–>Languages & Frameworks (might also be under the Spring directory)–>SQL Dialects, configure the database type and add the project to it. After configuring, click Apply-OK.
7.3.5.6. Binding the BookDao.xml File to MyBatis-config.xml

Modify MyBatis-config.xml
IDEA might not prompt for the BookDao.xml file, but rather for the BookDao.java. But be aware it’s not BookDao.java!!!

<?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>
    <!--Configuration of data source, delegated to Spring-->
    <typeAliases>
        <package name="P17.project"/>
    </typeAliases>

    <mappers>
        <!--If the two files in dao have different names, use mapper resource-->
        <!--Choose any one of the following three lines-->
        <mapper resource="P17/dao/BookDao.xml"/>
<!--        <mapper class="P17.dao.BookDao"/>-->
<!--        <package name="P17.dao"/>-->
    </mappers>
</configuration>
7.3.5.7. Writing the Service Layer Interface and Implementation Classes

7.3.5.7.1. Interface

Create BookService.Interface

package P17.service;

import P17.project.Books;

import java.util.List;

public interface BookService {
    // Add a book
    int addBook(Books books);

    // Delete a book by id
    int deleteBookById(int id);

    // Update book
    int updateBook(Books books);

    // Query and return a book by id
    Books queryBookById(int id);

    // Query all books, return a list collection
    List<Books> queryAllBook();
}
7.3.5.7.2. Implementation Class

Create BookServiceImplement.java

package P17.service;

import P17.dao.BookDao;
import P17.project.Books;

import java.util.List;

//@Service
public class BookServiceImplement implements BookService {
//    Service layer calling dao layer: for dao operations, set an interface for easy Spring management
//    @Autowired
    //Using the currently commented @Service and @Autowired can also achieve jumping to BookMapper
    private BookDao bookDao;
    public void setBookMapper (BookDao bookDao){
        this.bookDao = bookDao;
    }

    @Override
    public int addBook(Books books) {
        return bookDao.addBook(books);
    }

    @Override
    public int deleteBookById(int id) {
        return bookDao.deleteBookById(id);
    }

    @Override
    public int updateBook(Books books) {


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值