使用SSM重構Bookstore——環境準備

1、系統環境

在這裏插入圖片描述

2、數據庫建表

啓動mysql服務

sudo systemctl start mysqld

登錄mysql

mysql -u root -p

建立數據庫(如果存在先刪除)

drop database if exists `Bookstore`;
create database `Bookstore`;
use Bookstore;

建表(建好後通過show create table 表名 拷貝過來的,自己寫的有點亂,注意字符集選取utf8mb4而不是utf8)

  • 用戶表
CREATE TABLE `tbl_User` (
  `id` varchar(100) NOT NULL,
  `username` varchar(20) NOT NULL,
  `password` varchar(50) NOT NULL,
  `email` varchar(50) NOT NULL,
  `telephone` varchar(20) NOT NULL,
  `registTime` timestamp NOT NULL,
  `realname` varchar(10) DEFAULT NULL,
  `gender` char(1) DEFAULT 'M',
  `birthday` date DEFAULT NULL,
  `activeCode` varchar(50) DEFAULT NULL,
  `state` tinyint(4) DEFAULT NULL,
  `role` varchar(10) DEFAULT 'normal', 
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  • 產品表
CREATE TABLE `tbl_Product` (
  `id` varchar(100) NOT NULL,
  `name` varchar(40) NOT NULL,
  `price` double NOT NULL,
  `category` varchar(40) NOT NULL,
  `pnum` bigint(20) NOT NULL,
  `imgurl` varchar(100) DEFAULT NULL,
  `description` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  • 訂單表
CREATE TABLE `tbl_Order` (
  `id` varchar(100) NOT NULL,
  `money` double NOT NULL,
  `receiverAddress` varchar(255) NOT NULL,
  `receiverName` varchar(20) NOT NULL,
  `receiverPhone` varchar(20) NOT NULL,
  `paystate` tinyint NOT NULL,
  `ordertime` timestamp NOT NULL,
  `user_id` varchar(100) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`),
  CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `tbl_User` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  • 訂單條目表
CREATE TABLE `tbl_OrderItem` (
  `order_id` varchar(100) NOT NULL,
  `product_id` varchar(100) NOT NULL,
  `buynum` int(11) DEFAULT NULL,
  PRIMARY KEY (`order_id`,`product_id`),
  KEY `product_id` (`product_id`),
  CONSTRAINT `orderitem_ibfk_1` FOREIGN KEY (`order_id`) REFERENCES `tbl_Order` (`id`),
  CONSTRAINT `orderitem_ibfk_2` FOREIGN KEY (`product_id`) REFERENCES `tbl_Product` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

3、 SSM環境配置

IDE
在這裏插入圖片描述 1. 使用Maven新建工程
在這裏插入圖片描述2. 完善目錄結構
在這裏插入圖片描述
3. 配置依賴 —— POM文件(直接在Idea的Project Structure中配置依賴在刷新POM時會被丟棄)

<?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>ssm</groupId>
  <artifactId>Bookstore</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>Bookstore Maven Webapp</name>
  <url>http://localhost:8080/Bookstore</url>

  <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>
      
    <!-- spring 版本-->  
    <spring-version>5.1.6.RELEASE</spring-version>
  </properties>

    <!-- 依賴部分 -->
    <dependencies>

      <!-- Spring 核心 -->
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring-version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring-version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring-version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>${spring-version}</version>
      </dependency>

      <!-- Spring Aop -->
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${spring-version}</version>
      </dependency>
      <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.3</version>
      </dependency>

      <!-- Spring Web相關 -->
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring-version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring-version}</version>
      </dependency>
      <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
      </dependency>
      <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
      </dependency>

      <!-- Spring Dao -->
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring-version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring-version}</version>
      </dependency>

      <!-- Mybatis -->
      <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.1</version>
      </dependency>
      <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.1</version>
      </dependency>
      <dependency>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-core</artifactId>
        <version>1.3.7</version>
      </dependency>

      <!-- 數據庫相關 -->
      <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.4</version>
      </dependency>
      <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.15</version>
      </dependency>

      <!-- 日誌相關 -->
      <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
      </dependency>

      <!-- junit -->
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
      </dependency>

    </dependencies>
	
    <!-- 以下爲自動生成 -->
  <build>
    <finalName>Bookstore</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

4.使用Mybatis generator生成相關文件

生成器配置文件generatorConfig.xml位於src/main/resources

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<!-- Mybatis Generator最完整配置詳解 https://www.jianshu.com/p/e09d2370b796 -->

<generatorConfiguration>

  <properties resource="db.properties" /><!--數據庫配置文件也在main/resources下-->
  <context id="bookstore" targetRuntime="MyBatis3">

    <!--生成代碼不要註釋 -->
    <commentGenerator>
      <property name="suppressAllComments" value="true" />
      <property name="suppressDate" value="true" />
    </commentGenerator>

    <!-- 數據庫連接設置 -->
    <jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}">
    </jdbcConnection>

    <!-- true:使用BigDecimal對應DECIMAL和 NUMERIC數據類型 false:默認, scale>0;length>18:使用BigDecimal; scale=0;length[10,18]:使用Long; scale=0;length[5,9]:使用Integer; scale=0;length<5:使用Short; -->
    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>

    <!-- 實體類 -->
    <javaModelGenerator targetPackage="com.bookstore.Domain" targetProject="./src/main/java">
      <property name="trimStrings" value="true" />
    </javaModelGenerator>

    <!-- xml映射文件 -->
    <sqlMapGenerator targetPackage="Mapper" targetProject="./src/main/resources">
    </sqlMapGenerator>

     <!-- 接口包 -->
    <javaClientGenerator type="XMLMAPPER" targetPackage="com.bookstore.Dao" targetProject="./src/main/java">
    </javaClientGenerator>

	<!-- 表-->
    <table tableName="tbl_User" domainObjectName="User" />
    <table tableName="tbl_Product" domainObjectName="Product"/>
    <table tableName="tbl_Order" domainObjectName="Order"/>
    <table tableName="tbl_OrderItem" domainObjectName="OrderItem"/>

  </context>
</generatorConfiguration>

使用Maven插件運行MBG

<!-- POM文件dependencies添加插件依賴 -->
<dependency>
	<groupId>org.mybatis.generator</groupId>
	<artifactId>mybatis-generator-maven-plugin</artifactId>
	<version>1.3.7</version>
</dependency>

<!-- POM文件build添加插件 -->
<plugins>
	<plugin>
		<groupId>org.mybatis.generator</groupId>
		<artifactId>mybatis-generator-maven-plugin</artifactId>
		<version>1.3.7</version>
		<configuration>
			<configurationFile>
				<!--這裏是配置generatorConfig.xml的路徑 不寫默認在resources目錄下找generatorConfig.xml文件 -->
			</configurationFile>
			<verbose>true</verbose>
			<overwrite>true</overwrite>
		</configuration>
		<dependencies>
			<dependency>
                <!--數據庫驅動也可以用MBG配置文件ClassPathEntry標籤添加 -->
				<groupId>mysql</groupId>
				<artifactId>mysql-connector-java</artifactId>
				<version>8.0.15</version>
			</dependency>
		</dependencies>
	</plugin>
</plugins>

在這裏插入圖片描述

運行後生成結果:
在這裏插入圖片描述
5. 配置Spring及Spring MVC

Spring配置文件src/main/resources/spring.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" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mybatis="http://mybatis.org/schema/mybatis-spring" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd">

    <!-- 控制器由SpringMVC管理故而除外 -->
    <context:component-scan base-package="com.bookstore">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- 配置數據源 -->
    <context:property-placeholder location="classpath:db.properties" />
    <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}" />
    </bean>

    <!-- 配置事務管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 配置基於註解的聲明式事務 -->
    <tx:annotation-driven /> <!-- 如果管理器id不是transactionManager不可省略--> 

    <!-- Mybatis -->
    <!-- 配置SqlSessionFactory對象 -->
    <bean id="sqlSessionFactory" class="password" value="${jdbc.password}" />
    </bean>

    <!-- 配置事務管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 配置基於註解的聲明式事務 -->
    <tx:annotation-driven /> <!-- 如果管理器id不是transactionManager不可省略--> 

    <!-- Mybatis -->
    <!-- 配置SqlSessionFactory對象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入數據庫連接池 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 掃描sql配置文件:mapper需要的xml文件 -->
        <property name="mapperLocations" value="classpath:Mapper/*.xml" />
        <!--自動在下劃線駝峯命名方式間轉換 -->
        <property name="configuration" >
            <bean class="org.apache.ibatis.session.Configuration" >
                <property name="mapUnderscoreToCamelCase" value="true" />
            </bean>
        </property>
    </bean>

    <!-- 注入映射器 -->
    <!--不需要爲 <mybatis:scan/> 指定 SqlSessionFactory 或 SqlSessionTemplate,這是因爲它將使用能夠被自動注入的 MapperFactoryBean。 但如果你正在使用多個數據源(DataSource),自動注入可能不適合你。在這種情況下,你可以使用 factory-ref 或 template-ref 屬性指定你想使用的 bean 名稱。-->
    <mybatis:scan base-package="com.bookstore.Dao" />

    <!-- 老方法 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" > 注入sqlSessionFactory <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> 給出需要掃描Dao接口包 <property name="basePackage" value="com.bookstore.Dao" /> </bean> -->

</beans>

Spring MVC配置文件 src/main/resources/spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="" >
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 配置基於註解的聲明式事務 -->
    <tx:annotation-driven /> <!-- 如果管理器id不是transactionManager不可省略--> 

    <!-- Mybatis -->
    <!-- 配置SqlSessionFactory對象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入數據庫連接池 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 掃描sql配置文件:mapper需要的xml文件 -->
        <property name="mapperLocations" value="classpath:Mapper/*.xml" />
        <!--自動在下劃線駝峯命名方式間轉換 -->
        <property name="configuration" >
            <bean class="org.apache.ibatis.session.Configuration" >
                <property name="mapUnderscoreToCamelCase" value="true" />
            </bean>
        </property>
    </bean>

    <!-- 注入映射器 -->
    <!--不需要爲 <mybatis:scan/> 指定 SqlSessionFactory 或 SqlSessionTemplate,這是因爲它將使用能夠被自動注入的 MapperFactoryBean。 但如果你正在使用多個數據源(DataSource),自動注入可能不適合你。在這種情況下,你可以使用 factory-ref 或 template-ref 屬性指定你想使用的 bean 名稱。-->
    <mybatis:scan base-package="com.bookstore.Dao" />

    <!-- 老方法 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" > 注入sqlSessionFactory <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> 給出需要掃描Dao接口包 <property name="basePackage" value="com.bookstore.Dao" /> </bean> -->

</beans>

Spring MVC配置文件 src/main/resources/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:context="http://www.springframework.org/schema/context< <tx:annotation-driven /> <!-- 如果管理器id不是transactionManager不可省略--> <!-- Mybatis --> <!-- 配置SqlSessionFactory對象 --> <bean id="sqlSessionFactory" 
相關文章
相關標籤/搜索