首页 > 其他分享 >SSM整合

SSM整合

时间:2023-03-20 18:58:16浏览次数:37  
标签:return public SSM 整合 org import com id

整合流程

1、创建工程

  pom.xnl文件中导入相应的坐标

<packaging>war</packaging>
    <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>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </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>80</port>
                    <path>/</path>
                </configuration>
            </plugin>

        </plugins>
    </build>

  

   刷新

  打开项目结构,配置相关web文件夹

  

  工程创建完成

2、SSM整合

  创建各级包结构

  

Spring整合MyBatis:

  在resource文件夹下创建数据库连接配置文件 jdbc.properties

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

  在config包下创建JdbcConfig配置文件与MyBatisConfig配置文件  

  创建SpringConfig配置文件

package com.cqupt.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;

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

}

   完善JdbcConfig配置文件

package com.cqupt.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

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;
    }
}

  完善MyBatisConfig配置文件

package com.cqupt.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 sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setTypeAliasesPackage("com.cqupt.domain");
        return factoryBean;
    }
    
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.cqupt.dao");
        return msc;
    }
}

整合SpringMVC:

  创建ServletConfig,SpringMvcConfig配置文件

package com.cqupt.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[]{"/"};
    }
}

  SpringMvcConfig配置:

package com.cqupt.config;

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

@Configuration
@ComponentScan("com.cqupt.controller")
@EnableWebMvc
public class SpringMvcConfig {
    
}

3、功能模块

创建表:

drop table if exists tb_book;


create table tb_book(
    id int PRIMARY KEY AUTO_INCREMENT,
    type varchar(16),
    name varchar(32),
    description varchar(64)
);

在domain包下创建封装对象:

package com.cqupt.domain;

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

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", type='" + type + '\'' +
                ", name='" + name + '\'' +
                ", description='" + 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;
    }
}

在dao包下创建接口BookDao,service包下创建BookService与impl包并在impl包下创建实现类BookServiceImpl,在controller包下创建BookController

完善BookDao接口:

package com.cqupt.dao;

import com.cqupt.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;

public interface BookDao {

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

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

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

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

    @Select("select * from tb_book")
    public void getAll();
}

完善BookService接口:(注意增删改操作需要返回boolean类型)

package com.cqupt.service;

import com.cqupt.domain.Book;

public interface BookService {

    /**
     * 保存
     * @param book
     * @return
     */
    public boolean save(Book book);

    /**
     * 修改
     * @param book
     * @return
     */
    public boolean update(Book book);

    /**
     * 根据id删除
     * @param id
     * @return
     */
    public boolean delete(Integer id);

    /**
     * 根据id查询
     * @param id
     * @return
     */
    public void getById(Integer id);

    /**
     * 查询全部
     * @return
     */
    public void getAll();

}

完善BookServiceImpl实现类:

package com.cqupt.service.impl;

import com.cqupt.dao.BookDao;
import com.cqupt.domain.Book;
import com.cqupt.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;

    public boolean save(Book book) {
        bookDao.save(book);
        return true;
    }

    public boolean update(Book book) {
        bookDao.update(book);
        return true;
    }

    public boolean delete(Integer id) {
        bookDao.delete(id);
        return true;
    }

    public Book getById(Integer id) {
        return bookDao.getById(id);
    }

    public List<Book> getAll() {
        return bookDao.getAll();
    }
}

完善BookController:

package com.cqupt.controller;

import com.cqupt.domain.Book;
import com.cqupt.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 boolean save(@RequestBody Book book) {
        return bookService.save(book);
    }

    @PutMapping
    public boolean update(@RequestBody Book book) {
        return bookService.update(book);
    }

    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Integer id) {
        return bookService.delete(id);
    }

    @GetMapping("/{id}")
    public Book getById(@PathVariable Integer id) {
        return bookService.getById(id);
    }

    @GetMapping
    public List<Book> getAll() {
        return bookService.getAll();
    }

}



4、功能测试

(1)Junit

 

package com.cqupt.service;


import com.cqupt.config.SpringConfig;
import com.cqupt.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(2);
        System.out.println(book);
    }

    @Test
    public void testGetAll(){
        List<Book> books = bookService.getAll();
        System.out.println(books);
    }

}

(2)Tomcat本地服务器测试

 

 

5、添加事务处理

在SpringConfig中开启注解式事务驱动  添加注解

@EnableTransactionManagement   // 开启注解式事务驱动

 

在JdbcConfig中添加事务管理器

/**
     * 事务管理器
     * @param dataSource
     * @return
     */
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource){
        DataSourceTransactionManager ds = new DataSourceTransactionManager();
        ds.setDataSource(dataSource );
        return ds;
    }

 

在业务层接口BookService中添加注解

@Transactional  // 事务管理注解

6、其他

若有表单数据要提交, 还可以在ServletConfig中添加中文乱码处理

标签:return,public,SSM,整合,org,import,com,id
From: https://www.cnblogs.com/1873cy/p/17236753.html

相关文章

  • MongoDB简介及SpringBoot整合
    一、概述MongoDB中的记录是一个文档,它是一个数据结构组成字段和值对。MongoDB文档类似于JSON。对象。字段的值可能包括其他文档、数组、和文档数组:数据库(Database):和关系型......
  • SSM整合 - 简单项目功能实现
    SSM整合练习创建数据库CREATEDATABASE`ssmbuild`;USE`ssmbuild`;DROPTABLEIFEXISTS`books`;CREATETABLE`books`( `bookID`INT(10)NOTNULLAUTO_INCRE......
  • 【MyBatis框架】mybatis和spring整合
    spring和mybatis整合1.整合思路需要spring通过单例方式管理SqlSessionFactory。spring和mybatis整合生成代理对象,使用SqlSessionFactory创建Sql......
  • 【RabbitMQ消息中间件】12.RabbitMQ结合SSM框架-编写仓储系统
    了解了RabbitMQ的基本知识和几大队列模式,以及Spring-Rabbit开源工程的基本原理后,我们动手来实现在实际工作开发中需要与SSM框架结合使用的工程场景。该......
  • 【SpringMVC整合MyBatis】springmvc拦截器-定义和配置
    拦截器1.拦截定义定义拦截器,实现HandlerInterceptor接口。接口中提供三个方法。packagecn.edu.hpu.ssm.interceptor;importjavax.servlet.http......
  • 【SpringMVC整合MyBatis】springmvc对RESTful支持
    1.什么是RESTfulRESTful架构,就是目前最流行的一种互联网软件架构。它结构清晰、符合标准、易于理解、扩展方便,所以正得到越来越多网站的采用。RES......
  • Spring Study-lesson13-整合Mybatis-2-2023-3-19
    进一步优化将UserMapperImpl进行优化,继承系统提供的一个父类:extendsSqlSessionDaoSupport  新建一个:UserMapperImpl2类 继承父类,实现UserMapper接口。简化成一行......
  • Spring Study-lesson13-整合Mybatis-1-2023-3-19
    在配置前要加载依赖以及build (pom.xml中添加各种依赖)以及连接数据库<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"......
  • SSM
    SSM框架SSM=Spring+SpringMVC+mybatisSSH=Spring+struct2+HibernateSpring一个轻量级、非入侵的控制反转(IOC)和面向切面(AOP)容器框架雏形是interface21框架框......
  • 2023-Q1 公众号内容全部整合到 Github 啦
    项目地址:https://github.com/duanbiaowu/go-examples-for-beginners......