SSM_整合篇

一、整合步骤

1.1 数据表的介绍

team表:

SSM_整合篇_第1张图片

SSM_整合篇_第2张图片

 player表:

SSM_整合篇_第3张图片

SSM_整合篇_第4张图片

1.2 创建maven项目

1.3 pom.xml引入jar依赖



    4.0.0

    com.lxy
    myssm_test
    1.0-SNAPSHOT

    war

    
    
    
        5.2.13.RELEASE
        3.5.6
        1.3.3
        5.1.10
        8.0.23
        1.2.3
        4.0.1
        2.9.6
        1.2.17
        4.12
        11
        11
    
    
        
        
            org.springframework
            spring-webmvc
            ${spring.version}
        
        
            org.springframework
            spring-tx
            ${spring.version}
        
        
            org.springframework
            spring-jdbc
            ${spring.version}
        
        
            org.springframework
            spring-aspects
            ${spring.version}
        
        
        
            commons-fileupload
            commons-fileupload
            1.3.1
        
        
        
            org.mybatis
            mybatis
            ${mybatis.version}
        
        
        
            org.mybatis
            mybatis-spring
            ${mybatis.spring.version}
        
        
        
            com.github.pagehelper
            pagehelper
            ${pagehelper.version}
        
        
        
            mysql
            mysql-connector-java
            ${mysql.version}
        
        
        
            com.alibaba
            druid
            ${druid.version}
        
        
        
            javax.servlet
            javax.servlet-api
            ${servlet-api.version}
            provided
        
        
        
            com.fasterxml.jackson.core
            jackson-databind
            ${jackson.version}
        
        
        
            log4j
            log4j
            ${log4j.version}
        
        
        
            junit
            junit
            ${junit.version}
            test
        
        
            org.springframework
            spring-test
            ${spring.version}
        
        
        
            javax.annotation
            javax.annotation-api
            1.3.2
        
    
    
    
        
            
                src/main/java
                
                    **/*.properties
                    **/*.xml
                
                false
            
        
        
            
            
                org.apache.maven.plugins
                maven-compiler-plugin
                
                    1.8
                    1.8
                    UTF-8
                
            
            
            
                org.apache.tomcat.maven
                tomcat7-maven-plugin
                2.2
                
                    
                    80
                    
                    /
                    UTF-8
                
            
            
            
                org.mybatis.generator
                mybatis-generator-maven-plugin
                1.3.5
                
                    
                    src/main/resources/generatorConfig.xml
                    true
                
                
                    
                        org.mybatis.generator
                        mybatis-generator-core
                        1.3.5
                    
                
            
        
    

1.4 编写Mybatis的配置文件

Mybatis的配置文件mybatis.xml




    
        
    
    

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

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

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

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

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

这里数据库的版本是Mysql8

spring.xml: 




    
    

    
    
    
        
        
        
        
        
    
    
        
        
        
        
        
        
        
        
        
            
                
                
                    
                        
                            reasonable=true
                        
                    
                
            
        
    
    
        
        
    

    
    
    
        
    

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




    
    
    
    
    
        
        
    
    
    
    
    
    
    
    
    
    
    

 1.7 导入静态页面

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

1.8 编写web.xml配置文件



    
        /pages/index.html
    

    
    
        
        contextConfigLocation
        classpath*:spring.xml
    
    
        org.springframework.web.context.ContextLoaderListener
    
    
    
        dispatcherServlet
        org.springframework.web.servlet.DispatcherServlet
        
        
            contextConfigLocation
            classpath*:springmvc.xml
        
        
        1
    
    
    
        dispatcherServlet
        /
    

    
    
        httpMethodFilter
        
            org.springframework.web.filter.HiddenHttpMethodFilter
        
    
    
        httpMethodFilter
        /*
    

    
    
        characterEncodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
        
            encoding
            UTF-8
        
        
        
            forceRequestEncoding
            true
        
        
        
            forceResponseEncoding
            true
        
    
    
        characterEncodingFilter
        /*
    

 1.8 测试

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

SSM_整合篇_第5张图片

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

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





    
    
    
        
        
            
        
        
        
        
        
        
            
        
        
        
            
        
        
        
        
        
        
        
        
        

        
        

2.2运行插件

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

SSM_整合篇_第6张图片

 2.3 测试

package com.lxy.test;

import com.lxy.mapper.TeamMapper;
import com.lxy.pojo.Team;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring.xml"})
public class TestMapper {

    @Resource
    private TeamMapper teamMapper;
    @Test
    public void test01(){
        Team team = teamMapper.selectByPrimaryKey(1001);
        System.out.println(team);
    }
}

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

3.1 业务逻辑层

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

package com.lxy.vo;

import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

public class QueryVO {
    private String teamName;
    private String chineseName;
    private String coach;
    //@DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date beginDate;
    //@DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date endDate;
    private Integer area;

    @Override
    public String toString() {
        return "QueryVO{" +
                "teamName='" + teamName + '\'' +
                ", chineseName='" + chineseName + '\'' +
                ", coach='" + coach + '\'' +
                ", beginDate=" + beginDate +
                ", endDate=" + endDate +
                ", area=" + area +
                '}';
    }

    public String getTeamName() {
        return teamName;
    }

    public void setTeamName(String teamName) {
        this.teamName = teamName;
    }

    public String getChineseName() {
        return chineseName;
    }

    public void setChineseName(String chineseName) {
        this.chineseName = chineseName;
    }

    public String getCoach() {
        return coach;
    }

    public void setCoach(String coach) {
        this.coach = coach;
    }

    public Date getBeginDate() {
        return beginDate;
    }

    public void setBeginDate(Date beginDate) {
        this.beginDate = beginDate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public Integer getArea() {
        return area;
    }

    public void setArea(Integer area) {
        this.area = area;
    }
}

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

package com.lxy.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lxy.mapper.TeamMapper;
import com.lxy.pojo.Team;
import com.lxy.pojo.TeamExample;
import com.lxy.vo.QueryVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class TeamService {
    @Resource
    private TeamMapper teamMapper;

    public PageInfo queryByPage(Integer pageNum, Integer pageSize, QueryVO vo){
        TeamExample example = new TeamExample();
        //创建条件的容器
        TeamExample.Criteria criteria = example.createCriteria();
        if (vo!=null){
            if (vo.getTeamName()!=null&&!"".equals(vo.getTeamName().trim())){
                criteria.andTeamNameLike("%"+vo.getTeamName().trim()+"%");
            }
            if(vo.getChineseName()!=null && !"".equals(vo.getChineseName().trim()) ){
                criteria.andChineseNameLike("%"+vo.getChineseName().trim()+"%");
            }
            if(vo.getCoach()!=null && !"".equals(vo.getCoach().trim())){
                criteria.andCoachLike("%"+vo.getCoach().trim()+"%");
            }
            if(vo.getBeginDate()!=null){
                criteria.andCreateTimeGreaterThanOrEqualTo(vo.getBeginDate());
            }
            if(vo.getEndDate()!=null){
                criteria.andCreateTimeLessThanOrEqualTo(vo.getEndDate());
            }
            if(vo.getArea()!=null && vo.getArea()!=-1){
                criteria.andAreaEqualTo(vo.getArea());
            }
        }
        //分页
        PageHelper.startPage(pageNum,pageSize);
        List list = teamMapper.selectByExample(example);
        return new PageInfo<>(list);
    }
}

 编写测试类:

package com.lxy.test;

import com.github.pagehelper.PageInfo;
import com.lxy.mapper.TeamMapper;
import com.lxy.pojo.Team;
import com.lxy.service.TeamService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring.xml"})
public class TestMapper {

    @Resource
    private TeamMapper teamMapper;

    @Resource
    private TeamService teamService;

    @Test
    public void test02(){
        PageInfo teamPageInfo = teamService.queryByPage(1, 5, null);
        System.out.println(teamPageInfo);
    }
    @Test
    public void test01(){
        Team team = teamMapper.selectByPrimaryKey(1001);
        System.out.println(team);
    }
}

测试结果:

SSM_整合篇_第7张图片3.2 控制器层

3.2.1 返回值的初始写法 

编写controller代码:

package com.lxy.controller;

import com.github.pagehelper.PageInfo;
import com.lxy.pojo.Team;
import com.lxy.service.TeamService;
import com.lxy.vo.QueryVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller
@RequestMapping("team")
@ResponseBody
public class TeamController {

    @Resource
    private TeamService teamService;

    @RequestMapping("list")
    public PageInfo queryByPage(Integer pageNum, Integer pageSize, QueryVO vo){
        if (pageNum==null || pageNum<=0){
            pageNum=1;
        }
        if (pageSize==null || pageSize<=0){
            pageSize=5;
        }
        PageInfo teamPageInfo = teamService.queryByPage(pageNum, pageSize, vo);
        return teamPageInfo;
    }
}

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

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

启动程序来测试一下:

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

3.2.2 返回值的高级写法

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

更改controller代码:

package com.lxy.controller;

import com.github.pagehelper.PageInfo;
import com.lxy.pojo.Team;
import com.lxy.service.TeamService;
import com.lxy.vo.QueryVO;
import com.lxy.vo.ResultVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller
@RequestMapping("team")
@ResponseBody
public class TeamController {

    @Resource
    private TeamService teamService;

    @RequestMapping("list")
    public ResultVO queryByPage(Integer pageNum, Integer pageSize, QueryVO vo){
        if (pageNum==null || pageNum<=0){
            pageNum=1;
        }
        if (pageSize==null || pageSize<=0){
            pageSize=5;
        }
        PageInfo teamPageInfo = teamService.queryByPage(pageNum, pageSize, vo);
        return new ResultVO<>(teamPageInfo);
    }
}

启动程序测试:

SSM_整合篇_第8张图片

3.2.3 日期类型解决方案

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

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

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

 方案一: 

 日期格式化:

package com.lxy.vo;

import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

public class QueryVO {
    private String teamName;
    private String chineseName;
    private String coach;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date beginDate;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date endDate;
    private Integer area;

    @Override
    public String toString() {
        return "QueryVO{" +
                "teamName='" + teamName + '\'' +
                ", chineseName='" + chineseName + '\'' +
                ", coach='" + coach + '\'' +
                ", beginDate=" + beginDate +
                ", endDate=" + endDate +
                ", area=" + area +
                '}';
    }

    public String getTeamName() {
        return teamName;
    }

    public void setTeamName(String teamName) {
        this.teamName = teamName;
    }

    public String getChineseName() {
        return chineseName;
    }

    public void setChineseName(String chineseName) {
        this.chineseName = chineseName;
    }

    public String getCoach() {
        return coach;
    }

    public void setCoach(String coach) {
        this.coach = coach;
    }

    public Date getBeginDate() {
        return beginDate;
    }

    public void setBeginDate(Date beginDate) {
        this.beginDate = beginDate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public Integer getArea() {
        return area;
    }

    public void setArea(Integer area) {
        this.area = area;
    }
}

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

SSM_整合篇_第9张图片

 方案二:

 在controller中添加注解方法:

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

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

四、添加操作 

teamService添加代码:

package com.lxy.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lxy.mapper.TeamMapper;
import com.lxy.pojo.Team;
import com.lxy.pojo.TeamExample;
import com.lxy.vo.QueryVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class TeamService {
    @Resource
    private TeamMapper teamMapper;

    @Transactional(propagation = Propagation.REQUIRED,readOnly = true)
    public PageInfo queryByPage(Integer pageNum, Integer pageSize, QueryVO vo){
        TeamExample example = new TeamExample();
        //创建条件的容器
        TeamExample.Criteria criteria = example.createCriteria();
        if (vo!=null){
            if (vo.getTeamName()!=null&&!"".equals(vo.getTeamName().trim())){
                criteria.andTeamNameLike("%"+vo.getTeamName().trim()+"%");
            }
            if(vo.getChineseName()!=null && !"".equals(vo.getChineseName().trim()) ){
                criteria.andChineseNameLike("%"+vo.getChineseName().trim()+"%");
            }
            if(vo.getCoach()!=null && !"".equals(vo.getCoach().trim())){
                criteria.andCoachLike("%"+vo.getCoach().trim()+"%");
            }
            if(vo.getBeginDate()!=null){
                criteria.andCreateTimeGreaterThanOrEqualTo(vo.getBeginDate());
            }
            if(vo.getEndDate()!=null){
                criteria.andCreateTimeLessThanOrEqualTo(vo.getEndDate());
            }
            if(vo.getArea()!=null && vo.getArea()!=-1){
                criteria.andAreaEqualTo(vo.getArea());
            }
        }
        //分页
        PageHelper.startPage(pageNum,pageSize);
        List list = teamMapper.selectByExample(example);
        return new PageInfo<>(list);
    }

    //添加操作,再添加一个事务用来回滚
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
    public int addTeam(Team team){
        return teamMapper.insertSelective(team);
    }
}

teamController添加代码:

package com.lxy.controller;

import com.github.pagehelper.PageInfo;
import com.lxy.pojo.Team;
import com.lxy.service.TeamService;
import com.lxy.vo.QueryVO;
import com.lxy.vo.ResultVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller
@RequestMapping("team")
@ResponseBody
public class TeamController {

    @Resource
    private TeamService teamService;

    @RequestMapping(value = "list",method = RequestMethod.GET)
    public ResultVO queryByPage(Integer pageNum, Integer pageSize, QueryVO vo){
        if(pageNum==null || pageNum<=0){
            pageNum=1;
        }
        if(pageSize==null || pageSize<=0){
            pageSize=5;
        }
        PageInfo teamPageInfo = teamService.queryByPage(pageNum, pageSize, vo);
        return new ResultVO<>(teamPageInfo);
    }

    //添加操作
    @RequestMapping(value = "",method = RequestMethod.POST)
    public ResultVO addTeam(Team team){
        int i = teamService.addTeam(team);
        if (i==1){
            return new ResultVO<>();
        }
        return new ResultVO<>(500,"服务器内部异常,请稍后再试!");
    }
}

SSM_整合篇_第10张图片

五、更新操作

5.1 更新步骤

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

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

5.1.1 第一步:

teamService添加代码:

    /**
     * 根据主键查询
     * @param teamId
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED,readOnly = true)
    public Team queryById(Integer teamId){
        return teamMapper.selectByPrimaryKey(teamId);
    }

teamController添加代码:

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

5.1.2 第二步:

 teamService添加代码:

    /**
     * 更新 根据主键更新
     * @param team
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
    public int updateTeam(Team team){
        return teamMapper.updateByPrimaryKeySelective(team);
    }

teamController添加代码:

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

 六、删除操作

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

 teamService添加代码:

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

teamController添加代码:

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

SSM_整合篇_第11张图片 七、文件上传

 teamController添加代码:

    @RequestMapping(value = "{id}",method = RequestMethod.POST)
    public ResultVO uploadLogo(@RequestParam("logo") MultipartFile myFile, HttpServletRequest request,
                                     @PathVariable("id") Integer teamId){
        //文件上传到指定位置
        String path = request.getServletContext().getRealPath("/img/uploadFile");
        //获取原始文件的名称
        String originalFilename = myFile.getOriginalFilename();
        //定义文件的新名称:随机名称+原有的后缀名
        String randomName= UUID.randomUUID().toString().replace("-","");
        int index = originalFilename.lastIndexOf(".");
        String hz = originalFilename.substring(index);
        String logoName=randomName+hz;
        int num=0;
        try {
            myFile.transferTo(new File(path+"/"+logoName));
            System.out.println("上传成功!"+path+"/"+logoName);
            Team team = new Team();
            team.setTeamId(teamId);
            team.setTeamLogo(logoName);
            num = teamService.updateTeam(team);
            if(num==1){
                return new ResultVO();
            }else {
                return new ResultVO<>(500,"服务器内部异常,请稍后再试!");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return new ResultVO<>(500,"图片上传出现问题!"+e.getMessage());
        }
    }

SSM_整合篇_第12张图片

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

你可能感兴趣的:(java技术栈,mybatis,spring,java)