• SSM_整合篇


    一、整合步骤

    1.1 数据表的介绍

    team表:

     player表:

    1.2 创建maven项目

    1.3 pom.xml引入jar依赖

    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    5. <modelVersion>4.0.0modelVersion>
    6. <groupId>com.lxygroupId>
    7. <artifactId>myssm_testartifactId>
    8. <version>1.0-SNAPSHOTversion>
    9. <packaging>warpackaging>
    10. <properties>
    11. <spring.version>5.2.13.RELEASEspring.version>
    12. <mybatis.version>3.5.6mybatis.version>
    13. <mybatis.spring.version>1.3.3mybatis.spring.version>
    14. <pagehelper.version>5.1.10pagehelper.version>
    15. <mysql.version>8.0.23mysql.version>
    16. <druid.version>1.2.3druid.version>
    17. <servlet-api.version>4.0.1servlet-api.version>
    18. <jackson.version>2.9.6jackson.version>
    19. <log4j.version>1.2.17log4j.version>
    20. <junit.version>4.12junit.version>
    21. <maven.compiler.source>11maven.compiler.source>
    22. <maven.compiler.target>11maven.compiler.target>
    23. properties>
    24. <dependencies>
    25. <dependency>
    26. <groupId>org.springframeworkgroupId>
    27. <artifactId>spring-webmvcartifactId>
    28. <version>${spring.version}version>
    29. dependency>
    30. <dependency>
    31. <groupId>org.springframeworkgroupId>
    32. <artifactId>spring-txartifactId>
    33. <version>${spring.version}version>
    34. dependency>
    35. <dependency>
    36. <groupId>org.springframeworkgroupId>
    37. <artifactId>spring-jdbcartifactId>
    38. <version>${spring.version}version>
    39. dependency>
    40. <dependency>
    41. <groupId>org.springframeworkgroupId>
    42. <artifactId>spring-aspectsartifactId>
    43. <version>${spring.version}version>
    44. dependency>
    45. <dependency>
    46. <groupId>commons-fileuploadgroupId>
    47. <artifactId>commons-fileuploadartifactId>
    48. <version>1.3.1version>
    49. dependency>
    50. <dependency>
    51. <groupId>org.mybatisgroupId>
    52. <artifactId>mybatisartifactId>
    53. <version>${mybatis.version}version>
    54. dependency>
    55. <dependency>
    56. <groupId>org.mybatisgroupId>
    57. <artifactId>mybatis-springartifactId>
    58. <version>${mybatis.spring.version}version>
    59. dependency>
    60. <dependency>
    61. <groupId>com.github.pagehelpergroupId>
    62. <artifactId>pagehelperartifactId>
    63. <version>${pagehelper.version}version>
    64. dependency>
    65. <dependency>
    66. <groupId>mysqlgroupId>
    67. <artifactId>mysql-connector-javaartifactId>
    68. <version>${mysql.version}version>
    69. dependency>
    70. <dependency>
    71. <groupId>com.alibabagroupId>
    72. <artifactId>druidartifactId>
    73. <version>${druid.version}version>
    74. dependency>
    75. <dependency>
    76. <groupId>javax.servletgroupId>
    77. <artifactId>javax.servlet-apiartifactId>
    78. <version>${servlet-api.version}version>
    79. <scope>providedscope>
    80. dependency>
    81. <dependency>
    82. <groupId>com.fasterxml.jackson.coregroupId>
    83. <artifactId>jackson-databindartifactId>
    84. <version>${jackson.version}version>
    85. dependency>
    86. <dependency>
    87. <groupId>log4jgroupId>
    88. <artifactId>log4jartifactId>
    89. <version>${log4j.version}version>
    90. dependency>
    91. <dependency>
    92. <groupId>junitgroupId>
    93. <artifactId>junitartifactId>
    94. <version>${junit.version}version>
    95. <scope>testscope>
    96. dependency>
    97. <dependency>
    98. <groupId>org.springframeworkgroupId>
    99. <artifactId>spring-testartifactId>
    100. <version>${spring.version}version>
    101. dependency>
    102. <dependency>
    103. <groupId>javax.annotationgroupId>
    104. <artifactId>javax.annotation-apiartifactId>
    105. <version>1.3.2version>
    106. dependency>
    107. dependencies>
    108. <build>
    109. <resources>
    110. <resource>
    111. <directory>src/main/javadirectory>
    112. <includes>
    113. <include>**/*.propertiesinclude>
    114. <include>**/*.xmlinclude>
    115. includes>
    116. <filtering>falsefiltering>
    117. resource>
    118. resources>
    119. <plugins>
    120. <plugin>
    121. <groupId>org.apache.maven.pluginsgroupId>
    122. <artifactId>maven-compiler-pluginartifactId>
    123. <configuration>
    124. <source>1.8source>
    125. <target>1.8target>
    126. <encoding>UTF-8encoding>
    127. configuration>
    128. plugin>
    129. <plugin>
    130. <groupId>org.apache.tomcat.mavengroupId>
    131. <artifactId>tomcat7-maven-pluginartifactId>
    132. <version>2.2version>
    133. <configuration>
    134. <port>80port>
    135. <path>/path>
    136. <uriEncoding>UTF-8uriEncoding>
    137. configuration>
    138. plugin>
    139. <plugin>
    140. <groupId>org.mybatis.generatorgroupId>
    141. <artifactId>mybatis-generator-maven-pluginartifactId>
    142. <version>1.3.5version>
    143. <configuration>
    144. <configurationFile>src/main/resources/generatorConfig.xmlconfigurationFile>
    145. <overwrite>trueoverwrite>
    146. configuration>
    147. <dependencies>
    148. <dependency>
    149. <groupId>org.mybatis.generatorgroupId>
    150. <artifactId>mybatis-generator-coreartifactId>
    151. <version>1.3.5version>
    152. dependency>
    153. dependencies>
    154. plugin>
    155. plugins>
    156. build>
    157. project>

    1.4 编写Mybatis的配置文件

    Mybatis的配置文件mybatis.xml

    1. "1.0" encoding="UTF-8" ?>
    2. configuration
    3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
    5. <configuration>
    6. <settings>
    7. <setting name="logImpl" value="LOG4J" />
    8. settings>
    9. configuration>

    日志配置文件文件log4j.properties:

    1. # Global logging configuration info warning error
    2. log4j.rootLogger=DEBUG,stdout
    3. # Console output...
    4. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    5. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    6. log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

    1.5 编写Spring的配置文件spring.xml 

     连接数据库的参数配置文件jdbc.properties

    1. jdbc.driver=com.mysql.cj.jdbc.Driver
    2. jdbc.url=jdbc:mysql://localhost:3306/myssm_kkb?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
    3. jdbc.username=root
    4. jdbc.password=linda198721

    这里数据库的版本是Mysql8

    spring.xml: 

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xmlns:tx="http://www.springframework.org/schema/tx"
    6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    7. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    8. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
    9. <context:component-scan base-package="com.lxy.mapper,com.lxy.service"/>
    10. <context:property-placeholder location="classpath*:jdbc.properties"/>
    11. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    12. <property name="driverClassName" value="${jdbc.driver}"/>
    13. <property name="url" value="${jdbc.url}"/>
    14. <property name="username" value="${jdbc.username}"/>
    15. <property name="password" value="${jdbc.password}"/>
    16. bean>
    17. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    18. <property name="configLocation" value="classpath:mybatis.xml"/>
    19. <property name="dataSource" ref="dataSource"/>
    20. <property name="typeAliasesPackage" value="com.lxy.pojo"/>
    21. <property name="plugins">
    22. <array>
    23. <bean class="com.github.pagehelper.PageInterceptor">
    24. <property name="properties">
    25. <value>
    26. reasonable=true
    27. value>
    28. property>
    29. bean>
    30. array>
    31. property>
    32. bean>
    33. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    34. <property name="basePackage" value="com.lxy.mapper"/>
    35. <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    36. bean>
    37. <tx:annotation-driven transaction-manager="transactionManager"/>
    38. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    39. <property name="dataSource" ref="dataSource"/>
    40. bean>
    41. beans>

     1.6 编写SpringMVC的配置文件springmvc.xml

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xmlns:mvc="http://www.springframework.org/schema/mvc"
    6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    7. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    8. http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    9. <context:component-scan base-package="com.lxy.controller"/>
    10. <mvc:annotation-driven/>
    11. <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    12. <property name="prefix" value="/pages/"/>
    13. <property name="suffix" value=".html"/>
    14. bean>
    15. <mvc:resources mapping="/img/**" location="/img/"/>
    16. <mvc:resources mapping="/js/**" location="/js/"/>
    17. <mvc:resources mapping="/css/**" location="/css/"/>
    18. <mvc:resources mapping="/fonts/**" location="/fonts/"/>
    19. <mvc:resources mapping="/static/**" location="/static/"/>
    20. <mvc:resources mapping="/pages/**" location="/pages/"/>
    21. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    22. bean>
    23. beans>

     1.7 导入静态页面

    如果您也想要这个项目的话,可以在下发评论,我私信发送给您

    1.8 编写web.xml配置文件

    1. "1.0" encoding="UTF-8"?>
    2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    5. version="4.0">
    6. <welcome-file-list>
    7. <welcome-file>/pages/index.htmlwelcome-file>
    8. welcome-file-list>
    9. <context-param>
    10. <param-name>contextConfigLocationparam-name>
    11. <param-value>classpath*:spring.xmlparam-value>
    12. context-param>
    13. <listener>
    14. <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    15. listener>
    16. <servlet>
    17. <servlet-name>dispatcherServletservlet-name>
    18. <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    19. <init-param>
    20. <param-name>contextConfigLocationparam-name>
    21. <param-value>classpath*:springmvc.xmlparam-value>
    22. init-param>
    23. <load-on-startup>1load-on-startup>
    24. servlet>
    25. <servlet-mapping>
    26. <servlet-name>dispatcherServletservlet-name>
    27. <url-pattern>/url-pattern>
    28. servlet-mapping>
    29. <filter>
    30. <filter-name>httpMethodFilterfilter-name>
    31. <filter-class>
    32. org.springframework.web.filter.HiddenHttpMethodFilter
    33. filter-class>
    34. filter>
    35. <filter-mapping>
    36. <filter-name>httpMethodFilterfilter-name>
    37. <url-pattern>/*url-pattern>
    38. filter-mapping>
    39. <filter>
    40. <filter-name>characterEncodingFilterfilter-name>
    41. <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    42. <init-param>
    43. <param-name>encodingparam-name>
    44. <param-value>UTF-8param-value>
    45. init-param>
    46. <init-param>
    47. <param-name>forceRequestEncodingparam-name>
    48. <param-value>trueparam-value>
    49. init-param>
    50. <init-param>
    51. <param-name>forceResponseEncodingparam-name>
    52. <param-value>trueparam-value>
    53. init-param>
    54. filter>
    55. <filter-mapping>
    56. <filter-name>characterEncodingFilterfilter-name>
    57. <url-pattern>/*url-pattern>
    58. filter-mapping>
    59. web-app>

     1.8 测试

    启动项目,浏览器访问http://localhost:8088/。看到如图所示页面表示项目整合成功。

    二、使用mybatis反向生成实体类、dao和映射文件

    2.1 反向生成配置文件generatorConfig.xml

    1. "1.0" encoding="UTF-8"?>
    2. generatorConfiguration
    3. PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
    4. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
    5. <generatorConfiguration>
    6. <classPathEntry
    7. location="D:\repository\mysql\mysql-connector-java\8.0.23\mysql-connector-java-8.0.23.jar" />
    8. <context id="MyBatis" targetRuntime="MyBatis3">
    9. <commentGenerator>
    10. <property name="suppressAllComments" value="true" />
    11. commentGenerator>
    12. <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
    13. connectionURL="jdbc:mysql://localhost:3306/myssm_kkb?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT"
    14. userId="a"
    15. passwor="a">
    16. jdbcConnection>
    17. <javaTypeResolver>
    18. <property name="forceBigDecimals" value="false" />
    19. javaTypeResolver>
    20. <javaModelGenerator targetPackage="com.lxy.pojo"
    21. targetProject="src\main\java">
    22. <property name="trimStrings" value="true" />
    23. javaModelGenerator>
    24. <sqlMapGenerator targetPackage="com.lxy.mapper"
    25. targetProject="src\main\resources">
    26. sqlMapGenerator>
    27. <javaClientGenerator type="XMLMAPPER"
    28. targetPackage="com.lxy.mapper"
    29. targetProject="src\main\java">
    30. javaClientGenerator>
    31. <table tableName="Team">
    32. <property name="useActualColumnNames" value="true"/>
    33. table>
    34. <table tableName="Player">
    35. <property name="useActualColumnNames" value="true"/>
    36. table>
    37. <table tableName="game">
    38. <property name="useActualColumnNames" value="true"/>
    39. table>
    40. <table tableName="GameType">
    41. <property name="useActualColumnNames" value="true"/>
    42. table>
    43. <table tableName="Admins">
    44. <property name="useActualColumnNames" value="true"/>
    45. table>
    46. <table tableName="AdminRole">
    47. <property name="useActualColumnNames" value="true"/>
    48. table>
    49. context>
    50. generatorConfiguration>

    2.2运行插件

    注意只能运行一次,运行完毕显示BUILD SUCCESS即为成功。

     2.3 测试

    1. package com.lxy.test;
    2. import com.lxy.mapper.TeamMapper;
    3. import com.lxy.pojo.Team;
    4. import org.junit.Test;
    5. import org.junit.runner.RunWith;
    6. import org.springframework.test.context.ContextConfiguration;
    7. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    8. import javax.annotation.Resource;
    9. @RunWith(SpringJUnit4ClassRunner.class)
    10. @ContextConfiguration(locations = {"classpath:spring.xml"})
    11. public class TestMapper {
    12. @Resource
    13. private TeamMapper teamMapper;
    14. @Test
    15. public void test01(){
    16. Team team = teamMapper.selectByPrimaryKey(1001);
    17. System.out.println(team);
    18. }
    19. }

    三、案例--使用多条件分页查询

    3.1 业务逻辑层

    编写一个QueryVO类,存储查询条件

    1. package com.lxy.vo;
    2. import org.springframework.format.annotation.DateTimeFormat;
    3. import java.util.Date;
    4. public class QueryVO {
    5. private String teamName;
    6. private String chineseName;
    7. private String coach;
    8. //@DateTimeFormat(pattern = "yyyy-MM-dd")
    9. private Date beginDate;
    10. //@DateTimeFormat(pattern = "yyyy-MM-dd")
    11. private Date endDate;
    12. private Integer area;
    13. @Override
    14. public String toString() {
    15. return "QueryVO{" +
    16. "teamName='" + teamName + '\'' +
    17. ", chineseName='" + chineseName + '\'' +
    18. ", coach='" + coach + '\'' +
    19. ", beginDate=" + beginDate +
    20. ", endDate=" + endDate +
    21. ", area=" + area +
    22. '}';
    23. }
    24. public String getTeamName() {
    25. return teamName;
    26. }
    27. public void setTeamName(String teamName) {
    28. this.teamName = teamName;
    29. }
    30. public String getChineseName() {
    31. return chineseName;
    32. }
    33. public void setChineseName(String chineseName) {
    34. this.chineseName = chineseName;
    35. }
    36. public String getCoach() {
    37. return coach;
    38. }
    39. public void setCoach(String coach) {
    40. this.coach = coach;
    41. }
    42. public Date getBeginDate() {
    43. return beginDate;
    44. }
    45. public void setBeginDate(Date beginDate) {
    46. this.beginDate = beginDate;
    47. }
    48. public Date getEndDate() {
    49. return endDate;
    50. }
    51. public void setEndDate(Date endDate) {
    52. this.endDate = endDate;
    53. }
    54. public Integer getArea() {
    55. return area;
    56. }
    57. public void setArea(Integer area) {
    58. this.area = area;
    59. }
    60. }

    编写service层代码,用来条件分页查询

    1. package com.lxy.service;
    2. import com.github.pagehelper.PageHelper;
    3. import com.github.pagehelper.PageInfo;
    4. import com.lxy.mapper.TeamMapper;
    5. import com.lxy.pojo.Team;
    6. import com.lxy.pojo.TeamExample;
    7. import com.lxy.vo.QueryVO;
    8. import org.springframework.stereotype.Service;
    9. import javax.annotation.Resource;
    10. import java.util.List;
    11. @Service
    12. public class TeamService {
    13. @Resource
    14. private TeamMapper teamMapper;
    15. public PageInfo queryByPage(Integer pageNum, Integer pageSize, QueryVO vo){
    16. TeamExample example = new TeamExample();
    17. //创建条件的容器
    18. TeamExample.Criteria criteria = example.createCriteria();
    19. if (vo!=null){
    20. if (vo.getTeamName()!=null&&!"".equals(vo.getTeamName().trim())){
    21. criteria.andTeamNameLike("%"+vo.getTeamName().trim()+"%");
    22. }
    23. if(vo.getChineseName()!=null && !"".equals(vo.getChineseName().trim()) ){
    24. criteria.andChineseNameLike("%"+vo.getChineseName().trim()+"%");
    25. }
    26. if(vo.getCoach()!=null && !"".equals(vo.getCoach().trim())){
    27. criteria.andCoachLike("%"+vo.getCoach().trim()+"%");
    28. }
    29. if(vo.getBeginDate()!=null){
    30. criteria.andCreateTimeGreaterThanOrEqualTo(vo.getBeginDate());
    31. }
    32. if(vo.getEndDate()!=null){
    33. criteria.andCreateTimeLessThanOrEqualTo(vo.getEndDate());
    34. }
    35. if(vo.getArea()!=null && vo.getArea()!=-1){
    36. criteria.andAreaEqualTo(vo.getArea());
    37. }
    38. }
    39. //分页
    40. PageHelper.startPage(pageNum,pageSize);
    41. List list = teamMapper.selectByExample(example);
    42. return new PageInfo<>(list);
    43. }
    44. }

     编写测试类:

    1. package com.lxy.test;
    2. import com.github.pagehelper.PageInfo;
    3. import com.lxy.mapper.TeamMapper;
    4. import com.lxy.pojo.Team;
    5. import com.lxy.service.TeamService;
    6. import org.junit.Test;
    7. import org.junit.runner.RunWith;
    8. import org.springframework.test.context.ContextConfiguration;
    9. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    10. import javax.annotation.Resource;
    11. @RunWith(SpringJUnit4ClassRunner.class)
    12. @ContextConfiguration(locations = {"classpath:spring.xml"})
    13. public class TestMapper {
    14. @Resource
    15. private TeamMapper teamMapper;
    16. @Resource
    17. private TeamService teamService;
    18. @Test
    19. public void test02(){
    20. PageInfo teamPageInfo = teamService.queryByPage(1, 5, null);
    21. System.out.println(teamPageInfo);
    22. }
    23. @Test
    24. public void test01(){
    25. Team team = teamMapper.selectByPrimaryKey(1001);
    26. System.out.println(team);
    27. }
    28. }

    测试结果:

    3.2 控制器层

    3.2.1 返回值的初始写法 

    编写controller代码:

    1. package com.lxy.controller;
    2. import com.github.pagehelper.PageInfo;
    3. import com.lxy.pojo.Team;
    4. import com.lxy.service.TeamService;
    5. import com.lxy.vo.QueryVO;
    6. import org.springframework.stereotype.Controller;
    7. import org.springframework.web.bind.annotation.RequestMapping;
    8. import org.springframework.web.bind.annotation.ResponseBody;
    9. import javax.annotation.Resource;
    10. @Controller
    11. @RequestMapping("team")
    12. @ResponseBody
    13. public class TeamController {
    14. @Resource
    15. private TeamService teamService;
    16. @RequestMapping("list")
    17. public PageInfo queryByPage(Integer pageNum, Integer pageSize, QueryVO vo){
    18. if (pageNum==null || pageNum<=0){
    19. pageNum=1;
    20. }
    21. if (pageSize==null || pageSize<=0){
    22. pageSize=5;
    23. }
    24. PageInfo teamPageInfo = teamService.queryByPage(pageNum, pageSize, vo);
    25. return teamPageInfo;
    26. }
    27. }

    这样返回给前端是返回的json格式的,包括时间,如果我们要返回正常的时间,需要在Team实体类中的时间字段上添加

    @JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8")这样显示的时间正常。

    启动程序来测试一下:

    这样可以看到返回的json数据正常

    3.2.2 返回值的高级写法

    将返回值封装为ResultVO,既能返回一个pageInfo,还能返回一个对象,一个集合,以及一条消息。

    更改controller代码:

    1. package com.lxy.controller;
    2. import com.github.pagehelper.PageInfo;
    3. import com.lxy.pojo.Team;
    4. import com.lxy.service.TeamService;
    5. import com.lxy.vo.QueryVO;
    6. import com.lxy.vo.ResultVO;
    7. import org.springframework.stereotype.Controller;
    8. import org.springframework.web.bind.annotation.RequestMapping;
    9. import org.springframework.web.bind.annotation.ResponseBody;
    10. import javax.annotation.Resource;
    11. @Controller
    12. @RequestMapping("team")
    13. @ResponseBody
    14. public class TeamController {
    15. @Resource
    16. private TeamService teamService;
    17. @RequestMapping("list")
    18. public ResultVO queryByPage(Integer pageNum, Integer pageSize, QueryVO vo){
    19. if (pageNum==null || pageNum<=0){
    20. pageNum=1;
    21. }
    22. if (pageSize==null || pageSize<=0){
    23. pageSize=5;
    24. }
    25. PageInfo teamPageInfo = teamService.queryByPage(pageNum, pageSize, vo);
    26. return new ResultVO<>(teamPageInfo);
    27. }
    28. }

    启动程序测试:

    3.2.3 日期类型解决方案

    如果此时想访问localhost的主页面来获取数据,很抱歉目前还获取不到。

    因为如果通过主页面来获取条件,初始时时间数据为空,那么程序会想把空指转换为日期类型,所以我们必须要在QueryVO中日期属性上加上日期格式化的注解  如下--

    //如果实体类中的日期类型需要从页面获取数据,避免NULL转换为Date类型出现问题
    //解决方案2:@InitBinder
    //解决方案1:实体类的日期类型属性上添加注解
    

     方案一: 

     日期格式化:

    1. package com.lxy.vo;
    2. import org.springframework.format.annotation.DateTimeFormat;
    3. import java.util.Date;
    4. public class QueryVO {
    5. private String teamName;
    6. private String chineseName;
    7. private String coach;
    8. @DateTimeFormat(pattern = "yyyy-MM-dd")
    9. private Date beginDate;
    10. @DateTimeFormat(pattern = "yyyy-MM-dd")
    11. private Date endDate;
    12. private Integer area;
    13. @Override
    14. public String toString() {
    15. return "QueryVO{" +
    16. "teamName='" + teamName + '\'' +
    17. ", chineseName='" + chineseName + '\'' +
    18. ", coach='" + coach + '\'' +
    19. ", beginDate=" + beginDate +
    20. ", endDate=" + endDate +
    21. ", area=" + area +
    22. '}';
    23. }
    24. public String getTeamName() {
    25. return teamName;
    26. }
    27. public void setTeamName(String teamName) {
    28. this.teamName = teamName;
    29. }
    30. public String getChineseName() {
    31. return chineseName;
    32. }
    33. public void setChineseName(String chineseName) {
    34. this.chineseName = chineseName;
    35. }
    36. public String getCoach() {
    37. return coach;
    38. }
    39. public void setCoach(String coach) {
    40. this.coach = coach;
    41. }
    42. public Date getBeginDate() {
    43. return beginDate;
    44. }
    45. public void setBeginDate(Date beginDate) {
    46. this.beginDate = beginDate;
    47. }
    48. public Date getEndDate() {
    49. return endDate;
    50. }
    51. public void setEndDate(Date endDate) {
    52. this.endDate = endDate;
    53. }
    54. public Integer getArea() {
    55. return area;
    56. }
    57. public void setArea(Integer area) {
    58. this.area = area;
    59. }
    60. }

     这样就可以访问到主页面了:

     方案二:

     在controller中添加注解方法:

    1. @InitBinder
    2. protected void initDateFormatBinder(WebDataBinder binder){
    3. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    4. binder.registerCustomEditor(Date.class,new CustomDateEditor(dateFormat,true));
    5. }

    添加这个方法后,实体类中可不添加注解 

    四、添加操作 

    teamService添加代码:

    1. package com.lxy.service;
    2. import com.github.pagehelper.PageHelper;
    3. import com.github.pagehelper.PageInfo;
    4. import com.lxy.mapper.TeamMapper;
    5. import com.lxy.pojo.Team;
    6. import com.lxy.pojo.TeamExample;
    7. import com.lxy.vo.QueryVO;
    8. import org.springframework.stereotype.Service;
    9. import org.springframework.transaction.annotation.Propagation;
    10. import org.springframework.transaction.annotation.Transactional;
    11. import javax.annotation.Resource;
    12. import java.util.List;
    13. @Service
    14. public class TeamService {
    15. @Resource
    16. private TeamMapper teamMapper;
    17. @Transactional(propagation = Propagation.REQUIRED,readOnly = true)
    18. public PageInfo queryByPage(Integer pageNum, Integer pageSize, QueryVO vo){
    19. TeamExample example = new TeamExample();
    20. //创建条件的容器
    21. TeamExample.Criteria criteria = example.createCriteria();
    22. if (vo!=null){
    23. if (vo.getTeamName()!=null&&!"".equals(vo.getTeamName().trim())){
    24. criteria.andTeamNameLike("%"+vo.getTeamName().trim()+"%");
    25. }
    26. if(vo.getChineseName()!=null && !"".equals(vo.getChineseName().trim()) ){
    27. criteria.andChineseNameLike("%"+vo.getChineseName().trim()+"%");
    28. }
    29. if(vo.getCoach()!=null && !"".equals(vo.getCoach().trim())){
    30. criteria.andCoachLike("%"+vo.getCoach().trim()+"%");
    31. }
    32. if(vo.getBeginDate()!=null){
    33. criteria.andCreateTimeGreaterThanOrEqualTo(vo.getBeginDate());
    34. }
    35. if(vo.getEndDate()!=null){
    36. criteria.andCreateTimeLessThanOrEqualTo(vo.getEndDate());
    37. }
    38. if(vo.getArea()!=null && vo.getArea()!=-1){
    39. criteria.andAreaEqualTo(vo.getArea());
    40. }
    41. }
    42. //分页
    43. PageHelper.startPage(pageNum,pageSize);
    44. List list = teamMapper.selectByExample(example);
    45. return new PageInfo<>(list);
    46. }
    47. //添加操作,再添加一个事务用来回滚
    48. @Transactional(propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
    49. public int addTeam(Team team){
    50. return teamMapper.insertSelective(team);
    51. }
    52. }

    teamController添加代码:

    1. package com.lxy.controller;
    2. import com.github.pagehelper.PageInfo;
    3. import com.lxy.pojo.Team;
    4. import com.lxy.service.TeamService;
    5. import com.lxy.vo.QueryVO;
    6. import com.lxy.vo.ResultVO;
    7. import org.springframework.stereotype.Controller;
    8. import org.springframework.web.bind.annotation.RequestMapping;
    9. import org.springframework.web.bind.annotation.RequestMethod;
    10. import org.springframework.web.bind.annotation.ResponseBody;
    11. import javax.annotation.Resource;
    12. @Controller
    13. @RequestMapping("team")
    14. @ResponseBody
    15. public class TeamController {
    16. @Resource
    17. private TeamService teamService;
    18. @RequestMapping(value = "list",method = RequestMethod.GET)
    19. public ResultVO queryByPage(Integer pageNum, Integer pageSize, QueryVO vo){
    20. if(pageNum==null || pageNum<=0){
    21. pageNum=1;
    22. }
    23. if(pageSize==null || pageSize<=0){
    24. pageSize=5;
    25. }
    26. PageInfo teamPageInfo = teamService.queryByPage(pageNum, pageSize, vo);
    27. return new ResultVO<>(teamPageInfo);
    28. }
    29. //添加操作
    30. @RequestMapping(value = "",method = RequestMethod.POST)
    31. public ResultVO addTeam(Team team){
    32. int i = teamService.addTeam(team);
    33. if (i==1){
    34. return new ResultVO<>();
    35. }
    36. return new ResultVO<>(500,"服务器内部异常,请稍后再试!");
    37. }
    38. }

    五、更新操作

    5.1 更新步骤

    第一步:点击更新按钮时,首先应该根据此条数据的id来返回整条数据,让数据达到一种回显的效果

    第二步:等所有数据都修改之后,再次点击提交时才是真正的更新

    5.1.1 第一步:

    teamService添加代码:

    1. /**
    2. * 根据主键查询
    3. * @param teamId
    4. * @return
    5. */
    6. @Transactional(propagation = Propagation.REQUIRED,readOnly = true)
    7. public Team queryById(Integer teamId){
    8. return teamMapper.selectByPrimaryKey(teamId);
    9. }

    teamController添加代码:

    1. //根据主键查询
    2. @RequestMapping(value = "{id}",method =RequestMethod.GET)
    3. public ResultVO update(@PathVariable("id") Integer teamId){
    4. Team team = teamService.queryById(teamId);
    5. return new ResultVO<>(team);
    6. }

    5.1.2 第二步:

     teamService添加代码:

    1. /**
    2. * 更新 根据主键更新
    3. * @param team
    4. * @return
    5. */
    6. @Transactional(propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
    7. public int updateTeam(Team team){
    8. return teamMapper.updateByPrimaryKeySelective(team);
    9. }

    teamController添加代码:

    1. @RequestMapping(value = "{id}",method = RequestMethod.PUT)
    2. public ResultVO updateTeam(@PathVariable("id") Integer teamId,Team team){
    3. team.setTeamId(teamId);
    4. int i = teamService.updateTeam(team);
    5. if(i==1){
    6. return new ResultVO();
    7. }
    8. return new ResultVO<>(500,"服务器内部异常,请稍后再试!");
    9. }

     六、删除操作

     此删除功能也应该为逻辑删除,即删除时不是数据直接消失,而是数据在显示状态但不能操作。

     teamService添加代码:

    1. /**
    2. * 根据主键删除 逻辑删除
    3. * @param teamId
    4. * @return
    5. */
    6. @Transactional(propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
    7. public int deleteTeam(Integer teamId){
    8. Team team = teamMapper.selectByPrimaryKey(teamId);
    9. team.setIsDel(1);
    10. return teamMapper.updateByPrimaryKeySelective(team);
    11. }

    teamController添加代码:

    1. @RequestMapping(value = "{id}",method = RequestMethod.DELETE)
    2. public ResultVO delete(@PathVariable("id") Integer teamId){
    3. int delete = teamService.deleteTeam(teamId);
    4. if (delete==1){
    5. return new ResultVO<>();
    6. }
    7. return new ResultVO<>(500,"服务器内部异常,请稍后再试!");
    8. }

     七、文件上传

     teamController添加代码:

    1. @RequestMapping(value = "{id}",method = RequestMethod.POST)
    2. public ResultVO uploadLogo(@RequestParam("logo") MultipartFile myFile, HttpServletRequest request,
    3. @PathVariable("id") Integer teamId){
    4. //文件上传到指定位置
    5. String path = request.getServletContext().getRealPath("/img/uploadFile");
    6. //获取原始文件的名称
    7. String originalFilename = myFile.getOriginalFilename();
    8. //定义文件的新名称:随机名称+原有的后缀名
    9. String randomName= UUID.randomUUID().toString().replace("-","");
    10. int index = originalFilename.lastIndexOf(".");
    11. String hz = originalFilename.substring(index);
    12. String logoName=randomName+hz;
    13. int num=0;
    14. try {
    15. myFile.transferTo(new File(path+"/"+logoName));
    16. System.out.println("上传成功!"+path+"/"+logoName);
    17. Team team = new Team();
    18. team.setTeamId(teamId);
    19. team.setTeamLogo(logoName);
    20. num = teamService.updateTeam(team);
    21. if(num==1){
    22. return new ResultVO();
    23. }else {
    24. return new ResultVO<>(500,"服务器内部异常,请稍后再试!");
    25. }
    26. } catch (IOException e) {
    27. e.printStackTrace();
    28. return new ResultVO<>(500,"图片上传出现问题!"+e.getMessage());
    29. }
    30. }

    至此SSM整合完毕,如果你想要此项目来练习一下,请给我一个三连并在下发评论,我会及时联系你给你发前端素材和后端源码,感谢观看!!!

  • 相关阅读:
    16、学习MySQL 正则表达式
    讲一讲VS Code配置GoLang语言开发环境
    Ubuntu下 FTP的搭建配置
    面试官:熟悉Redis?请讲讲Redis缓存穿透、缓存击穿、缓存雪崩有什么区别
    如何使用Python进行机器学习?
    算法书学习笔记
    mysql8.0版本的 utf8mb4 格式数据不能移植到 mysql1.0版本上
    基于ssm操作系统课程网站
    腾讯开源 tRPC:多语言、高性能 RPC 开发框架
    SQL Server事务及隔离级别
  • 原文地址:https://blog.csdn.net/m0_57209427/article/details/128036423