首先明确项目的大体流程:需求分析->设计数据库->业务->前端页面。利用SSM实现图书馆的图书管理,包含增删改查。

1、设计数据库

使用命令行操作mysql,先建立一个简单的数据库ssm,并插入表单library:

SSM项目连接mysql ssm项目怎么连接数据库_xml


其字段等信息创建好后,插入几组数据:

SSM项目连接mysql ssm项目怎么连接数据库_bc_02


2、开始配置项目环境

首先,创建一个普通的maven项目。

在pom.xml中,配置基本的依赖(导入依赖,包括:junit/数据库驱动/连接池/servlet/jsp/mybatis/mybatis-spring/springmvc/springjdbc/lombok(方便创建实体类)等),并解决静态资源导出问题:

<?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.pht</groupId>
    <artifactId>ssmdemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--导入依赖,包括:junit/数据库驱动/连接池/servlet/jsp/mybatis/mybatis-spring/spring-->
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.2</version>
            <scope>test</scope>
        </dependency>

        <!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</version>
        </dependency>

        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>3.0-alpha-1</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2.1-b03</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>

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

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>1.2.6</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
		<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
        </dependency>
    </dependencies>

    <!--静态资源问题-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>

            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>

配置完依赖后,可以测试数据库连接。

3、建立文件架构

SSM项目连接mysql ssm项目怎么连接数据库_spring_03

包含:Dao层/Service层/Controller层/实体类
此外,spring的配置文件applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>

mybatis配置文件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>

</configuration>

4、开始配置mybatis(没有采用注解的方法)

(1)建立数据库的属性配置文件database.properties:

SSM项目连接mysql ssm项目怎么连接数据库_bc_04

jdbc.driver=com.mysql.cj.jdbc.Driver
#MySQL8.0+连接时区设置
jdbc.url=jdbc:mysql://localhost:3306/ssm?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456

(2)编写dao层接口与实体类:
实体类:

package com.pht.ssm.Pojo;

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

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Library {
    private int bookID;
    private String bookName;
    private int bookNums;
    private String bookDetail;
}

编写Dao层接口Daomapper:

package com.pht.ssm.Dao;

import com.pht.ssm.Pojo.Library;

import java.util.List;

public interface Daomapper {
    //Dao层的方法有原子性,比较简单底层的方法
    //增加一本书
    int addBook(Library ly);
    //删除一本书
    int deleteBook(int bookId);
    //通过id查询一本书
    Library queryBookById(int bookID);
    //通过书名查询一本书
    Library queryBookByName(String bookName);
    //更新一本书
    int updatabook(Library ly);
    //查询全部书籍
    List<Library> allbook();

}

(3)编写Daomapper.xml

SSM项目连接mysql ssm项目怎么连接数据库_xml_05


一个mapper对应一个接口!

其实插入时,id为主键自增,不用添加的。在mybatis-config中注册了实体类的别名,故可以直接写成这样parameterType="Library"内容如下:

<?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">
<mapper namespace="com.pht.ssm.Dao.Daomapper">
    <insert id="addBook" parameterType="Library">
        <!--id为主键自增,不用添加-->
        insert into ssm.library (bookName,bookNums,bookDetail) values (#{bookName},#{bookNums},#{bookDetail});
    </insert>

    <delete id="deleteBook" parameterType="int">
        delete from ssm.library where bookId=#{bookId}
    </delete>

    <update id="updatabook" parameterType="Library">
        update ssm.library set bookName=#{bookName},bookNums=#{bookNums},bookDetail=#{bookDetail} where bookId=#{bookId};
    </update>

    <select id="queryBookById" resultType="Library">
        select * from ssm.library where bookId=#{bookId}
    </select>

    <select id="queryBookByName" resultType="Library">
        select * from ssm.library where bookName=#{bookName}
    </select>

    <select id="allbook" resultType="Library">
        select * from ssm.library
    </select>

</mapper>

(4)、记得要在mybatis-config中注册mapper
typeAliases:别名

<?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>
        <typeAliases>
            <package name="com.pht.ssm.Pojo"/>
        </typeAliases>
    
    <mappers>
        <mapper class="com.pht.ssm.Dao.Daomapper"/>
    </mappers>
</configuration>

(5)编写service层的接口和实现

SSM项目连接mysql ssm项目怎么连接数据库_bc_06


接口:

package com.pht.ssm.Service;
import com.pht.ssm.Pojo.Library;

import java.util.List;
//业务层接口,实现的业务逻辑,这里与Dao层的方法差不多,直接拿过来用了
public interface LibraryServer {
    int addBook(Library ly);
    int deleteBook(int bookId);
    Library queryBookById(int bookID);
    Library queryBookByName(String bookName);
    int updatabook(Library ly);
    List<Library> allbook();
}

实现类:

package com.pht.ssm.Service;

import com.pht.ssm.Dao.Daomapper;
import com.pht.ssm.Pojo.Library;
import java.util.List;

public class LibrarySerImp implements LibraryServer{
    //业务层实现持久层
    private Daomapper dmr;
    public void setDmr(Daomapper dmr) {
        this.dmr = dmr;
    }
    public int addBook(Library ly) {
        return dmr.addBook(ly);
    }
    public int deleteBook(int bookId) {
        return dmr.deleteBook(bookId);
    }
    public Library queryBookById(int bookID) {
        return dmr.queryBookById(bookID);
    }
    public Library queryBookByName(String bookName) {
        return dmr.queryBookByName(bookName);
    }
    public int updatabook(Library ly) {
        return dmr.updatabook(ly);
    }
    public List<Library> allbook() {
        return dmr.allbook();
    }
}

以上暂时没有使用spring框架,下面将配置spring,并对上面的一些地方进行优化。

5、开始配置spring

(1)spring整合Dao层。首先建立spring-Dao.xml:

SSM项目连接mysql ssm项目怎么连接数据库_xml_07

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

    <!--关联数据库配置文件(之前是通过mybatis读取配置文件,现在交给spring了)-->
    <context:property-placeholder location="classpath:database.properties"/>

    <!--连接池,不使用spring的,使用c3p0-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- ${}用于字符的拼接
        ${}和#{}的区别:${}注入会直接注入,即注入的变量是什么就注入什么
        -->
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

        <!--设置数据库连接池的参数-->
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <property name="acquireRetryAttempts" value="3"/>
        <property name="checkoutTimeout" value="8000"/>
        <property name="autoCommitOnClose" value="false"/>
    </bean>

    <!--sqlsessionfactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--绑定mybatis的配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!--动态实现Dao接口配置到包-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--注入sqlSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!--要扫描的Dao包-->
        <property name="basePackage" value="com.pht.ssm"/>
    </bean>

</beans>

(2)spring整合service层,该层中最重要的是事务的配置。先建立spring-Service.xml用于整合:

SSM项目连接mysql ssm项目怎么连接数据库_bc_08


idea自动将下面几个文件的上下文整合到一起了:

SSM项目连接mysql ssm项目怎么连接数据库_SSM项目连接mysql_09

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

    <!--首先,扫描service下的包-->
    <context:component-scan base-package="com.pht.ssm.Service"/>

    <!--将业务类注入到spring-->
    <bean id="LibrarySerImp" class="com.pht.ssm.Service.LibrarySerImp">
        <property name="dmr" ref="dmr"/>
    </bean>

    <!--声明式事务-->
    <bean id="tranactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

6、配置springmvc
先把项目添加web。在web.xml中配置DispatchServlet,乱码过滤,web.xml如下:
contextConfigLocation的路径要写:applicationContext.xml 而不是:spring-mvc.xml 因为applicationContext.xml配置了三个xml文件的上下文,applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <import resource="spring-Dao.xml"/>
    <import resource="spring-Service.xml"/>
    <import resource="spring-mvc.xml"/>
</beans>

spring-mvc.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--配置DispatchServlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--乱码过滤-->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--session配置-->
    <session-config>
        <session-timeout>10</session-timeout>
    </session-config>
</web-app>

(2)创建spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
       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">

    <!--使用注解,添加注解驱动-->
    <mvc:annotation-driven/>
    <!--静态资源过滤-->
    <mvc:default-servlet-handler/>
    <!--扫描包-->
    <context:component-scan base-package="com.pht.ssm.Controller"/>

    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="suffix" value=".jsp"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
    </bean>

</beans>

并在WEB-INF下建立jsp文件夹。还要记得在项目structure中增加lib,并导入jar包。接下来亏可以写项目了,即将Controller层和jsp交互起来。
到这里,ssm框架大体就完成了