Java商城数据库实体创建与Spring+Mybatis连接配置

系统整体设计

系统功能模块划分

系统用到的数据表设计如下,首先head_line用于储存头条显示的信息。shop是店铺表,area为其所属区域表,shop_category为商店类别表。product为商品表,product_category为商品类别表,product_img为商品图片信息表。person_info为用户信息表,wechat_account为微信账户表,local_account为本地账户表。

创建实体类

首先需要在数据库中创建以上的表,例如部分表的设计如下

然后利用IDEA的JPA接口可以实现自动创建相应地Java类,如下所示,首先在Project Structure中点击“+”选择JPA,然后选择provider为Hibernate之后就会在左下角出现Persistence的图标。或者通过工具栏的View -> Tool windows也能添加窗口。选择创建By data schema,然后选择类生成的包、导入的数据表即可自动生成一个类,并且自动生成类的get/set方法。

 

package com.tory.shop.entity;

import java.util.Date;

public class Shop {
    private Integer shopId;
    private String shopName;
    private String shopDescribe;
    private String shopAddr;
    private String shopImg;
    private String shopPhone;
    private Date createTime;
    private Date lastEditTime;
    private Integer priority;
    private Integer enableStatus;       //店铺状态:-1、不可用,0、审核中,1、可用
    private String adviceMessage;      //管理员给店铺的提示信息
    private Area area;
    private PersonInfo owner;
    private ShopCategory shopCategory;

    //getter & setter ...
}

maven构建项目

创建Java工程项目如下所示。首先src/main/java目录下存放主要的java文件,例如包括控制器类包controller、dao包、主要实体类entity、枚举enums、拦截器interceptor、服务类service、工具类util的包。resources文件夹用于存放xml配置文件等资源。webapp为web应用的文件夹,resources文件夹用于存放web页面的静态资源,WEB-INF存放页面。test目录为测试文件的目录,其中java和resources目录与src/main下的相对应。

接着通过maven添加项目依赖。首先引入Java项目所需要的基本包:提供servlet服务的javax.servlet-api、提供json解析的jackson-databind、spring所需的Map工具类commons-collections、日志输出工具logback-classic包、测试模块junit

接着引入8个Spring相关的包:核心工具类spring-core、bean管理类spring-beans、上下文管理类spring-context、数据库访问类spring-jdbc、事务管理类spring-tx、web开发相关类spring-web、MVC框架类spring-mvc、测试相关类spring-test。

最后引入数据库交互相关的包:链接MySQL的mysql-connector-java、数据库连接池c3p0、mybatis核心包mybatis、与spring交互的mybatis-spring

SSM框架配置

接着由下到上配置SSM框架的相关文件,首先在resources文件夹下新建数据库连接配置文件jdbc.properties,在该文件中指定数据库的连接驱动、url、用户名和密码

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/shop_demo
jdbc.username=root
jdbc.password=1234

接着对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>
    <settings>
        <!--设置控制台输出日志-->
        <setting name="logImpl" value="STDOUT_LOGGING" />
        <!--获取自增主键值-->
        <setting name="useGeneratedKeys" value="true"/>
        <!--查询语句使用数据库字段名-->
        <setting name="useColumnLabel" value="true"/>
        <!--开启驼峰命名转换-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

在往上来到了spring的DAO层,在spring-dao.xml文件中首先根据jdbc.properties文件创建c3p0类型的数据库连接源dataSource,然后将该数据源注入并创建Mybatis的SqlSessionFactory对象,然后完成mybatis对Spring的DAO接口映射。

值得注意的是,在加载xml资源文件时需要在前面增加"classpath:",项目打包之后resource目录下的文件会放到target/classes目录下,因此需要从该路径下加载。否则有时候IDEA的自动提示会找得到该文件,而且在测试代码中可以正常运行,但是打包发布项目就会报错找不到.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="classpath:jdbc.properties"/>

    <!--配置c3p0数据库连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--注入引入jdbc.properties文件中的数据库变量-->
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <!--对c3p0进行设置-->
        <property name="maxPoolSize" value="30"/>
        <property name="checkoutTimeout" value="10000"/>
        <property name="autoCommitOnClose" value="false"/>  <!--关闭连接后不自动提交-->
        <property name="acquireRetryAttempts" value="2"/>   <!--自动重连尝试次数-->
    </bean>

    <!--配置Mybatis的SqlSessionFactory对象-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--引入配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--扫描数据库实体的java类-->
        <property name="typeAliasesPackage" value="com.tory.shop.entity"/>
        <!--扫描实体对应的mapper文件-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

    <!--配置DAO接口注入到Spring容器-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--注入sqlSessionFactory对象名,注意是只是名字,等到spring初始化完成后在创建对象-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!--扫描DAO类所在的包-->
        <property name="basePackage" value="com.tory.shop.dao"/>
    </bean>
</beans>

接着向上配置spring的服务层,如下所示为spring-service.xml文件,在其中扫描service类并且开启Spring的事务管理

<?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"
       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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--扫描service包下所有的service类-->
    <context:component-scan base-package="com.tory.shop.service"/>

    <!-- 事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 开启基于注解的事务管理 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

再往上配置spring的MVC管理模块,如下所示为spring-mvc.xml,在其中扫描所有的controller类,配置web的静态资源目录,并且定义视图解析器

<?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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--开启SpringMVC的注解模式-->
    <mvc:annotation-driven/>
    <!--扫描controller类-->
    <context:component-scan base-package="com.tory.shop.controller"/>
    <!-- 映射静态资源目录,将静态资源交给default-servlet-handler处理 -->
    <mvc:resources mapping="/resources/**" location="/resources/"/>
    <mvc:default-servlet-handler/>
    <!--定义视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/html/"/>
        <property name="suffix" value=".html"/>
    </bean>
</beans>

最后是总的web配置文件,如下所示为web.xml文件,在其中注册spring的DispatcherServlet并映射管理所有的路径请求

可以在其中添加编码方式过滤器用于给请求中的字符进行编码防止出现中文乱码的情况,注意编码过滤器要配置在所有过滤器的前面

<?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_3_1.xsd"
         version="3.1" metadata-complete="true">
  <servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/spring-*.xml</param-value>
    </init-param>
  </servlet>
  <!--映射管理所有的路径-->
  <servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>


  <!-- 配置编码方式过滤器 -->
  <filter>
    <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

验证测试

首先实现Area的Dao层来完成与数据库的交互操作,创建AreaDao接口,由于使用Mybatis框架,所以该接口不需要实现

package com.tory.shop.dao;

import com.tory.shop.entity.Area;

import java.util.List;

public interface AreaDao {
    List<Area> queryArea();
}

接着在resources/mapper下创建AreaDao对应的映射配置文件AreaDao.xml,并且实现queryArea方法的SQL语句

<?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.tory.shop.dao.AreaDao">
    <select id="queryArea" resultType="com.tory.shop.entity.Area">
        SELECT area_id,area_name,priority,create_time,last_edit_time
        FROM tb_area ORDER BY priority
    </select>
</mapper>

通过Service层调用Dao操作,如下所示为AreaService接口及其实现类AreaServiceImpl

package com.tory.shop.service;

import com.tory.shop.entity.Area;
import java.util.List;

public interface AreaService {
    List<Area> getAreaList();
}

package com.tory.shop.service.impl;

import com.tory.shop.dao.AreaDao;
import com.tory.shop.entity.Area;
import com.tory.shop.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service                        //添加注解才能被Spring的Bean管理发现
public class AreaServiceImpl implements AreaService {
    @Autowired
    private AreaDao areaDao;

    public List<Area> getAreaList() {
        return areaDao.queryArea();
    }
}

最后在Controller层定义对特定请求路径的响应方法,通过调用AreaService获得数据列表并以Json的形式返回给客户

package com.tory.shop.controller.superadmin;

import com.tory.shop.entity.Area;
import com.tory.shop.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/area")        //类的路由映射
public class AreaController {
    @Autowired
    private AreaService areaService;

    @RequestMapping("/list")    //方法的路由映射
    @ResponseBody               //返回Json格式的数据
    public List<Area> getList(){
        return areaService.getAreaList();
    }
}

在浏览器中访问上述路径,得到结果如下,证明SSM框架运行成功并从数据库中取得数据返回给客户:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值