学习笔记-Spring-SpringMvc-ssm整合(四)

ssm整合 配置

所谓ssm整合,即整合spring,springmvc,mybatis。

先创建一个maven项目,选择创建webapp模板。

文件目录结构:

再在pom文件导入所需要的各种坐标

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

导入各种坐标要注意坐标间的兼容问题,不同的版本可能不兼容。

先创建配置类:

JdbcConfig主要用于造数据源   DataSource

mybatis连接数据库需配置数据库连接的properties文件,jdbc.properties在resourse目录下:

thesecondcast为数据库名

SpringConfig的注解:

@Configuration:  配置类的注解,使其作为bean交给ioc管理

@ComponentScan:加载SpringConfig控制的bean

@propertySource:加载properties文件

@Import:加载JdbcConfig,MybatisConfig配置类

JdbcConfig类内使用Druid造DataSourse:

package com.example.config;

import javax.sql.DataSource;

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

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

ServletConfig为web容器配置类(加载SpringMvc环境),还是先前的代码:

package com.example.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};          //springMvc容器可以访问spring容器,spring容器不可访问springMvc容器
    }

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

SpringMvcConfig扫描controller包下的文件(设定SpringMvc加载对应的bean),扫描控制器类里面的各种请求方法。

ssm整合 功能模块开发

目录结构新增为:

新添domain中的User类,类中属性与表中属性一致:

新增UserDao接口,用以与数据库进行联络,实现增删改查功能,提供接口给Service层:

package com.example.dao;

import com.example.domain.User;
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 UserDao {


    @Insert("insert into user values (null,#{name},#{age},#{gender},#{phone})")
    public void save(User user);

    @Update("update user set  name=#{name},age=#{age},gender=#{gender},phone=#{phone} where id=#{id}")
    public void update(User user);

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

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

    @Select("select * from user")
    public List<User> getAll();
}

Service接口与实现类调用Dao接口,处理业务,为Controller层提供接口:

package com.example.service;

import com.example.domain.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface UserService {

    /**
     * 保存
     * @param user
     */
    public Boolean save(User user);

    /**
     * 修改
     * @param user
     */
    public Boolean update(User user);

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

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

    /**
     * 查询全部
     * @return
     */
    public List<User> getAll();
}
package com.example.service.impl;

import com.example.dao.UserDao;
import com.example.domain.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {           //提供业务层接口

    @Autowired
    private UserDao userDao;

    @Override
    public Boolean save(User user) {
        userDao.save(user);
        return true;
    }

    @Override
    public Boolean update(User user) {
        userDao.update(user);
        return true;
    }

    @Override
    public Boolean delete(Integer id) {
        userDao.delete(id);
        return true;
    }

    @Override
    public User getById(Integer id) {
        return userDao.getById(id);
    }

    @Override
    public List<User> getAll() {
        return  userDao.getAll();
    }
}

UserController层负责请求转发,接收用户传来的参数,通过调用Service层提供的接口,实现将数据转发给Service层处理。接收Service的返回值,再转发给用户:

package com.example.controller;


import com.example.domain.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController    //@Controller+@ResponseBody
@RequestMapping("/users")
public class UserController {


    @Autowired
    private UserService userService;


    @PostMapping
    public Boolean save(@RequestBody User user) {
        return userService.save(user);
    }

    @PutMapping
    public Boolean update(@RequestBody User user) {
        return  userService.update(user);
    }

    @DeleteMapping("/{id}")
    public Boolean delete(@PathVariable Integer id) {

        return userService.delete(id);
    }

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


    @GetMapping
    public List<User> getAll() {
        return  userService.getAll();
    }
}

ssm整合 接口测试

先使用Junit测试业务层接口:

package com.example;


import com.example.config.SpringConfig;
import com.example.domain.User;
import com.example.service.UserService;
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 UserServiceTest {

    @Autowired
    private UserService userService;
    @Test
    public void testGetbyId(){
        User user = userService.getById(3);
        System.out.println(user);
    }

    @Test
    public void testGetAll(){
        List<User> users = userService.getAll();
        System.out.println(users);
    }
}

两个查询操作均没问题。

再使用postman接口测试表现层接口:

GetAll

GetById:

Put修改数据:

其他就不一一演示了。

最后我们再给Controller的所有操作添加事务:

在JdbcConfig内添加代码

再在Service接口添加注解:

事务即添加完成。

以上内容均学自b站黑马ssm教学视频

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值