Springboot+Mybatis+Springmvc的案例(参考学习)

以往的ssm框架整合通常有两种形式,一种是xml形式,一种是注解形式,不管是xml还是注解,基本都会有一大堆xml标签配置,其中有很多重复性的。springboot带给我们的恰恰是“零配置”,"零配置"不等于什么也不配置,只是说相对于传统的ssm框架的xml配置或是注解配置,要少的多。作为常规的来说,一个ssm框架整合,拿maven来说,首先在src/main/resource下加入jdbc.properties,spring-mvc.xml,spring-mybatis.xml等,还有要再web.xml配置监听类和前端控制器,同时还要配置对应的加载spring-mvc和spring-mybatis的路径。

而springboot的话,则不需要,只需在一个叫application.properties或者是叫application.yml配置数据源和解析jsp的即可。

参考网址:https://www.ggdoc.com

上述网址有许多参考文档可参考

参考网址:https://projects.spring.io/spring-boot/  该网址为springboot官网,官网虽然是英文的,但是可以通过第三方翻译过来,不过最好的话还是懂点英文。建议学习一门新技术,最好还是参考其官方网址和文档,那里是最详细的,其他什么博客之类的,可以作为参考学习过程中解决问题的利器。学习过程中是不可能不遇到问题的。

最好还是那句话,在不懂该技术之前,可以通过百度百科了解,或者其他博客写个入门实例,不过最好在此以后参考官网

就我个人的看法,必须和最好掌握spring+mybatis+springmvc等相关知识,同时也接触过ssm框架的xml配置和ssm框架的注解配置。这样方便比较学习,同时也有利于深入学习等。

不多说了,下面开始整合实例教程

一、准备环境

window10 jdk8 eclipe maven

二、pom文件

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

<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.0modelVersion>

  <groupId>cn.springbootgroupId>

  <artifactId>springbootartifactId>

  <version>0.0.1-SNAPSHOTversion>

  <packaging>warpackaging>

    <parent>

        <groupId>org.springframework.bootgroupId>

        <artifactId>spring-boot-starter-parentartifactId>

        <version>1.2.5.RELEASEversion>

    parent>

    <properties>

        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>

        <java.version>1.8java.version>

    properties>

    <dependencies>

        

        

        <dependency>

            <groupId>org.springframework.bootgroupId>

            <artifactId>spring-boot-starter-webartifactId>

        dependency>

     

        

        <dependency>

            <groupId>org.springframework.bootgroupId>

            <artifactId>spring-boot-starter-jdbcartifactId>

        dependency>

        

        <dependency>

            <groupId>org.springframework.bootgroupId>

            <artifactId>spring-boot-starter-actuatorartifactId>

        dependency>

        

        <dependency>

            <groupId>org.mybatisgroupId>

            <artifactId>mybatis-springartifactId>

            <version>1.2.2version>

        dependency>

        <dependency>

            <groupId>org.mybatisgroupId>

            <artifactId>mybatisartifactId>

            <version>3.2.8version>

        dependency>

        

        <dependency>

            <groupId>org.apache.tomcatgroupId>

            <artifactId>tomcat-jdbcartifactId>

        dependency>

        <dependency>

            <groupId>mysqlgroupId>

            <artifactId>mysql-connector-javaartifactId>

        dependency>

        

        <dependency>

            <groupId>com.alibabagroupId>

            <artifactId>fastjsonartifactId>

            <version>1.1.43version>

        dependency>

        

        <dependency>

            <groupId>com.mangofactorygroupId>

            <artifactId>swagger-springmvcartifactId>

            <version>0.9.5version>

        dependency>

         

        

        <dependency>

            <groupId>javax.servletgroupId>

            <artifactId>jstlartifactId>

        dependency>

        <dependency>

 

            <groupId>org.springframework.bootgroupId>

 

            <artifactId>spring-boot-starter-tomcatartifactId>

 

            <scope>providedscope>

 

        dependency>

 

        <dependency>

 

            <groupId>org.apache.tomcat.embedgroupId>

 

            <artifactId>tomcat-embed-jasperartifactId>

 

            <scope>providedscope>

 

        dependency>

        

    dependencies>

    <build>

        <plugins>

            <plugin>

                <groupId>org.springframework.bootgroupId>

                <artifactId>spring-boot-maven-pluginartifactId>

            plugin>

            <plugin>

                <groupId>org.apache.maven.pluginsgroupId>

                <artifactId>maven-compiler-pluginartifactId>

     

                <configuration>

                    <source>1.8source>

                    <target>1.8target>

                configuration>

            plugin>

 

        plugins>

    build>

    <repositories>

        <repository>

            <id>spring-milestoneid>

            <url>https://repo.spring.io/libs-releaseurl>

        repository>

    repositories>

    <pluginRepositories>

        <pluginRepository>

            <id>spring-milestoneid>

            <url>https://repo.spring.io/libs-releaseurl>

        pluginRepository>

pluginRepositories>

  

  

 project>

 三、准备数据库和表

复制代码

库名为 springboot

    CREATE TABLE `t_user` (  
      `id` INT(11) NOT NULL,  
      `username` VARCHAR(255) DEFAULT NULL,  
      `password` VARCHAR(255) DEFAULT NULL,  
      `email` VARCHAR(255) DEFAULT NULL,  
      `useable` INT(20) DEFAULT NULL,  
      `addtime` DATETIME DEFAULT NULL,  
      `logintime` DATETIME DEFAULT NULL,  
      `loginip` VARCHAR(255) DEFAULT NULL,  
      PRIMARY KEY  (`id`)  
    ) ENGINE=INNODB DEFAULT CHARSET=utf8;  

复制代码

四、在src/main/resource下新建application.properties文件

复制代码

spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=1234
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.view.prefix=/WEB-INF/templates/
spring.view.suffix=.jsp

复制代码

 

五、建立实体类和对应的mapper接口相关

1.建立实体

复制代码

    package com.sam.project.mvc.model;  
      
    /**  
     * @ClassName: User  
     * @Description: 实体模型  
     */  
    public class User {  
        private Integer id;  
      
        private String username;  
      
        private String password;  
      
        private String email;  
      
        /**  
         * 是否可用(0禁用,1可用)  
         */  
        private Integer useable;  
      
        /**  
         * 创建时间  
         */  
        private String addtime;  
      
        /**  
         * 登陆时间  
         */  
        private String logintime;  
      
        /**  
         * 登陆IP  
         */  
        private String loginip;  
      
        /**  
         * @return id  
         */  
        public Integer getId() {  
            return id;  
        }  
      
        /**  
         * @param id  
         */  
        public void setId(Integer id) {  
            this.id = id;  
        }  
      
        /**  
         * @return username  
         */  
        public String getUsername() {  
            return username;  
        }  
      
        /**  
         * @param username  
         */  
        public void setUsername(String username) {  
            this.username = username;  
        }  
      
        /**  
         * @return password  
         */  
        public String getPassword() {  
            return password;  
        }  
      
        /**  
         * @param password  
         */  
        public void setPassword(String password) {  
            this.password = password;  
        }  
      
        /**  
         * @return email  
         */  
        public String getEmail() {  
            return email;  
        }  
      
        /**  
         * @param email  
         */  
        public void setEmail(String email) {  
            this.email = email;  
        }  
      
        /**  
         * 获取是否可用(0禁用,1可用)  
         *  
         * @return useable - 是否可用(0禁用,1可用)  
         */  
        public Integer getUseable() {  
            return useable;  
        }  
      
        /**  
         * 设置是否可用(0禁用,1可用)  
         *  
         * @param useable  
         *            是否可用(0禁用,1可用)  
         */  
        public void setUseable(Integer useable) {  
            this.useable = useable;  
        }  
      
        /**  
         * 获取创建时间  
         *  
         * @return addtime - 创建时间  
         */  
        public String getAddtime() {  
            return addtime;  
        }  
      
        /**  
         * 设置创建时间  
         *  
         * @param addtime  
         *            创建时间  
         */  
        public void setAddtime(String addtime) {  
            this.addtime = addtime;  
        }  
      
        /**  
         * 获取登陆时间  
         *  
         * @return logintime - 登陆时间  
         */  
        public String getLogintime() {  
            return logintime;  
        }  
      
        /**  
         * 设置登陆时间  
         *  
         * @param logintime  
         *            登陆时间  
         */  
        public void setLogintime(String logintime) {  
            this.logintime = logintime;  
        }  
      
        /**  
         * 获取登陆IP  
         *  
         * @return loginip - 登陆IP  
         */  
        public String getLoginip() {  
            return loginip;  
        }  
      
        /**  
         * 设置登陆IP  
         *  
         * @param loginip  
         *            登陆IP  
         */  
        public void setLoginip(String loginip) {  
            this.loginip = loginip;  
        }  
    }  

复制代码

2.建立对应的mapper接口

复制代码

package com.sam.project.mvc.mapper;  
  
import java.util.List;  
  
import com.sam.project.mvc.model.User;  
  
/**  
 * @ClassName: UserMapper   
 * @Description: mybites数据查询接口  
 */  
public interface UserMapper {  
  
    List queryList();  
  
    void save(User user);  
  
    void batchDelete(Integer[] ids);  
  
    void update(User user);  
  
} 

复制代码

3.建立mapper对应的xml文件

在src/main/resource下新建mapper文件夹

在该文件下下新建UserMapper.xml

复制代码

  
  
      
          
          
          
          
          
            insert into t_user(username, password, email, useable, addtime)  
            values(#{username}, #{password}, #{email}, #{useable}, now())  
          
          
          
            update t_user set password = #{password}, email = #{email}, useable = #{useable} where id = #{id}  
          
          
          
            delete from t_user where id in  
              
                #{item}  
              
          
          
          
      

复制代码

 

六、建立业务接口和对应的Controller及其相关返回json数据工具类

1.UserService业务接口

复制代码

package com.sam.project.mvc.service;  
      
    import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sam.project.mvc.common.AjaxResult;
import com.sam.project.mvc.mapper.UserMapper;
import com.sam.project.mvc.model.User;  
      
    @Service  
    public class UserService {  
      
        @Autowired  
        private UserMapper userMapper;  
          
        public AjaxResult queryList() {  
            List list = userMapper.queryList();  
            return new AjaxResult(list);  
        }  
      
        public AjaxResult save(User user) {  
            user.setUsername("user" + System.currentTimeMillis());  
            user.setPassword("123456");  
            user.setEmail("user" + System.currentTimeMillis());  
            user.setUseable(1);  
            userMapper.save(user);  
            return new AjaxResult();  
        }  
      
        public AjaxResult batchDelete(Integer[] ids) {  
            userMapper.batchDelete(ids);  
            return new AjaxResult();  
        }  
      
        public AjaxResult update(User user) {  
            userMapper.update(user);  
            return new AjaxResult();  
        }  
      
    }  

复制代码

 

2.controller

复制代码

    package com.sam.project.mvc.controller;  
      
    import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sam.project.mvc.common.AjaxResult;
import com.sam.project.mvc.model.User;
import com.sam.project.mvc.service.UserService;  
      
    /**  
     * @ClassName: UserController   
     * @Description: 用户Controller  
     */  
    @Controller  
    public class UserController {  
      
        @Autowired  
        private UserService userService;  
          
        @ResponseBody  
        @RequestMapping("/queryList")  
        public AjaxResult queryList(){  
            return userService.queryList();  
        }  
      
        @ResponseBody  
        @RequestMapping("/addUser")  
        public AjaxResult addUser(User user){  
            return userService.save(user);  
        }  
          
        @ResponseBody  
        @RequestMapping("/delUser")   
        public AjaxResult delUser(Integer[] ids){  
            return userService.batchDelete(ids);  
        }  
          
        @ResponseBody  
        @RequestMapping("/updateUser")  
        public AjaxResult updateUser(User user){  
            return userService.update(user);  
        }  
        
        @RequestMapping("/hello")
        public String hello(ModelMap map) {
            map.put("title", "你好");
            return "index";
        }
      
    }  

复制代码

3.工具类

复制代码

    package com.sam.project.mvc.common;  
      
    /**  
     * @ClassName: AjaxResult   
     * @Description: 封装返回数据  
     */  
    public class AjaxResult {  
      
        private int retcode = 1;  
        private String retmsg = "操作成功";  
        private Object data;  
          
        public AjaxResult(int retcode, String retmsg, Object data){  
            this.retcode = retcode;  
            this.retmsg = retmsg;  
            this.data = data;  
        }  
          
        public AjaxResult(int retcode, String retmsg){  
            this.retcode = retcode;  
            this.retmsg = retmsg;  
        }  
          
        public AjaxResult(Object data){  
            this.retmsg = "查询成功";  
            this.data = data;  
        }  
          
        public AjaxResult(int retcode){  
            this.retcode = retcode;  
            this.retmsg = "操作失败";  
        }  
          
        public AjaxResult(String retmsg){  
            this.retcode = 0;  
            this.retmsg = retmsg;  
        }  
          
        public AjaxResult(){  
              
        }  
      
        public int getRetcode() {  
            return retcode;  
        }  
        public void setRetcode(int retcode) {  
            this.retcode = retcode;  
        }  
        public String getRetmsg() {  
            return retmsg;  
        }  
        public void setRetmsg(String retmsg) {  
            this.retmsg = retmsg;  
        }  
        public Object getData() {  
            return data;  
        }  
        public void setData(Object data) {  
            this.data = data;  
        }  
      
        @Override  
        public String toString() {  
            return "AjaxResult [retcode=" + retcode + ", retmsg=" + retmsg + ", data=" + data + "]";  
        }  
          
    }  

复制代码

七、springboot启动类

复制代码

package com.sam.project.mvc;
 
import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
 
@EnableAutoConfiguration
@SpringBootApplication
@ComponentScan
@MapperScan("com.sam.project.mvc.mapper")
public class Application extends SpringBootServletInitializer {
    private static Logger logger = Logger.getLogger(Application.class);
 
    //DataSource配置
    @Bean
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource dataSource() {
        return new org.apache.tomcat.jdbc.pool.DataSource();
    }
 
    //提供SqlSeesion
    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
 
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
 
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
 
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mapper/*.xml"));
 
        return sqlSessionFactoryBean.getObject();
    }
 
    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
 
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }
    /**
     * Main Start
     */
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        logger.info("============= SpringBoot Start Success =============");
    }
 
}

复制代码

 

八、在WEB-INF下新建templates文件夹并在该文件夹下新建index.jsp文件

复制代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




你好


${title }

复制代码

九、启动Application类

启动成功,控制台会显示如下内容

Springboot+Mybatis+Springmvc的案例(参考学习)_第1张图片

 

十、在浏览器输入localhost:8080/hello

Springboot+Mybatis+Springmvc的案例(参考学习)_第2张图片

 

 上述就是springboot+springmvc+mybatis整合实例

你可能感兴趣的:(JAVA,JAVA架构)