栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring+springmvc+maven+mybaties(SSM整合)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring+springmvc+maven+mybaties(SSM整合)

项目框架:

提示:


pom文件

提示:这里描述项目中遇到的问题:




  4.0.0

  org.example
  SSMTest
  1.0-SNAPSHOT
  war

  SSMTest Maven Webapp
  
  http://www.example.com

  
    UTF-8
    1.7
    1.7
  

  
    
      org.springframework
      spring-webmvc
      5.2.10.RELEASE
    
    
      org.springframework
      spring-jdbc
      5.2.10.RELEASE
    
    
      org.springframework
      spring-test
      5.2.10.RELEASE
    
    
      org.mybatis
      mybatis
      3.5.6
    
    
      org.mybatis
      mybatis-spring
      1.3.0
    

    
      mysql
      mysql-connector-java
      5.1.47
    

    
      com.alibaba
      druid
      1.1.16
    

    
      junit
      junit
      4.12
      test
    

    
      javax.servlet
      javax.servlet-api
      3.1.0
      provided
    

    
      com.fasterxml.jackson.core
      jackson-databind
      2.9.0
    

  

  
    
      
        org.apache.tomcat.maven
        tomcat7-maven-plugin
        2.1
        
          80
          /
        
      
    
  




全局配置: com/niujl/config/JdbcConfig.java(JDBC配置)
package com.niujl.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

public class JdbcConfig {

    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    //事物配置
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource){
        DataSourceTransactionManager ds = new DataSourceTransactionManager();
        ds.setDataSource(dataSource);
        return ds;
    }
}


jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_db?useSSL=false
jdbc.username=root
jdbc.password=admin
com/niujl/config/MyBatisConfig.java
package com.niujl.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

public class MyBatisConfig {
    //定义bean,SqlSessionFactoryBean,该类内部用于产生SqlSessionFactory对象
    //该方法主要用于保存数据库配置信息,最重要的是这一句:factoryBean.setDataSource(dataSource);
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setTypeAliasesPackage("com.niujl.domain");
        return factoryBean;
    }

    //定义bean,返回MapperScannerConfigurer对象
    //初始化映射配置文件(原先是xml配置文件写sql,现在是注解写sql)
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.niujl.dao");
        return msc;
    }
}

com/niujl/config/ServletConfig.java(开启servlet服务器时启动)
package com.niujl.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }

    @Override
    protected Class[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

com/niujl/config/SpringConfig.java(Spring入口:配置、扫描、引入)
package com.niujl.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@ComponentScan("com.niujl.service")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class, MyBatisConfig.class})
@EnableTransactionManagement
public class SpringConfig {
}

com/niujl/config/SpringMvcConfig.java(SpringMvc入口:配置、扫描、引入)
package com.niujl.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@ComponentScan({"com.niujl.controller","com.niujl.config"})
@EnableWebMvc
public class SpringMvcConfig {
}

com/niujl/config/SpringMvcSupport.java(配置静态资源,不去拦截)
package com.niujl.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
    //添加为静态资源,不让springMvc去拦截加载bean
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/pages

        Book book = bookService.getById(id);
        Integer code = book != null ? Code.GET_OK:Code.GET_ERR;
        String msg = book != null ? "": "数据查询失败,请重试";
        return new Result(code, book, msg);
    }

    @GetMapping
    public Result getAll() {
        List bookList = bookService.getAll();
        Integer code = bookList != null?Code.GET_OK:Code.GET_ERR;
        String msg = bookList != null ?"":"查询不到全部图书";
        return new Result(code, bookList, msg);
    }
}

com/niujl/controller/Code.java(正确、错误编码)
package com.niujl.controller;

public class Code {
    public static final Integer SAVE_OK = 20011;
    public static final Integer DELETe_OK = 20021;
    public static final Integer UPDATE_OK = 20031;
    public static final Integer GET_OK = 20041;

    public static final Integer SAVE_ERR = 20010;
    public static final Integer DELETE_ERR = 20020;
    public static final Integer UPDATE_ERR = 20030;
    public static final Integer GET_ERR = 20040;

    public static final Integer SYSTEM_ERR = 50001;
    public static final Integer SYSTEM_TIMEOUT_ERR = 50002;
    public static final Integer SYSTEM_UNKNOW_ERR = 59999;
    public static final Integer BUSINESS_ERR = 60002;

}

异常处理过程

com/niujl/exception/BusinessException.java(异常定义的类)
package com.niujl.exception;

public class BusinessException extends RuntimeException{
    private Integer code;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    //message可自定义,是在表现层控制器(路由)里传参的
    public BusinessException(Integer code, String message) {
        super(message);
        this.code = code;
    }

    public BusinessException(Integer code, String message, Throwable cause) {
        super(message, cause);
        this.code = code;
    }
}

com/niujl/exception/SystemException.java(同上)
package com.niujl.exception;

public class SystemException extends RuntimeException{
    private Integer code;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public SystemException(Integer code, String message) {
        super(message);
        this.code = code;
    }

    public SystemException(Integer code, String message, Throwable cause) {
        super(message, cause);
        this.code = code;
    }

}

com/niujl/controller/ProjectExceptionAdvice.java(扫描异常,返回结果)
package com.niujl.controller;

import com.niujl.exception.BusinessException;
import com.niujl.exception.SystemException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class ProjectExceptionAdvice {

//    系统异常
    @ExceptionHandler(SystemException.class)
    public Result doSystemException(SystemException ex){
        System.out.println("doSystemException异常出现!");
        //记录日志
        //发送消息给运维
        //发送邮件给开发人员

        return new Result(ex.getCode(), null, ex.getMessage());
    }

//    业务异常
    @ExceptionHandler(BusinessException.class)
    public Result doBusinessException(BusinessException ex){
        System.out.println("doBusinessException异常出现!");
        //记录日志
        //发送消息给运维
        //发送邮件给开发人员
        return new Result(ex.getCode(), null, ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result doException(Exception ex){
        System.out.println("doException第三类异常出现!");
        //记录日志
        //发送消息给运维
        //发送邮件给开发人员
        return new Result(Code.SYSTEM_UNKNOW_ERR,null,"系统繁忙,请稍后再试!");
    }
}

com/niujl/controller/Result.java(返回结果格式)
package com.niujl.controller;

public class Result {
    private Object data;
    private Integer code;
    private String msg;

    public Result() {
    }

    public Result(Integer code,Object data) {
        this.data = data;
        this.code = code;
    }

    public Result(Integer code, Object data, String msg) {
        this.data = data;
        this.code = code;
        this.msg = msg;
    }



    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}


数据层及实现 com/niujl/domain/Book.java(数据格式)
package com.niujl.domain;

public class Book {
    private Integer id;
    private String type;
    private String name;
    private String description;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", type='" + type + ''' +
                ", name='" + name + ''' +
                ", description='" + description + ''' +
                '}';
    }
}

com/niujl/dao/BookDao.java(接口加实现,使用注解实现)
package com.niujl.dao;

import com.niujl.domain.Book;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.context.annotation.Bean;

import java.util.List;
public interface BookDao {

//    @Insert("insert into tbl_book values(null,#{type}, #{name}, #{description})")
    @Insert("insert into tbl_book (type,name,description) values (#{type}, #{name}, #{description})")
    public int save(Book book);

    @Update("update tbl_book set type= #{type}, name = #{name}, description = #{description} where id = #{id}")
    public int update(Book book);

    @Delete("delete from tbl_book where id = #{id}")
    public int delete(Integer id);

    @Select("select * from tbl_book where id = #{id}")
    public Book getById(Integer id);

    @Select("select * from tbl_book")
    public List getAll();

}


业务层实现 com/niujl/service/BookService.java(业务层接口)
package com.niujl.service;

import com.niujl.domain.Book;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

//类里全部方法开启事务
@Transactional
public interface BookService {

    
    public boolean save(Book book);

    
    public boolean update(Book book);

    
    public boolean delete(Integer id);

    
    public Book getById(Integer id);

    
    public List getAll();
}

com/niujl/service/impl/BookServiceImpl.java(实现接口)
package com.niujl.service.impl;

import com.niujl.dao.BookDao;
import com.niujl.domain.Book;
import com.niujl.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;

    @Override
    public boolean save(Book book) {
        return bookDao.save(book) > 0;
//        return true;
    }

    @Override
    public boolean update(Book book) {
        return bookDao.update(book) > 0;
//        return true;
    }

    @Override
    public boolean delete(Integer id) {
        return bookDao.delete(id) > 0;
//        return true;
    }

    @Override
    public Book getById(Integer id) {

		//业务层模拟异常
        int i = 1/0;

        return bookDao.getById(id);
    }

    @Override
    public List getAll() {
        return bookDao.getAll();
    }
}


测试 src/test/java/com/niujl/service/BookServiceTest.java
package com.niujl.service;

import com.niujl.config.SpringConfig;
import com.niujl.domain.Book;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class BookServiceTest {

    @Autowired
    private BookService bookService;

    @Test
    public void testGetById(){
        Book book = bookService.getById(1);
        System.out.println(book);
    }
    @Test
    public void testGetByAll(){
        List all = bookService.getAll();
        System.out.println(all);
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/987960.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号