基于SpringBoot的SSM整合案例

项目目录:

基于SpringBoot的SSM整合案例_第1张图片

数据库表以及表结构

user表结构

基于SpringBoot的SSM整合案例_第2张图片

user_info表结构

基于SpringBoot的SSM整合案例_第3张图片

基于SpringBoot的SSM整合案例_第4张图片

基于SpringBoot的SSM整合案例_第5张图片

引入依赖

父模块依赖:

        org.springframework.boot
        spring-boot-starter-parent
        2.2.12.RELEASE
    
中的版本管理

        2.2.2
        
        1.2.11
        
        5.1.38
依赖:

        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.boot
            spring-boot-starter-jdbc
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            ${mybatis.spring.version}
        
        
            com.alibaba
            druid-spring-boot-starter
            ${druid.version}
        
        
            mysql
            mysql-connector-java
            ${mysql.version}
        
        
            org.projectlombok
            lombok
        

添加配置文件

application.xml
spring:
  profiles:
    active: dev
server:
  port: 8088
  servlet:
    context-path: /ssm
mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/**/*Mapper.xml
application-dev.xml
# 数据源配置
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: root
    druid:
      # 初始连接数
      initialSize: 5
      # 最小连接池数量
      minIdle: 10
      # 最大连接池数量
      maxActive: 20
      # 配置获取连接等待超时的时间
      maxWait: 60000
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      timeBetweenEvictionRunsMillis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      minEvictableIdleTimeMillis: 300000
      # 配置一个连接在池中最大生存的时间,单位是毫秒
      maxEvictableIdleTimeMillis: 900000
      # 配置检测连接是否有效
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      webStatFilter:
        enabled: true
      statViewServlet:
        enabled: true
        # 设置白名单,不填则允许所有访问
        allow:
        # 指定访问druid监控页面的请求映射路径
        # 开发中一般通过:服务器映射路径/druid/index,来访问监控页面
        url-pattern: /druid/*
        # 监控默认是可以直接访问的
        # 如果有以下配置,那么访问监控页面时会跳转到,控制台管理页面进行登录控制
        # 控制台管理用户名和密码
        login-username: druid
        login-password: druid
      filter:
        stat:
          enabled: true
          # 慢SQL记录(控制慢查询sql语句显示为红色提醒)
          log-slow-sql: true
          slow-sql-millis: 1000
          merge-sql: true
        wall:
          config:
            multi-statement-allow: true
全局配置文件mybatis-config.xml



    
        
    
MybatisConfig配置类(用于扫描mapper接口包)
@Configuration
@MapperScan("com.yaorange.mapper")
public class MyBatisConfig {
}

公共类包

返回结果以及常量
public interface CommonConstant {
    /**
     * {@code 500 Server Error} (HTTP/1.0 - RFC 1945)
     */
    Integer SC_INTERNAL_SERVER_ERROR_500 = 500;
    /**
     * {@code 200 OK} (HTTP/1.0 - RFC 1945)
     */
    Integer SC_OK_200 = 2000;

    String ERROR_MSG = "操作失败";
    String OK_MSG = "操作成功";
    String LOGIN_ERROR_MSG = "用户名或密码错误";
}
@Data
public class PageInfo {
    /**
     * 当前页
     */
    private int pageNum;
    /**
     * 每页的数量
     */
    private int pageSize;
    /**
     * 总记录数
     */
    protected long total;
    /**
     * 结果集
     */
    protected List list;
    /**
     * 总页数
     */
    private int pages;
}

数据层

entity实体类
@Data
public class User implements Serializable {
    /**
     * 用户Id
     */
    private Integer userId;

    /**
     * 用户名
     */
    private String userName;

    /**
     * 用户状态
     */
    private Integer userState;

    /**
     * 用户详情id
     */
    private UserInfo userInfo;

    private static final long serialVersionUID = 1L;
}
@Data
public class UserInfo implements Serializable {
    /**
     * 用户详情id
     */
    private Integer infoId;

    /**
     * 家庭住址
     */
    private String address;

    private static final long serialVersionUID = 1L;
}

mapper接口
public interface UserMapper {
    /**查询用户列表*/
    List selectList();

    /**查询总记录数*/
    int countTotal();

    /**分页查询数据*/
    List selectPage(@Param("start") int start,
                          @Param("pageSize") Integer pageSize);
    /**通过Id查询用户信息*/
    User selectUserById(Integer userId);

    /**添加用户信息*/
    int insert(User user);

    /**批量删除用户*/
    int deleteUsers(Integer[] ids);
}

mapper.xml





    
            
            
            
    
    
        
            
            
        
    

    
        user_id,user_name,user_state,
        user_info_id
    
    
        INSERT INTO `ssm`.`user`( `user_name`, `user_state`, `user_info_id`)
        VALUES ( #{userName}, #{userState}, #{userInfo.infoId});

    
    
        update user set user.user_state=1
        
            user_id in
            
                #{e}
            
        

    
    
    
    
    


业务层

业务层接口
public interface UserService {
    /**查询用户列表数据*/
    List selectList();

    /**分页查询用户数据*/
    PageInfo page(Integer pageNum, Integer pageSize);

    User selectUserById(Integer userId);

    int insertUser(User user);

    int deleteUsers(Integer[] ids);
}
业务层实现类
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public List selectList() {
        return userMapper.selectList();
    }

    @Override
    public PageInfo page(Integer pageNum, Integer pageSize) {
        //查询总条数
        int total=userMapper.countTotal();
        //总页数
        int pages=total%pageSize==0?total/pageSize:total/pageSize+1;
        //起始页
        int start=(pageNum-1)*pageSize;
        List userList=userMapper.selectPage(start,pageSize);
        PageInfo userPageInfo = new PageInfo<>();
        userPageInfo.setPageNum(pageNum);
        userPageInfo.setPageSize(pageSize);
        userPageInfo.setTotal(total);
        userPageInfo.setList(userList);
        userPageInfo.setPages(pages);
        return userPageInfo;
    }

    @Override
    public User selectUserById(Integer userId) {
        return userMapper.selectUserById(userId);
    }

    @Override
    public int insertUser(User user) {
        return userMapper.insert(user);
    }

    @Override
    public int deleteUsers(Integer[] ids) {
        return userMapper.deleteUsers(ids);
    }

}

控制层

@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping(value="/list",method = RequestMethod.GET)
    public Result list(){
       List userList =userService.selectList();
       return Result.ok(userList);
    }
    @RequestMapping(value = "/page",method = RequestMethod.GET)
    public Result page(@RequestParam(defaultValue = "1") Integer pageNum,
                          @RequestParam(defaultValue = "3") Integer pageSize){
        PageInfo userPageInfo=userService.page(pageNum,pageSize);
        return Result.ok(userPageInfo);
    }

    @RequestMapping(method = RequestMethod.GET)
    public Result selectUserById(@RequestParam Integer userId){
        User user=userService.selectUserById(userId);
        return Result.ok(user);
    }
    @RequestMapping(value="/add",method = RequestMethod.POST)
    public Result addUser(@RequestBody  User user){
      int row=userService.insertUser(user);
      if(row>0){
          return Result.ok(CommonConstant.OK_MSG);
      }
      return Result.error(CommonConstant.ERROR_MSG);
    }
    @RequestMapping(value="/batchDelete",method=RequestMethod.POST)
    public Result deleteUsers(@RequestBody Integer ids[]){
        int rows=userService.deleteUsers(ids);
        if(rows>0){
            return Result.ok(CommonConstant.OK_MSG);
        }
        return Result.error(CommonConstant.ERROR_MSG);
    }
}

数据层测试代码

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceImplTest {

    @Autowired
    private UserService userService;
    @Test
    public void selectList() {
        List users = userService.selectList();
        users.stream().forEach(System.out::println);
    }

    @Test
    public void page() {
        PageInfo pageList = userService.page(1, 10);
        System.out.println(pageList);
    }

    @Test
    public void selectUserById() {
        User user = userService.selectUserById(2);
        System.out.println(user);
    }

    @Test
    public void insertUser() {
        User user = new User();
        user.setUserName("陈六");
        user.setUserState(1);
        UserInfo userInfo = new UserInfo();
        userInfo.setInfoId(2);
        user.setUserInfo(userInfo);

        int i = userService.insertUser(user);
        System.out.println(i);
    }

    @Test
    public void deleteUsers() {
        Integer[] ids={1,5};
        int i = userService.deleteUsers(ids);
        System.out.println(i);
    }
}

Postman测试结果

批量删除

基于SpringBoot的SSM整合案例_第6张图片

查询用户列表

基于SpringBoot的SSM整合案例_第7张图片

根据id查用户

基于SpringBoot的SSM整合案例_第8张图片

添加用户

基于SpringBoot的SSM整合案例_第9张图片

你可能感兴趣的:(spring,boot,java,spring)