Spring整合Mybatis、junit纯注解

如何创建一个Spring项目

错误问题

不知道什么原因,大概是依赖版本不兼容、java版本不对的问题,折磨了好久就是搞不成。

主要原因看pom.xml配置

pom.xml配置

java版本

由于是跟着22年黑马视频做的,java版本换成了jdk-11,用21以上不行,其他没试过。

<properties><maven.compiler.source>11</maven.compiler.source><maven.compiler.target>11</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

Project Structure设置

依赖

需要修改的下面几个

<?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>SpringDemo</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>11</maven.compiler.source><maven.compiler.target>11</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.10.RELEASE</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.16</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.6</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.26</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.2.10.RELEASE</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.0.6</version></dependency><!-- 添加logback-classic依赖 --><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-classic</artifactId><version>1.2.3</version></dependency><!-- 添加logback-core依赖 --><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-core</artifactId><version>1.2.3</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.2.10.RELEASE</version></dependency></dependencies>
</project>

文件结构

下面只介绍用上的

数据库

create database mybatis;
use mybatis;
create table user
(id       int auto_incrementprimary key,username varchar(20) null,password varchar(20) null,gender   char        null,addr     varchar(30) null
);

application.properties

把mybatis换成自己数据库名即可

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false
jdbc.username=root
jdbc.password=root

MybatisConfig

package com.example.config;import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;import javax.sql.DataSource;public class MybatisConfig {@Beanpublic SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();sqlSessionFactoryBean.setTypeAliasesPackage("com.example.domain");sqlSessionFactoryBean.setDataSource(dataSource);return sqlSessionFactoryBean;}@Beanpublic MapperScannerConfigurer mapperScannerConfigurer() {MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();mapperScannerConfigurer.setBasePackage("com.example.dao");return mapperScannerConfigurer;}
}

JdbcConfig

package com.example.config;import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;import javax.sql.DataSource;// 从 application.properties 文件中加载配置属性
@PropertySource("application.properties")
public class JdbcConfig {// 注入数据库驱动类名@Value("${jdbc.driver}")private String driver;// 注入数据库连接 URL@Value("${jdbc.url}")private String url;// 注入数据库用户名@Value("${jdbc.username}")private String username;// 注入数据库密码@Value("${jdbc.password}")private String password;/*** 创建并配置 Druid 数据源* @return 配置好的数据源对象*/@Beanpublic DataSource dataSource() {DruidDataSource ds = new DruidDataSource();// 设置数据库驱动类名,使用从配置文件中注入的值ds.setDriverClassName(driver);// 设置数据库连接 URL,使用从配置文件中注入的值ds.setUrl(url);// 设置数据库用户名,使用从配置文件中注入的值ds.setUsername(username);// 设置数据库密码,使用从配置文件中注入的值ds.setPassword(password);return ds;}
}

User

package com.example.domain;public class User {private int id;private String username;private String password;private String gender;private String addr;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public String getAddr() {return addr;}public void setAddr(String addr) {this.addr = addr;}@Overridepublic String toString() {return "User{" +"id=" + id +", username='" + username + '\'' +", password='" + password + '\'' +", gender='" + gender + '\'' +", addr='" + addr + '\'' +'}';}
}

UserDao

package com.example.dao;import com.example.domain.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;import java.util.List;@Mapper
public interface UserDao {@Select("select * from mybatis.user")public List<User> selectAll();@Select("select * from mybatis.user where id = #{id}")public User selectById(Integer id);
}

UserService

package com.example.service;import com.example.domain.User;import java.util.List;public interface UserService {public List<User> selectAll();public User selectById(Integer id);
}

UserServiceImpl

package com.example.service.impl;import com.example.dao.UserDao;
import com.example.domain.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service("userService")
public class UserServiceImpl implements UserService {//private BookDao bookDao = new BookDaoImpl();// 5.为了解决代码耦合度过高,使用IOC容器将创建对象的过程在容器中实现,不再使用new@Autowiredprivate UserDao userDao;@Overridepublic List<User> selectAll() {return userDao.selectAll();}@Overridepublic User selectById(Integer id){return userDao.selectById(id);}
}

logback.xml(无关紧要)

<?xml version="1.0" encoding="UTF-8"?>
<configuration><!-- console表示当前日志信息是可以输出到控制台的--><appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"><encoder><pattern>(%level %boldBlue(%d{HH:mm:ss.SSS}) %cyan(【%thread】) %boldGreen(%logger{15}) - %msg %n)</pattern></encoder></appender><root level="debug"><appender-ref ref="STDOUT" /></root>
</configuration>

AppTest(Spring整合mybatis的运行程序)

package com.example;import com.example.config.SpringConfig;
import com.example.domain.User;
import com.example.service.UserService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;import java.util.List;public class AppTest {public static void main(String[] args) {// 获取IOC容器AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);UserService userService = ctx.getBean(UserService.class);List<User> users = userService.selectAll();System.out.println(users);ctx.close();}
}

UserServiceTest(测试类)

package com.example.service;import com.example.config.SpringConfig;
import com.example.domain.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.util.List;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class UserServiceTest {@Autowiredprivate UserService userService;@Testpublic void selectAllTest() {List<User> users = userService.selectAll();System.out.println(users);}@Testpublic void selectByIdTest() {Integer id = 3;User user = userService.selectById(id);System.out.println(user);}
}

整合思路

整合mybaits

在mybatisConfig用SqlSessionFactoryBean封装SqlSessionFactory需要的环境信息

连接信息用jdbcConfig实现,dataSource对象是自动加载的

使用MapperScannerConfigurer加载Dao接口,创建代理对象保存到IOC容器中

主配置类SpringConfig中引入Mybatis配置类

  • @Configuration:声明这是一个配置类
  • @ComPonentScan:使得 Spring 容器能够自动扫描和发现被特定注解标注的类,并将它们注册为 Spring 容器中的 Bean
  • @PropertySource:加载外部属性文件,将外部的属性文件(如 .properties.yml 等)中的属性加载到 Spring 的 Environment 中,为应用程序提供配置信息。
  • @Import:这里是导入配置类,可以将其他的 Spring 配置类导入到当前配置类中,让 Spring 容器能够扫描和管理这些配置类中定义的 Bean。
@Configuration
@ComponentScan("com.examole")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MybatisConfig.class})
public class SpringConfig {
}

整合Jnuit

//设置类运行器
@RunWith(SpringJUnit4ClassRunner.class)//设置Spring环境对应的配置类
@ContextConfiguration(classes = {SpringConfiguration.class}) //加载配置类
  • 单元测试,如果测试的是注解配置类,则使用@ContextConfiguration(classes = 配置类.class)
  • 单元测试,如果测试的是配置文件,则使用 名,...}) @ContextConfiguration(locations={配置文件名,...})
  • Junit运行后是基于Spring环境运行的,所以Spring提供了一个专用的类运行器,这个务必要设 置,这个类运行器就在Spring的测试专用包中提供的,导入的坐标就是这个东西 SpringJUnit4ClassRunner
  • 上面两个配置都是固定格式,当需要测试哪个bean时,使用自动装配加载对应的对象,下面的工 作就和以前做Junit单元测试完全一样了

注解解释

@RunWith

@ContextConfiguration

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/7487.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【架构面试】二、消息队列和MySQL和Redis

MQ MQ消息中间件 问题引出与MQ作用 常见面试问题&#xff1a;面试官常针对项目中使用MQ技术的候选人提问&#xff0c;如如何确保消息不丢失&#xff0c;该问题可考察候选人技术能力。MQ应用场景及作用&#xff1a;以京东系统下单扣减京豆为例&#xff0c;MQ用于交易服和京豆服…

MATLAB提供的颜色映射表colormap——伪彩色

图像处理领域的一个习惯&#xff1a;不是真实的颜色&#xff0c;一般用伪彩色。一是说明不是物体本身的颜色&#xff0c;二是彩色更容易分辨。 MATLAB陆续提供了16种颜色映射表colormap。 之前的都很丑&#xff0c;近5年新增的4种还可以。总的说来还是丑。 这是一种鸟的名字。…

案例研究丨浪潮云洲通过DataEase推进多维度数据可视化建设

浪潮云洲工业互联网有限公司&#xff08;以下简称为“浪潮云洲”&#xff09;成立于2018年&#xff0c;定位于工业数字基础设施建设商、具有国际影响力的工业互联网平台运营商、生产性互联网头部服务商。截至目前&#xff0c;浪潮云洲工业互联网平台连续五年入选跨行业跨领域工…

电脑无法开机,重装系统后没有驱动且驱动安装失败

电脑无法开机&#xff0c;重装系统后没有驱动且驱动安装失败 前几天电脑突然坏了&#xff0c;电脑卡住后&#xff0c;强制关机&#xff0c;再开机后开机马上就关机。尝试无数次开机后失败&#xff0c;进入BIOS界面&#xff0c;发现已经没有Windows系统了。重新安装系统后&…

C++异步future

&#x1f30e; C11异步futrue 文章目录&#xff1a; C11异步futrue future介绍     应用场景     future操作       std::async函数模版       std::packaged_task类模版       std::promise类模版 &#x1f680;future介绍 std::future是C11标准库…

【C++探索之路】STL---string

走进C的世界&#xff0c;也意味着我们对编程世界的认知达到另一个维度&#xff0c;如果你学习过C语言&#xff0c;那你绝对会有不一般的收获&#xff0c;感受到C所带来的码云风暴~ ---------------------------------------begin--------------------------------------- 什么是…

CF 339A.Helpful Maths(Java实现)

题目分析 输入一串式子&#xff0c;输出从小到大排列的式子 思路分析 如上所说核心思路&#xff0c;但是我要使用笨方法&#xff0c;输入一串式子用split分割开&#xff0c;但是此时需要用到转义字符&#xff0c;即函数内参数不能直接使用“”&#xff0c;而是“\\”。分割开后…

C#,入门教程(07)——软件项目的源文件与目录结构

上一篇&#xff1a; C#&#xff0c;入门教程(06)——解决方案资源管理器&#xff0c;代码文件与文件夹的管理工具https://blog.csdn.net/beijinghorn/article/details/124895033 创建新的 C# 项目后&#xff0c; Visual Studio 会自动创建一系列的目录与文件。 程序员后面的工…

Cpp::静态 动态的类型转换全解析(36)

文章目录 前言一、C语言中的类型转换二、为什么C会有四种类型转换&#xff1f;内置类型 -> 自定义类型自定义类型 -> 内置类型自定义类型 -> 自定义类型隐式类型转换的坑 三、C强制类型转换static_castreinterpret_castconst_castdynamic_cast 四、RTTI总结 前言 Hell…

Android中Service在新进程中的启动流程

目录 1、Service与AMS交互框架介绍 1.1、认识AMS代表IActivityManager 1.2、认识客户端代表IApplicationThread 2、Service启动流程概览 我们知道Android有四大组件&#xff0c;Activity、Service、ContentProvider、Broadcast&#xff0c;每个组件在系统运行中或者我们编写…

docker 简要笔记

文章目录 一、前提内容1、docker 环境准备2、docker-compose 环境准备3、流程说明 二、打包 docker 镜像1、基础镜像2、国内镜像源3、基础的dockerfile4、打包镜像 四、构建运行1、docker 部分2、docker-compose 部分2.1、构建docker-compose.yml2.1.1、同目录构建2.1.2、利用镜…

利用Redis实现数据缓存

目录 1 为啥要缓存捏&#xff1f; 2 基本流程&#xff08;以查询商铺信息为例&#xff09; 3 实现数据库与缓存双写一致 3.1 内存淘汰 3.2 超时剔除&#xff08;半自动&#xff09; 3.3 主动更新&#xff08;手动&#xff09; 3.3.1 双写方案 3.3.2 读写穿透方案 3.3.…

活动回顾和预告|微软开发者社区 Code Without Barriers 上海站首场活动成功举办!

Code Without Barriers 上海活动回顾 Code Without Barriers&#xff1a;AI & DATA 深入探索人工智能与数据如何变革行业 2025年1月16日&#xff0c;微软开发者社区 Code Without Barriers &#xff08;CWB&#xff09;携手 She Rewires 她原力在大中华区的首场活动“AI &…

python爬虫入门(一) - requests库与re库,一个简单的爬虫程序

目录 web请求与requests库 1. web请求 1.1 客户端渲染与服务端渲染 1.2 抓包 1.3 HTTP状态代码 2. requests库 2.1 requests模块的下载 2.2 发送请求头与请求参数 2.3 GET请求与POST请求 GET请求的例子&#xff1a; POST请求的例子&#xff1a; 3. 案例&#xff1a;…

全连接神经网络(前馈神经网络)

目录 一、初步认识全连接神经网络 1、神经元 2、网络结构 3、正向传播算法 二、反向传播算法 1、理解 2、迭代流程 三、构建神经网络模型的基本步骤 四、线性回归神经网络结构 4.1 数据处理 1、数据导入 2、数据归一化处理 3、数据集划分 4、数据形状变换 4.2 模…

【C++初阶】第11课—vector

文章目录 1. 认识vector2. vector的遍历3. vector的构造4. vector常用的接口5. vector的容量6. vector的元素访问7. vector的修改8. vector<vector\<int\>>的使用9. vector的使用10. 模拟实现vector11. 迭代器失效11.1 insert插入数据内部迭代器失效11.2 insert插入…

Linux查看服务器的内外网地址

目录&#xff1a; 1、内网地址2、外网地址3、ping时显示地址与真实不一致 1、内网地址 ifconfig2、外网地址 curl ifconfig.me3、ping时显示地址与真实不一致 原因是dns缓存导致的&#xff0c;ping这种方法也是不准确的&#xff0c;有弊端不建议使用&#xff0c;只适用于测试…

PAT甲级-1024 Palindromic Number

题目 题目大意 一个非回文数&#xff0c;加上它的翻转数所得的和&#xff0c;进行k次&#xff0c;有可能会得到一个回文数。给出一个数n&#xff0c;限制相加次数为k次&#xff0c;如果小于k次就得到回文数&#xff0c;那么输出该回文数和相加的次数&#xff1b;如果进行k次还…

xss靶场

xss-labs下载地址&#xff1a;GitHub - do0dl3/xss-labs: xss 跨站漏洞平台 xss常见触发标签&#xff1a;XSS跨站脚本攻击实例与防御策略-CSDN博客 level-1 首先查看网页的源代码发现get传参的name的值test插入了html里头&#xff0c;还回显了payload的长度。 <!DOCTYPE …

数据结构——实验七·排序

欢迎各位大佬们来到Tubishu的博客&#x1f31f; Tubishu是一名计算机本科生&#xff0c;不定期发送一些在学校的成果供佬们消遣~希望能为佬的编程之路添砖加瓦⭐&#x1f525; 求各位大佬们垂怜&#x1f525;点赞评论一下呗&#x1f525;&#x1f525; 本文专栏 ➡️ 数据结构 …