基于SpringBoot的SSM整合案例

项目目录:

数据库表以及表结构

user表结构

user_info表结构

引入依赖

父模块依赖:
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.12.RELEASE</version>
    </parent>
<properties>中的版本管理
<!--mybatis版本-->
        <mybatis.spring.version>2.2.2</mybatis.spring.version>
        <!--Druid版本-->
        <druid.version>1.2.11</druid.version>
        <!--mysql版本-->
        <mysql.version>5.1.38</mysql.version>
<dependences>依赖:
<!--应用程序的web起步依赖,包含了构建web应用程序所需的基本组件和依赖-->
        <!--使用该依赖可以快速启动一个基于SpringMVC的应用程序-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--添加测试依赖,该依赖用于在SpringBoot应用程序中进行单元测试和继承测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis.spring.version}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>${druid.version}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

添加配置文件

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
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
</configuration>
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<T> {
    /**
     * 当前页
     */
    private int pageNum;
    /**
     * 每页的数量
     */
    private int pageSize;
    /**
     * 总记录数
     */
    protected long total;
    /**
     * 结果集
     */
    protected List<T> 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<User> selectList();

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

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

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

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

mapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yaorange.mapper.UserMapper">

    <resultMap id="BaseResultMap" type="com.yaorange.entity.User">
            <id property="userId" column="user_id" jdbcType="INTEGER"/>
            <result property="userName" column="user_name" jdbcType="VARCHAR"/>
            <result property="userState" column="user_state" jdbcType="VARCHAR"/>
    </resultMap>
    <resultMap id="User_UserInfo" type="com.yaorange.entity.User" extends="BaseResultMap">
        <association property="userInfo" javaType="com.yaorange.entity.UserInfo">
            <id property="infoId" column="user_info_id" jdbcType="INTEGER"/>
            <result property="address" column="address" jdbcType="VARCHAR"/>
        </association>
    </resultMap>

    <sql id="Base_Column_List">
        user_id,user_name,user_state,
        user_info_id
    </sql>
    <insert id="insert" parameterType="com.yaorange.entity.User">
        INSERT INTO `ssm`.`user`( `user_name`, `user_state`, `user_info_id`)
        VALUES ( #{userName}, #{userState}, #{userInfo.infoId});

    </insert>
    <delete id="deleteUsers">
        update user set user.user_state=1
        <where>
            user_id in
            <foreach collection="array" separator="," open="(" close=")" item="e">
                #{e}
            </foreach>
        </where>

    </delete>
    <select id="selectList" resultMap="User_UserInfo">
        SELECT
            u.user_id,
            u.user_name,
            u.user_state,
            u.user_info_id,
            i.address
        FROM
            user AS u left join
            user_info AS i
            on u.user_info_id=i.info_id
        where u.user_state=0
    </select>
    <select id="countTotal" resultType="java.lang.Integer">
        select Count(*) from user where user_state=0
    </select>
    <select id="selectPage" resultMap="User_UserInfo">
        SELECT
            u.user_id,
            u.user_name,
            u.user_state,
            u.user_info_id,
            i.address
        FROM
            user AS u left join
            user_info AS i
            on u.user_info_id=i.info_id
        where u.user_state=0
        limit #{start},#{pageSize}
    </select>
    <select id="selectUserById" resultMap="User_UserInfo">
        SELECT
            u.user_id,
            u.user_name,
            u.user_state,
            u.user_info_id,
            i.address
        FROM
            user AS u left join
            user_info AS i
            on u.user_info_id=i.info_id
        where u.user_state=0
          and u.user_id=#{userId}
    </select>

</mapper>

业务层

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

    /**分页查询用户数据*/
    PageInfo<User> 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<User> selectList() {
        return userMapper.selectList();
    }

    @Override
    public PageInfo<User> 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<User> userList=userMapper.selectPage(start,pageSize);
        PageInfo<User> 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<User> 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<User> 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<User> users = userService.selectList();
        users.stream().forEach(System.out::println);
    }

    @Test
    public void page() {
        PageInfo<User> 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测试结果

批量删除

查询用户列表

根据id查用户

添加用户