博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
springboot整合mybatis(SSM开发环境搭建)
阅读量:6713 次
发布时间:2019-06-25

本文共 14161 字,大约阅读时间需要 47 分钟。

0.项目结构:

 

 

---------------------方法一:使用mybatis官方提供的Spring Boot整合包实现---------------------

 1.application.properties中配置整合mybatis的配置文件、mybatis扫描别名的基本包与数据源

server.port=80logging.level.org.springframework=DEBUG#springboot   mybatis#jiazai mybatis peizhiwenjianmybatis.mapper-locations = classpath:mapper/*Mapper.xmlmybatis.config-location = classpath:mapper/config/sqlMapConfig.xmlmybatis.type-aliases-package = cn.qlq.bean#shujuyuanspring.datasource.driver-class-name= com.mysql.jdbc.Driverspring.datasource.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8spring.datasource.username = rootspring.datasource.password = 123456

 

 

 2.pom.xml加入springboot整合mybatis的jar包与数据库驱动包

4.0.0
cn.qlq
springboot-ssm
0.0.1-SNAPSHOT
war
org.springframework.boot
spring-boot-starter-parent
1.5.2.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-devtools
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.1.1
mysql
mysql-connector-java
5.1.6
junit
junit
4.9
test
javax.servlet
servlet-api
2.5
provided
javax.servlet
jsp-api
2.0
provided
org.apache.maven.plugins
maven-compiler-plugin
3.5.1
1.7
1.7
UTF-8
org.springframework.boot
spring-boot-maven-plugin

 

 

3.mybatis全局配置文件:

sqlMapConfig.xml

 

 

4.编写代码:

(1)User.java

package cn.qlq.bean;import java.io.Serializable;import java.util.Date;public class User implements Serializable{        /**     *      */    private static final long serialVersionUID = 1L;    private Integer id;        private String username;    private Date birthday;    private String sex;    private String address;                public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public Date getBirthday() {        return birthday;    }    public void setBirthday(Date birthday) {        this.birthday = birthday;    }    public String getSex() {        return sex;    }    public void setSex(String sex) {        this.sex = sex;    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getAddress() {        return address;    }    public void setAddress(String address) {        this.address = address;    }        }

 

(2)UserMapper.java  (注意接口上的注解是@mapper,代替之前扫描接口的操作)

package cn.qlq.mapper;import java.util.List;import org.apache.ibatis.annotations.Mapper;import cn.qlq.bean.User;@Mapperpublic interface UserMapper {        public List
findAll();}

 

 

UserMapper.xml

 

 

 

(3)

UserService.java

package cn.qlq.service;import java.util.List;import cn.qlq.bean.User;public interface UserService {        /**     * 根据接口查询所用的用户     */    public List
findAllUser();}

 

 

UserServiceImpl.java

package cn.qlq.service.impl;import java.util.List;import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import cn.qlq.bean.User;import cn.qlq.mapper.UserMapper;import cn.qlq.service.UserService;@Servicepublic class UserServiceImpl implements UserService {        @Autowired    private UserMapper userMapper;            public List
findAllUser() { List
list = userMapper.findAll(); return list; }}

 

 

(4)UserController.java

package cn.qlq.action;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import cn.qlq.bean.User;import cn.qlq.service.UserService;@RestController/**自动返回的是json格式数据***/public class UserController {        @Autowired    private UserService userService;    @RequestMapping("list")    public List
list(){ List
list = userService.findAllUser(); return list; }}

 

注意:@RestController  注解  (自动返回的是json格式数据)

 

 

(5)测试类

MySpringBootApplication.java

package cn.qlq;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cache.annotation.EnableCaching;@SpringBootApplicationpublic class MySpringBootApplication {        public static void main(String[] args) {                //入口运行类        SpringApplication.run(MySpringBootApplication.class, args);            }}

 

 

 

4.启动测试

 

 

 

git源码地址:  

 

---------------方法二:使用mybatis-spring整合的方式,也就是我们传统的方式--------------

这里我们推荐使用第二种,因为这样我们可以很方便的控制Mybatis的各种配置。

首先,创建一个Mybatis的配置类:

代码:

package cn.qlq.config;import javax.sql.DataSource;import org.mybatis.spring.SqlSessionFactoryBean;import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.io.Resource;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.core.io.support.ResourcePatternResolver;@Configuration    public class MyBatisConfig {        @Bean        @ConditionalOnMissingBean //当容器里没有指定的Bean的情况下创建该对象        public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();            // 设置数据源            sqlSessionFactoryBean.setDataSource(dataSource);            // 设置mybatis的主配置文件            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();            Resource mybatisConfigXml = resolver.getResource("classpath:mybatis/SqlMapConfig.xml");            sqlSessionFactoryBean.setConfigLocation(mybatisConfigXml);            // 设置别名包            sqlSessionFactoryBean.setTypeAliasesPackage("cn.qlq.bean");            return sqlSessionFactoryBean;        }    }

 

 

然后,创建Mapper接口的扫描类MapperScannerConfig:

package cn.qlq.config;import org.mybatis.spring.mapper.MapperScannerConfigurer;import org.springframework.boot.autoconfigure.AutoConfigureAfter;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configuration@AutoConfigureAfter(MyBatisConfig.class) //保证在MyBatisConfig实例化之后再实例化该类public class MapperScannerConfig {        // mapper接口的扫描器    @Bean    public MapperScannerConfigurer mapperScannerConfigurer() {        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();        mapperScannerConfigurer.setBasePackage("cn.qlq.mapper");        return mapperScannerConfigurer;    }}

 

 

 

创建一个spring配置类,扫描的包,与读取的资源文件,创建数据源:

package cn.qlq.config;import javax.sql.DataSource;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.PropertySource;import com.jolbox.bonecp.BoneCPDataSource;@Configuration // 通过该注解来表明该类是一个Spring的配置,相当于一个xml文件@ComponentScan(basePackages = "cn.qlq") // 配置扫描包@PropertySource(value = { "classpath:db.properties"}, ignoreResourceNotFound = true)public class SpringConfig {    @Value("${jdbc.url}")    private String jdbcUrl;    @Value("${jdbc.driverClassName}")    private String jdbcDriverClassName;    @Value("${jdbc.username}")    private String jdbcUsername;    @Value("${jdbc.password}")    private String jdbcPassword;    @Bean(destroyMethod = "close")    public DataSource dataSource() {        BoneCPDataSource boneCPDataSource = new BoneCPDataSource();        // 数据库驱动        boneCPDataSource.setDriverClass(jdbcDriverClassName);        // 相应驱动的jdbcUrl        boneCPDataSource.setJdbcUrl(jdbcUrl);        // 数据库的用户名        boneCPDataSource.setUsername(jdbcUsername);        // 数据库的密码        boneCPDataSource.setPassword(jdbcPassword);        // 检查数据库连接池中空闲连接的间隔时间,单位是分,默认值:240,如果要取消则设置为0        boneCPDataSource.setIdleConnectionTestPeriodInMinutes(60);        // 连接池中未使用的链接最大存活时间,单位是分,默认值:60,如果要永远存活设置为0        boneCPDataSource.setIdleMaxAgeInMinutes(30);        // 每个分区最大的连接数        boneCPDataSource.setMaxConnectionsPerPartition(100);        // 每个分区最小的连接数        boneCPDataSource.setMinConnectionsPerPartition(5);        return boneCPDataSource;    }}

 

 

application.properties:

server.port=80logging.level.org.springframework=DEBUG#springboot   mybatis#jiazai mybatis peizhiwenjian#mybatis.mapper-locations = classpath:mapper/*Mapper.xml#mybatis.config-location = classpath:mapper/config/sqlMapConfig.xml#mybatis.type-aliases-package = cn.qlq.bean#shujuyuanspring.datasource.driver-class-name= com.mysql.jdbc.Driverspring.datasource.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8spring.datasource.username = rootspring.datasource.password = 123456

 

 

pom.xml:

4.0.0
cn.qlq
springboot-ssm
0.0.1-SNAPSHOT
war
org.springframework.boot
spring-boot-starter-parent
1.5.2.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-devtools
mysql
mysql-connector-java
5.1.6
org.springframework
spring-tx
4.3.7.RELEASE
junit
junit
4.9
test
javax.servlet
servlet-api
2.5
provided
javax.servlet
jsp-api
2.0
provided
org.mybatis
mybatis
3.2.7
org.mybatis
mybatis-spring
1.2.2
com.jolbox
bonecp-spring
0.8.0.RELEASE
org.springframework
spring-jdbc
org.apache.maven.plugins
maven-compiler-plugin
3.5.1
1.7
1.7
UTF-8
org.springframework.boot
spring-boot-maven-plugin

 

 

2.启动测试:

 

转载地址:http://cwelo.baihongyu.com/

你可能感兴趣的文章
关于C语言判断文件尾问题的探讨
查看>>
poj1243(经典dp)
查看>>
svn仓库转为git仓库
查看>>
跳转到指定的控制器
查看>>
cocoapod升级版本
查看>>
在正式800修改代码
查看>>
AngularJs的UI组件ui-Bootstrap分享(十三)——Progressbar
查看>>
用前序遍历递归构造二叉树
查看>>
JavaScript jQuery bootstrap css ajax
查看>>
组合选择器
查看>>
Understanding Angular’s $apply() and $digest()
查看>>
HTML之列表
查看>>
Global.asax文件说明
查看>>
(十六)SpringBoot之使用 Caching- - EhCache
查看>>
ubuntu制作apt源
查看>>
理解Java常量池
查看>>
JVM调优总结-调优方法
查看>>
微信小程序 watch监听数据变化 类似vue中的watch
查看>>
u检验、t检验、F检验、X2检验 (转)
查看>>
不可不知的Python模块: collections
查看>>