使用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="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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--controller -->
    <context:component-scan base-package="com.bookstore.Controller" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

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

    <!-- 注册映射 -->
    <mvc:annotation-driven />

    <!-- 处理静态资源-->
    <mvc:default-servlet-handler />
</beans>

web.xml配置文件src/main/webapp/WEB-INF/web.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">

    <!-- 载入Spring配置 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 编码格式UTF8 -->
    <filter>
        <filter-name>encodingUTF8</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>encodingUTF8</filter-name>
        <url-pattern>/*</url-pattern>   <!--注意此处加*表示所有 -->
    </filter-mapping>

    <!-- Spring MVC 前端转发器 -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
发布了13 篇原创文章 · 获赞 0 · 访问量 914
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览