目录
概述
- ,mybatis
- ,druid
壹: spring 整合
- ,jdbc.properties
- ,mybatis-config.xml
二: java 代码
- ,mapper
- ,service
3, 测试
贰: springboot 整合
- ,pom.xml
- ,application.YAML(resources 下)
3,druid 配置
4,mapper
5, 测试
作者有话
概述
本文分别讲述了 spring 与 springboot 是怎么整合 mybatis 与 druid 数据源的? 如果你只是想实现其中一种, 那你就不要把他们的配置过程搞混了.
1,mybatis
MyBatis 本是 apache 的一个开源项目 iBatis, 2010 年这个项目由 apache software foundation 迁移到了 google code, 并且改名为 MyBatis .2013 年 11 月迁移到 GitHub.
MyBatis 是一款优秀的持久层框架, 它支持定制化 SQL, 存储过程以及高级映射. MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集. MyBatis 可以使用简单的 xml 或注解来配置和映射原生信息, 将接口和 Java 的 POJOs(Plain Ordinary Java Object, 普通的 Java 对象) 映射成数据库中的记录.
在国内以及韩国等地 mybatis 的普及率还是很高的. 所以 mybatis 是绝对值得学习的.
2,druid
Druid 提供了一个高效, 功能强大, 可扩展性好的数据库连接池, druid 还有自己的数据访问监听系统, 你的系统数据调用实时状况你都一通过 druid 来查看.
@
壹: spring 整合
在整合 mybatis 之前, 我们首先需要明确的是, 我们需要哪些文件分别拿来干嘛的.
1,pom.xml
-- maven 用于引入依赖的
2,jdbc.properties
-- 配置 mybatis 的数据源
3,mybatis-config.xml
-- 配置 mybatis 参数
一: 文件结构
我们可以看淡我的整个的项目结构就是这样的, 这里使用的是 maven 管理项目, 直接建立 maven 项目即可, 不懂 maven 的安装与配置的可以见我另一篇博文 maven 的安装与配置, 配置好后, 直接在新建项目里选择 maven 即可.
注: 我的 mybatis-config.xml 直接就是放在 spring-config.xml, 归根到地, 他们都是 spring 的配置文件, 只是命名不同而已.
二: 配置文件
1,pom.xml
pom.xml 文件, 有了这个文件之后, 我们不需要像以前一样去找 jar 包, 找到还不一定兼容, maven 项目里, 你直接在你的 pom.xml 文件里写相关依赖, 他就会自动导入, jar 包也会自动下载好, 下面就是我们整合 mybatis 所需要的的相关依赖.
- <!-- 数据库 start-->
- <!-- 引入 jdbc 与 mysql 依赖 -->
- <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-jdbc</artifactId>
- <version>5.1.5.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>MySQL</groupId>
- <artifactId>MySQL-connector-java</artifactId>
- <version>5.0.8</version>
- </dependency>
- <!-- 引入 druid 数据源 -->
- <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- <version>1.1.8</version>
- </dependency>
- <!-- mybatis-->
- <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
- <dependency>
- <groupId>org.mybatis</groupId>
- <artifactId>mybatis</artifactId>
- <version>3.4.6</version>
- </dependency>
- <!-- spring 整合 mybatis -->
- <dependency>
- <groupId>org.mybatis</groupId>
- <artifactId>mybatis-spring</artifactId>
- <version>1.3.0</version>
- </dependency>
- <!-- 数据库 end-->
- 2,jdbc.properties
这个文件主要用于存放我们 mybatis 连接的数据库参数, 依次为驱动, url, 用户名, 密码参数, 你只需要换成你自己的就好了, 设置好之后, 我们需要下一个配置文件来加载.
- jdbc.driverClassName=com.MySQL.jdbc.Driver
- jdbc.url=jdbc:MySQL://localhost:3306/world?characterEncoding=UTF-8
- jdbc.username=root
- jdbc.password=qwer1234
- 3,mybatis-config.xml
这时, 你会疑问, 咦, 上面的文件结构图中没有这个文件啊?
我的 mybatis-config.xml 直接就是放在 spring-config.xml, 归根到地, 他们都是 spring 的配置文件, 只是命名不同而已. 当然, 也可以单独配置一个, 只需要在启动的时候加载他就可以了.
整合 druid 数据源, 就在这个文件里配置即可.
- <!-- 这个是加载下面的 mapper 与 service 注入到容器中, 这样你才能使用, 注意你自己的包名 -->
- <context:annotation-config/>
- <context:component-scan base-package="com.lomtom"/>
- <!-- 配置 读取 properties 文件 jdbc.properties -->
- <context:property-placeholder location="classpath:jdbc.properties" />
- <!-- <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">-->
- <!-- <property name="location" value="classpath:jdbc.properties"/>-->
- <!-- </bean>-->
- <!-- 配置 数据源 整合 druid-->
- <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
- <property name="driverClassName" value="${jdbc.driverClassName}" />
- <property name="url" value="${jdbc.url}" />
- <property name="username" value="${jdbc.username}" />
- <property name="password" value="${jdbc.password}" />
- </bean>
- <!-- spring 和 MyBatis 完美整合, 不需要 mybatis 的配置映射文件 -->
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
- <property name="dataSource" ref="dataSource"/>
- <property name="mapperLocations" value="classpath:com/lomtom/mapper/*.java"/>
- </bean>
- <!-- DAO 接口所在包名, Spring 会自动查找其下的类 -->
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
- <property name="basePackage" value="com.lomtom.mapper" />
- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
- </bean>
二: java 代码
1,mapper
在 mybatis 里, 支持两种写法, 一种是注解版, 一种是 xml 版, 这里推荐使用注解版.
mybatis 我使用的是注解版, 注解版简单. 如果使用 xml 版, 需要配置 maven 的静态资源访问.
- package com.lomtom.mapper;
- import com.lomtom.model.User;
- import org.apache.ibatis.annotations.*;
- /**
- * User: lomtom
- * Date: 2020/3/2
- * Time: 16:45
- */
- @Mapper
- public interface UserInfoMapper {
- @Select("select * from user where username = #{username} and password = #{password}")
- User login(@Param("username") String username,@Param("password") String password);
- }
- 2,service
一般来说, 我们为了规范, 还是建一个 service 层. 这里是实现 service 接口, 你还需要自己写 UserInfoService 接口, 加上 login(); 函数即可, 不是很难, 就不板述了.
- package com.lomtom.service;
- import com.lomtom.mapper.UserInfoMapper;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- /**
- * User: lomtom
- * Date: 2020/3/2
- * Time: 17:21
- */
- @Service
- public class UserInfoServiceImpl implements UserInfoService {
- @Autowired
- UserInfoMapper userInfoMapper;
- @Override
- public boolean login(String username, String password) {
- return userInfoMapper.login(username, password) != null;
- }
- }
3, 测试
我使用的是 spring 测试单元测试的, 需要在 pom.xml 引入 JUNIT 依赖, 当然, 你也可以直接写一个 main 函数调用.
最后的结果就不展示了, 他无非就是一句登陆成功, 或者登陆失败.
- import com.lomtom.model.HelloWorld;
- import com.lomtom.service.UserInfoService;
- import org.junit.Before;
- import org.junit.Test;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- /**
- * User: lomtom
- * Date: 2020/3/2
- * Time: 19:45
- */
- // 测试类
- public class test {
- private ApplicationContext context;
- @Before
- public void setUp() throws Exception {
- // 加载配置文件
- context = new ClassPathXmlApplicationContext("spring-config.xml");
- }
- @Test
- public void Test2(){
- UserInfoService userInfoService = context.getBean(UserInfoService.class);
- boolean flag = userInfoService.login("admin","123456");
- if (flag){
- System.out.println("登录成功....");
- }
- else{
- System.out.println("登陆失败...");
- }
- }
- }
参考:
spring 与 mybatis 四种整合方法
贰: springboot 整合
相对于 spring,springboot 的整合就简单的多, 因为在 springboot 里, 很多都是自动配置的, 相当于就是对 spring 的再一次封装, 所以在 springboot 里, 很多东西就变得简单很多.
相比 spring, 我们不需要配置麻烦的 spring 配置 xml 文件, 只需要在 application.YAML 文件中配置即可. 当然, pom.xml 时 maven 所需要的, 所以他也是必不可少的.
建立项目的时候, 选择 spring initializr 就可以快速建立一个 springboot 项目, 当然如果你想自己配置, 那我也是无法阻拦的.
1,pom.xml
springboot 与 spring 引入 mybatis 所需依赖, 是不同的, 所以你最好还是复制这里的, 这里我也是吸取了教训的. 哈哈哈
- <!-- 引入 jdbc 与 mysql 依赖 -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-jdbc</artifactId>
- </dependency>
- <dependency>
- <groupId>MySQL</groupId>
- <artifactId>MySQL-connector-java</artifactId>
- </dependency>
- <!-- 引入 druid 数据源 -->
- <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- <version>1.1.8</version>
- </dependency>
- <!-- 日志打印 -->
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <version>1.2.17</version>
- </dependency>
- <!-- mybatis-->
- <dependency>
- <groupId>org.mybatis.spring.boot</groupId>
- <artifactId>mybatis-spring-boot-starter</artifactId>
- <version>1.3.1</version>
- </dependency>
- 2,application.YAML(resources 下)
与 spring 不同的是, 在 springboot 里, 不需要建很多的配置文件, 你所有的配置参数全部卸载这里面即可.
在 springboot 里面, 配置文件有两种, 一种是 properties, 另一种是 YAML, 两种语法有点不同, 不过都可以作为 springboot 的配置文件,
- spring:
- datasource:
- username: root
- password: qwer1234
- url: jdbc:MySQL://localhost:3306/world?serverTimezone=UTC&characterEncoding=utf-8
- # 不写 driver-class-name 则自动分配
- # driver-class-name: com.MySQL.cj.jdbc.Driver
- # 配置 druid 数据源
- type: com.alibaba.druid.pool.DruidDataSource
- mybatis:
- #注解版与 xml 版不能共同使用
- ## 指定全局配置的路径 (xml 版配置)
- # config-location: classpath::mybatis/mybatis-config.xml
- ## 指定 sql 映射文件的位置 (xml 版配置)
- # mapper-locations: classpath:mybatis/mapper/*.xml
- configuration:
- # 开启驼峰命名法
- map-Underscore-to-camel-case: true
- logging:
- # 开启 com.lomtom.blog.mapper 包下所有的日志 (在调用时)
- level:
- com.lomtom.myblog1.mapper: debug
3,druid 配置
虽然说在 springboot 里面配置数据源, 但是如果我们想要通过网页端访问的话, 需要配置以下内容, 我们就可以通过访问 druid 的来查看 web 的数据状态.
访问地址: http://localhost:8080/druid, 然后输入账号密码就可以访问.
- package com.lomtom.myblog1.config;
- import com.alibaba.druid.pool.DruidDataSource;
- import com.alibaba.druid.support.http.StatViewServlet;
- import com.alibaba.druid.support.http.WebStatFilter;
- import org.springframework.boot.context.properties.ConfigurationProperties;
- import org.springframework.boot.Web.servlet.FilterRegistrationBean;
- import org.springframework.boot.Web.servlet.ServletRegistrationBean;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import javax.sql.DataSource;
- import java.util.Arrays;
- import java.util.HashMap;
- import java.util.Map;
- /**
- * User: lomtom
- * Date: 2020/1/4
- * Time: 21:09
- */
- @Configuration
- public class DruidConfig {
- @ConfigurationProperties(prefix = "spring.datasource")
- @Bean
- public DataSource druid(){
- return new DruidDataSource();
- }
- // 设置 druid 监控
- //1, 设置管理后台的 servlet
- @Bean
- public ServletRegistrationBean statViewServlet(){
- ServletRegistrationBean registrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
- Map<String,String> initParams=new HashMap<>();
- initParams.put("loginUsername","admin");
- initParams.put("loginPassword","admin");
- initParams.put("allow","");
- // initParams.put("deny","");
- registrationBean.setInitParameters(initParams);
- return registrationBean;
- }
- //2, 设置 Web 的监控 filter
- @Bean
- public FilterRegistrationBean webStatFilter(){
- FilterRegistrationBean registrationBean = new FilterRegistrationBean();
- registrationBean.setFilter(new WebStatFilter());
- Map<String,String> initParams=new HashMap<>();
- initParams.put("exclusion","*.js,*.CSS,/druid/*");
- registrationBean.setInitParameters(initParams);
- // 添加过滤规则
- registrationBean.setUrlPatterns(Arrays.asList("/*"));
- return registrationBean;
- }
- }
访问
http://localhost: 端口名 / druid
4,mapper
在 spring 里面, 还要配置文件进行包扫面, 而在 springboot 里面直接加 @Mapper 注解即可, springboot 会自动注册的. 然后直接调用即可.
- import com.lomtom.myblog1.entity.User;
- import org.apache.ibatis.annotations.*;
- import java.util.List;
- /**
- * User: lomtom
- * Date: 2020/1/30
- * Time: 17:49
- */
- /**
- * 用户的 mapper 类
- */
- @Mapper
- public interface UserMapper {
- @Select("select * from user where userName=#{username} or email=#{username}")
- User getUserByUsername(String username);
- }
5, 测试
在 spring boot 里, 在启动的时候不需要手动配置加载文件, 所有的一切, 他都会自动配置完成, 你只管调用就可以了.
当然, 最后的结果就不展示了, 他无非就是一句登陆成功, 或者登陆失败.
- package com.lomtom.myblog1;
- import com.lomtom.myblog1.mapper.UserMapper;
- import org.junit.jupiter.API.Test;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.context.SpringBootTest;
- @SpringBootTest
- class Myblog1ApplicationTests {
- @Autowired
- UserMapper userMapper;
- @Test
- void contextLoads() {
- boolean flag = userMapper.login("admin","123456");
- if (flag){
- System.out.println("登录成功....");
- }
- else{
- System.out.println("登陆失败...");
- }
- }
- }
作者有话
本文主要介绍了 spring 与 springboot 分别怎么整合 mybatis 的, 相信你看了之后, 如果你还是初学者, 那么问题是免不了的, 但是谁不是这么过来的呢, 你唯一能做的就是发现问题 - 找到问题 - 解决问题, 当然, 如果你在配置过程中有问题, 笔者还是很乐意为你解答的.
而谈及 spring 与 spring boot,spring boot 就是 spring 的拓展, 他主要消除了 spring 复杂繁多的 xml 配置文件, 实现极大程度的自动化配置, 所以看到我们在整合 mybatis 时, 配置变得相当简单, 当然, 最为笔者的建议, 你要是会 spring boot, 一定要明白他其中的自动配置原理, 然后再去回顾 spring 时, 你就会惊讶的发现, 哦~, 原来他是这样的. 很多东西就会豁然开朗.
来源: https://www.cnblogs.com/lomtom/p/12528264.html