SSM注解式开发项目

1.SSM整合流程

1.1创建工程并提供pom.xml文件依赖及插件(数据表的设计)

 

 项目创建文件截图。

<groupId>com.znzz</groupId>
<artifactId>springmvc_ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<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>

2.SSM整和 

2.1Spring核心配置类

创建SpringConfig配置类

Public class SpringConfig{
//spring核心配置类
@Configuration//设置为配置类
@ComponentScan({"com.znzz.service"})
@PropertySource("classpath:jdbc.properties")//加载数据库配置文件
@Import({JdbcConfig.class,MybatisConfig.class})//加载配置类
//1.开启注解式事务驱动
@EnableTransactionManagement
public class SpringConfig {
}
}

2.2Spring整合Mybatis

(1)创建jdbc.properties数据源文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db1?useSSL=false
jdbc.username=root
jdbc.password=123456

(2)创建JdbcConfig配置类

//spring整合mybatis1
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;
    }
    //2.添加事务管理器
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource){
        DataSourceTransactionManager ds=new DataSourceTransactionManager();
        ds.setDataSource(dataSource);
        return ds;
    }

(3)创建MybatisConfig配置类

public class MybatisConfig {
    //创建sqlSessionFactory对象
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean factoryBean=new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setTypeAliasesPackage("com.znzz.domain");
        return factoryBean;
    }
    //映射扫描
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc=new MapperScannerConfigurer();
        msc.setBasePackage("com.znzz.dao");
        return msc;
    }
}

2.3Spring整合SpringMVC

(1)创建ServletConfig配置类

// web配置类
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
    //web容器启动时,加载SpringConfig和SpringMvcConfig两个配置类,配置类加载各自对应的bean
    //springMvcConfig造出来的容器对象和SpringConfig造出来的容器对象,不是同一个对象。但是SpringMvc容器可以反问Spring容器,反之不可以
    //RootConfig 根配置
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }
    //ServletConfig 应对web的请求处理
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }

    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
    //乱码处理
    @Override
    protected Filter[] getServletFilters(){
        CharacterEncodingFilter filter=new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        return new Filter[]{filter};
    }
}

(2)创建SpringMvcConfig配置类

//SpringMVC配置类
@Configuration//申明为配置类
@ComponentScan("com.znzz.controller")//扫描包
@EnableWebMvc
public class SpringMvcConfig {
}

(3)事务处理开启步骤:在JdbcConfig中写一个事务管理器,在SpringConfig中开启注解式事务驱动,在BookService服务层加载事务

 3.功能模块

3.1实体类Book

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

3.2数据层BookDao

package com.znzz.dao;

import com.znzz.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 {
    //mybatis自动代理快速实现SQL语句的处理   表中的列名       values(book实体类中的属性)
    //insert into tb_book (type,name,description) values(#{type},#{name},#{description}
    @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 Book getById(Integer id);
    @Select("select * from tb_book")
    public List<Book> getAll();

}

3.3业务层BookService

package com.znzz.service;

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

import java.util.List;

@Transactional//3.业务层加载事务
public interface BookService {
    /**
     * 保存
     * @param book
     * @return
     */
    public boolean save(Book book);
    /**
     * 修改
     * @param book
     * @return
     */
    public boolean update(Book book);
    /**
     * 删除
     * @param id
     * @return
     */
    public boolean delete(Integer id);
    /**
     * 按照id取得数据
     * @param id
     * @return
     */
    public Book getById(Integer id);
    /**
     * 得到所有数据
     * @param
     * @return
     */
    public List<Book> getAll();
}

3.4业务层的实现BookServiceImpl

package com.znzz.service.impl;

import com.znzz.dao.BookDao;
import com.znzz.domain.Book;
import com.znzz.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();
    }
}

3.5表现层BookController

public class BookController{
@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();
    }
}

3.6测试类BookServiceTest:测试业务层接口功能

package com.znzz.service;

import com.znzz.config.SpringConfig;
import com.znzz.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  testGetAll(){
        List<Book> books = bookService.getAll();
        System.out.println(books);
    }
}

测试得到数据,运行正常。

3.7表现层路径测试,采用PostMan.这里不过多介绍。

以上是实现SSM注解式开发项目的整个基础流程,对于业务层及表现层的功能测试顺利通过。关于整合SSM项目中的表现层传递给前端的数据封装;如何配置异常处理器;项目异常处理方案放在下一章。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值