Java教程

SSM框架整合

本文主要是介绍SSM框架整合,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

SSM框架整合

Config

  • JdbcConfig

package com.yang.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 dtm = new DataSourceTransactionManager();
        dtm.setDataSource(dataSource);
        return dtm;
    }
}
  • MybatisConfig

package com.yang.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
    public SqlSessionFactoryBean sessionFactoryBean(DataSource dataSource){
        SqlSessionFactoryBean sfb = new SqlSessionFactoryBean();
        sfb.setDataSource(dataSource);
        sfb.setTypeAliasesPackage("com.yang.domain");
        return sfb;
    }
​
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.yang.dao");
        return msc;
    }
}
​
  • SpringConfig

package com.yang.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.yang.service")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MybatisConfig.class})
@EnableTransactionManagement
public class SpringConfig {
}
  • SpringMvcConfig

package com.yang.config;
​
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
​
​
@Configuration
@ComponentScan("com.yang.controller","com.yang.config")
@EnableWebMvc
public class SpringMvcConfig {
}
​
  • ServletConfig

package com.yang.config;
​
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
​
import javax.servlet.Filter;
​
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }
​
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{ServletConfig.class};
    }
​
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
​
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
        encodingFilter.setEncoding("UTF-8");
        return new Filter[]{encodingFilter};
    }
}
​
  • SpringMvcSupportConfig

package com.yang.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 SpringMvcSupportConfig extends WebMvcConfigurationSupport {
​
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
        registry.addResourceHandler("/js/**").addResourceLocations("/js/");
        registry.addResourceHandler("/css/**").addResourceLocations("/css/");
        registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
    }
}

 

controller

  • BookController

package com.yang.controller;
​
import com.yang.domain.Book;
import com.yang.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
​
import java.util.List;
​
@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;
​
    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean flag = bookService.save(book);
        return new Result(flag, flag ? Code.SAVE_OK:Code.SAVE_ERR);
    }
​
    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean flag = bookService.update(book);
        return new Result(flag, flag ? Code.UPDATE_OK:Code.UPDATE_ERR);
​
    }
​
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag = bookService.delete(id);
        return new Result(flag, flag ? Code.DELETE_OK:Code.DELETE_ERR);
    }
​
    @GetMapping("/{id}")
    public Result select(@PathVariable Integer id) {
        Book book = bookService.select(id);
        Integer code = book !=null ?Code.GET_OK:Code.GET_ERR;
        String msg = book !=null ? "" :"数据查询失败,请重试!";
        return new Result(book,code,msg);
    }
​
    @GetMapping
    public Result selectAll() {
        List<Book> bookList = bookService.selectAll();
        Integer code = bookList !=null ?Code.GET_OK:Code.GET_ERR;
        String msg = bookList !=null ? "" :"数据查询失败,请重试!";
        return new Result(bookList,code,msg);
    }
​
}
​
  • Code

package com.yang.controller;
​
public class Code {
    public static final Integer SAVE_OK = 20011;
    public static final Integer UPDATE_OK = 20011;
    public static final Integer DELETE_OK = 20011;
    public static final Integer GET_OK = 20011;
​
​
    public static final Integer SAVE_ERR = 20010;
    public static final Integer UPDATE_ERR = 20010;
    public static final Integer DELETE_ERR = 20010;
    public static final Integer GET_ERR = 20010;
}
​
  • Result

package com.yang.controller;
​
public class Result {
    private Object data;
    private Integer code;
    private String msg;
​
    public Result() {
    }
​
    public Result(Object data, Integer code) {
        this.data = data;
        this.code = code;
    }
​
    public Result(Object data, Integer code, 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;
    }
​
}
​

dao

  • BookDao

package com.yang.dao;
​
import com.yang.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 java.util.List;
​
public interface BookDao {
    @Insert("insert into td_book values(null,#{type},#{name},#{description})")
    int save(Book book);
    @Update("update td_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")
    int update(Book book);
    @Delete("delete from td_book where id = #{id}")
    int delete(Integer id);
    @Select("select * from td_book where id = #{id}")
    Book select(Integer id);
    @Select("select * from td_book")
    List<Book> selectAll();
}
​

domain

  • Book

package com.yang.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 + '\'' +
                '}';
    }
}
​

service

  • BookService

package com.yang.service;
​
import com.yang.domain.Book;
import org.springframework.transaction.annotation.Transactional;
​
import java.util.List;
@Transactional
public interface BookService {
    /**
     * 保存
     * @param book
     * @return
     */
    boolean save(Book book);
​
    /**
     * 更新
     * @param book
     * @return
     */
    boolean update(Book book);
​
    /**
     * 删除
     * @param id
     * @return
     */
    boolean delete(Integer id);
​
    /**
     * 单个查询
     * @param id
     * @return
     */
    Book select(Integer id);
​
    /**
     * 查询所有
     * @return
     */
    List<Book> selectAll();
}
​
  • BookServiceImpl

package com.yang.service.impl;
​
import com.yang.dao.BookDao;
import com.yang.domain.Book;
import com.yang.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;
    }
​
    @Override
    public boolean update(Book book) {
        return bookDao.update(book) > 0;
    }
​
    @Override
    public boolean delete(Integer id) {
        return bookDao.delete(id) > 0;
    }
​
    @Override
    public Book select(Integer id) {
        return bookDao.select(id);
    }
​
    @Override
    public List<Book> selectAll() {
        return bookDao.selectAll();
    }
}
​

resource

  • jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_db?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root

test

  • BookServiceTest

package com.yang.spring;
​
import com.yang.config.SpringConfig;
import com.yang.domain.Book;
import com.yang.service.BookService;
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 select(){
        Book book = bookService.select(2);
        System.out.println(book);
    }
    @Test
    public void selectAll(){
        List<Book> bookList = bookService.selectAll();
        System.out.println(bookList);
    }
}

pom.xml

<?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>org.example</groupId>
    <artifactId>springSSM-result</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
​
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.45</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.0</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.1</version>
                <configuration>
                    <port>8080</port>
                    <path>/</path>
                    <uriEncoding>UTF-8</uriEncoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
 

 

这篇关于SSM框架整合的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!