1. 程式人生 > >【SpringBoot】整合SSM框架

【SpringBoot】整合SSM框架

學習Spring Boot框架,想必已經感受到該框架帶來的快感,接下來教你如何快速搭建Spring、SpringMvc、Mybatis框架整合。

1.專案構建
這裡寫圖片描述

2.sql檔案

/*
MySQL Backup
Source Server Version: 5.7.13
Source Database: springboot
Date: 2018/3/14 10:28:39
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
--  Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL COMMENT '主鍵', `name` varchar(20) DEFAULT NULL, `birthday` date DEFAULT NULL COMMENT '生日', `address` varchar(256) DEFAULT NULL COMMENT '地址', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ----------------------------
-- Records -- ---------------------------- INSERT INTO `user` VALUES ('1','張三','1994-10-20','杭州市'), ('2','李四','1996-02-19','上海市');

3.pom檔案

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation
="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <!-- 起步依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

4.application.properties檔案

#database 資料來源
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#tomcat埠
server.port=8080

#整合mybatis 
#起別名,省略寫mybatis的xml中的resultType的全路徑
mybatis.mapper-locations = classpath:mapper/*Mapper.xml
#掃描(配置xml模式使用)
mybatis.type-aliases-package=com.example.pojo

5.mybatis的對映檔案UserMapper.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.example.mapper.IUserMapper"> 
    <resultMap type="User" id="UserList">
        <result column="id" property="id" />
        <result column="name" property="name" />
        <result column="birthday" property="birthday" />
        <result column="address" property="address" />
    </resultMap>

    <select id="queryAllUser" resultMap="UserList">
        SELECT * FROM user
    </select>   

    <delete id="deleteUser" parameterType="int">
        DELETE FROM user WHERE id = #{id}
    </delete>
</mapper>

6.資料互動層Controller

@RestController
@EnableAutoConfiguration
public class IndexController {

    @Autowired
    private IUserService userService;

    /**
     * 整合SSM框架
     */
    @RequestMapping("/ssm")
    public List<User> findAllUser() throws Exception{
        return userService.queryAllUser();
    }

    @RequestMapping(value = "/delete/{id}",method = RequestMethod.GET)
    public void findAllUser(@PathVariable Integer id) throws Exception{
        userService.deleteUser(id);
    }


    /**
     * 返回基本格式JSON格式資料
     * @return
     */
    @RequestMapping(value="/index",produces="text/plain;charset=UTF-8")
    public String index(){
        return "hello spring boot";
    }

    /**
     * 返回POJO物件
     * @return
     */
    @RequestMapping("/pojo")
    public User showUser(){
        User user = new User();
        user.setId(1);
        user.setName("張三");
        user.setBirthday("1990-02-20");
        user.setAddress("武當山");

        return user;
    }

    /**
     * 返回Map集合物件
     */
    @RequestMapping("/map")
    public Map<String, Object> showMap(){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("username", "張三丰");
        map.put("gender", "男");
        map.put("username", "趙敏");
        map.put("gender", "女");
        return map;
    } 

    /**
     * 返回List集合物件
     */
    @RequestMapping("/list")
    public List<User> showList(){
        List<User> list = new ArrayList<User>();
        User u1 = new User();
        u1.setId(1);
        u1.setName("張三");
        u1.setAddress("武當山");
        u1.setBirthday("1990-02-20");

        User u2 = new User();
        u2.setId(2);
        u2.setName("李四");
        u2.setAddress("上海市");
        u2.setBirthday("1990-02-21");

        list.add(u1);
        list.add(u2);

        return list;
    } 
}

7.業務邏輯層Service

public interface IUserService {

    List<User> queryAllUser() throws Exception;

    void deleteUser(Integer id) throws Exception;
}

@Service
public class UserServiceImpl implements IUserService{

    @Autowired
    private IUserMapper mapper;

    @Override
    public List<User> queryAllUser() throws Exception {
        return mapper.queryAllUser();
    }

    @Override
    public void deleteUser(Integer id) throws Exception {
        mapper.deleteUser(id);
    }

}

8.資料持久層及實體Bean

//@Mapper //宣告是一個Mapper,與DemoApplication中的@MapperScan二選一寫上即可
public interface IUserMapper {

    List<User> queryAllUser() throws Exception;

    void deleteUser(Integer id) throws Exception;
}

public class User implements Serializable {

    private Integer id;
    private String name;
    private String birthday;
    private String address;
    //省略getXxx()、setXxx()
}

9.入口類

@MapperScan("com.example.mapper")
@SpringBootApplication
@EnableTransactionManagement//啟註解事務管理,等同於xml配置方式的 <tx:annotation-driven />
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

執行結果
這裡寫圖片描述