spring学习日记-day7-整合mybatis

news2024/10/3 0:21:35

一、学习目标

        spring整合MyBatis的原理主要涉及到将MyBatis的Mapper映射文件交由Spring容器管理,并将其注入到MyBatis的SqlSessionFactory中,从而实现两者的整合。

二、整合mybatis

1.写一个mybatis测试案例

项目结构:

1.数据库

CREATE DATABASE `mybatis`;
USE `mybatis`;

create table Users(
    id int not null auto_increment primary key,
    name varchar(10) not null,
    age int not null
);

insert into Users(id,name,age) values(null,'张三',20),(null,'李四',18);

2.实体类


public class User {
    private int id;  //id
    private String name;   //姓名
    private int age;   //密码

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public User(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public User() {
    }
}

2.编写接口

public interface UserMapper {
    public List<User> selectUser();
}

3.mybatisConfig配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <package name="com.lzh.pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="admin123"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name="com.lzh.dao"/>
    </mappers>
</configuration>

4.UserrMapper文件:

<?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.lzh.dao.UserMapper">
    <select id="selectUser" resultType="User">
        select * from users
    </select>
</mapper>

5.pom.xml

<?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.lzh</groupId>
    <artifactId>spring-07</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.1.10.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.1.10.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.4</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.2</version>
    </dependency>

    </dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

</project>

6.测试

@Test
    public void selectUser() throws IOException {
        String resource = "MybatisConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.selectUser();
        for (User user: userList){
            System.out.println(user);
        }
        sqlSession.close();
    }

2.整合mybatis方式一

1.配置数据源

    <!--配置数据源->
    定义一个数据源bean,id为"dataSource",用于管理数据库连接。
    class属性指定了数据源的实现类为org.springframework.jdbc.datasource.DriverManagerDataSource,
    -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <!--
            设置数据库连接的URL。
            - useSSL=true&amp;useSSL=false:这里似乎有一个错误,通常只需要一个useSSL参数,并且应该保持一致。
              对于本地开发,通常不需要SSL,所以应设置为false。
            - useUnicode=true:指定使用Unicode字符集。
            - characterEncoding=utf8:指定字符编码为UTF-8。注意,从MySQL 5.5.3版本开始,建议使用utf8mb4代替utf8,
              以支持更广泛的Unicode字符,包括emoji表情等。
        -->
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8"/>
        <property name="username" value="root"/>
        <property name="password" value="admin123"/>
    </bean>

2.配置SqlSessionFactory,关联MyBatis注册,sqlSessionTemplate,关联sqlSessionFactory

     <!-- 配置SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据源,这里的ref指向之前定义的数据源bean -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 关联Mybatis的全局配置文件,MybatisConfig.xml中包含了MyBatis的设置,如别名、类型处理器、插件等 -->
        <property name="configLocation" value="classpath:MybatisConfig.xml"/>
        <!-- 指定Mapper XML文件的位置,MyBatis会根据这些XML文件来创建Mapper接口的实现 -->
        <!-- 注意:这里只指定了一个Mapper XML文件,如果有多个,可以使用逗号分隔或者使用通配符 -->
        <property name="mapperLocations" value="classpath:com/lzh/dao/UserMapper.xml"/>
    </bean>
    <!-- 注册sqlSessionTemplate,关联sqlSessionFactory -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!-- 通过构造器注入SqlSessionFactory,使得SqlSessionTemplate能够管理SqlSession -->
        <!-- index="0"指定了构造器参数的索引,这里假设SqlSessionTemplate的构造器第一个参数就是SqlSessionFactory -->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

3.增加接口实现类

public class UserDaoImpl implements UserMapper {
    // 注入SqlSessionTemplate,Spring容器会负责注入
    private SqlSessionTemplate sqlSession;
    // 通过构造器注入SqlSessionTemplate(推荐的方式,因为它支持Spring的依赖注入最佳实践)
    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }
    public List<User> selectUser() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}

4.注册bean

    <bean id="userDao" class="com.lzh.dao.UserDaoImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>

5.修改mybatis配置文件

     <!--mappers>
        <package name="com.lzh.dao"/>
    </mappers-->

6.测试

@Test
    public void test2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserMapper mapper = (UserMapper) context.getBean("userDao");
        List<User> user = mapper.selectUser();
        System.out.println(user);
    }

2.整合mybatis方式二

1.修改接口实现类

public class UserDaoImpl extends SqlSessionDaoSupport implements UserMapper {
    public List<User> selectUser() {
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}

2.修改bean配置

 <!-- 注册sqlSessionTemplate,关联sqlSessionFactory -->
    <!--bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        < 通过构造器注入SqlSessionFactory,使得SqlSessionTemplate能够管理SqlSession -->
        <!-- index="0"指定了构造器参数的索引,这里假设SqlSessionTemplate的构造器第一个参数就是SqlSessionFactory -->
        <!--constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean-->

    <!--bean id="userDao" class="com.lzh.dao.UserDaoImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean-->
    <bean id="userDao" class="com.lzh.dao.UserDaoImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

高考技术——pandas使用

百家讲坛&#xff0c;谈论古今&#xff0c;今天我们不聊别的&#xff0c;我们来聊一聊中国的国宝——大熊猫&#xff08;bushi&#xff09; 好好&#xff0c;言归正传&#xff0c;我们今天来讲pandas import pandas as pd 申明无需多言&#xff0c;高考主要考察Series和Data…

区块链媒体推广:15个数字解读未来-华媒舍

区块链技术性作为一种区块链技术和加密的数据帐簿技术性&#xff0c;正在逐步引起广泛关注。伴随着新闻媒体市场的发展&#xff0c;区块链媒体推广也成为了新的发展趋势。下面我们就带大家探寻15个数字&#xff0c;揭露将来区块链媒体推广的新方向。 1、网络传播年增长率 数字…

Mac 网络连接正常,微信可以使用,但浏览器打不开网页?

解决&#xff1a; Step1&#xff0c;选择&#x1f34e;图标&#xff0c;选择系统设置&#xff08;或系统偏好设置&#xff09;打开&#xff1b; Step2&#xff0c;选择网络&#xff0c;Wi-Fi Step3&#xff0c;选择详细信息&#xff1b; Step4: 选择代理&#xff0c;关闭右…

每日OJ题_牛客_JOR26最长回文子串_C++_Java

目录 牛客_OR26最长回文子串 题目解析 C代码1 C代码2 Java代码 牛客_OR26最长回文子串 最长回文子串_牛客题霸_牛客网 描述&#xff1a; 对于长度为n的一个字符串A&#xff08;仅包含数字&#xff0c;大小写英文字母&#xff09;&#xff0c;请设计一个高效算法&#xf…

Redis: 持久化之RDB和AOF

概述 Redis 有一个高质量的课题&#xff1a;数据安全性与数据可靠性Redis 是一个内存型数据库&#xff0c;数据大部分都是存在内存里面当信息在内存中流通时&#xff0c;Redis 节点突然就故障挂掉当重新启动的时候&#xff0c;内存中的数据肯定是全部丢失了如果在这种情况下&a…

MySQL 中如何优化 DISTINCT 查询

一、引言 在 MySQL 数据库中&#xff0c;DISTINCT关键字用于查询结果集中去除重复的行。然而&#xff0c;使用DISTINCT可能会导致查询性能下降&#xff0c;特别是在处理大量数据时。本文将介绍一些优化 MySQL 中DISTINCT查询的方法。 二、理解 DISTINCT 查询的性能影响 &…

Oracle中TRUNC()函数详解

文章目录 前言一、TRUNC函数的语法二、主要用途三、测试用例总结 前言 在Oracle中&#xff0c;TRUNC函数用于截取或截断日期、时间或数值表达式的部分。它返回一个日期、时间或数值的截断版本&#xff0c;根据提供的格式进行截取。 一、TRUNC函数的语法 TRUNC(date) TRUNC(d…

2024/10/2

1 线代内积和外积 2 在 PyTorch 中&#xff0c;x.dot(torch.ones(3)) 是执行向量点积&#xff08;dot product&#xff09;操作的代码。假设 x 是一个一维张量&#xff08;向量&#xff09;&#xff0c;其形状是 (N,)&#xff0c;且 N 应该与 torch.ones(3) 的长度相匹配。具…

查找与排序-插入排序

排序算法可以分为内部排序和外部排序&#xff0c;内部排序是数据记录在内存中进行排序&#xff0c;而外部排序是因排序的数据很大&#xff0c;一次不能容纳全部的排序记录&#xff0c;在排序过程中需要访问外存。常见的内部排序算法有&#xff1a;插入排序、希尔排序、选择排序…

java基础应用-循环控制

1、使用while与自增运算符循环遍历数组 1.1 实例说明 本实例利用自增运算符结合while循环获取每个数组元素的值&#xff0c;然后把它们输出到控制台中。其中自增运算符控制索引变量的递增。程序运行结果如图1所示。 图1 实例运行结果 1.2 实现过程 创建ErgodicArray类&#…

企业网盘预算规划,了解2024年最新价格标准

2024年全球企业云存储市场将增15%&#xff0c;企业网盘收费多样&#xff0c;包括用户数量、存储容量定价及综合功能套餐。ZohoWorkDrive、DropboxBusiness、GoogleWorkspace为主流选择&#xff0c;价格因企业规模、功能需求而异&#xff0c;建议灵活选择套餐和长期合作计划。 一…

yub‘s Algorithmic Adventures_Day3

yub’s Algorithmic Adventures_Day3 有序数组的平方 link&#xff1a;977. 有序数组的平方 - 力扣&#xff08;LeetCode&#xff09; 非递减顺序 一个数列中的元素从左到右依次不减&#xff0c;或者说不降序排列. 比如&#xff1a;1233445&#xff0c;12345. 思路分析 如果…

CORE MVC 过滤器 (筛选器)《2》 TypeFilter、ServiceFilter

TypeFilter、ServiceFilter ServiceFilter vs TypeFilter ServiceFilter和TypeFilter都实现了IFilterFactory ServiceFilter需要对自定义的Filter进行注册&#xff0c;TypeFilter不需要 ServiceFilter的Filter生命周期源自于您如何注册&#xff08;全局、区域&#xff09;&…

vite中sass警告JS API过期

1.问题 在Vite创建项目中引入Sass弹出The legacy JS API is deprecated and will be removed in Dart Sass 2.0.0 - vite中sass警告JS API过期 The legacy JS API is deprecated and will be removed in Dart Sass 2.0.0警告提示表明你当前正在使用的 Dart Sass 版本中&#…

Python画图|渐变背景

Python画图在有些时候&#xff0c;需要使用渐变过度。 在matplotlib官网中&#xff0c;提供了一个为柱状图画渐变背景的案例&#xff0c;我们一同探索一番。 【1】官网教程 点开下述链接&#xff0c;直达官网教程&#xff1a; https://matplotlib.org/stable/gallery/lines…

【Bug】解决 Ubuntu 中 “error: Unable to Find Python3 Executable” 错误

解决 Ubuntu 中 “Unable to Find Python3 Executable” 错误 在 Ubuntu 系统上使用 Python 进行开发时&#xff0c;遇到找不到 python3 可执行文件的错误。 主要问题是无法正常打开终端&#xff08;原生与terminator&#xff09;&#xff0c;找不到python3&#xff0c;且无法…

基于muduo库函数实现protobuf协议的通信

文章目录 先定义具体的业务请求类型2. 实现服务端提供的服务protobuf_server.cppprotobuf_client.cpp 建议先去了解muduo库和protobuf协议&#xff1a; Protobuf库的使用Muduo库介绍及使用 先定义具体的业务请求类型 先使用protobuf库创建我们所要完成的业务请求类型&#xf…

域内用户名枚举 实验

1. 实验网络拓扑 kali: 192.168.72.128win2008: 192.168.135.129 192.168.72.139win7: 192.168.72.149win2012:(DC) 192.168.72.131 2. 简单原理 详细的报文分析在之前写过了&#xff0c;这里简单提一提。 利用的是Kerberos的AS阶段&#xff0c;AS_REP的回显不同&#xff0c…

迷宫中的最短路径:如何用 BFS 找到最近出口【算法模板】

如何通过广度优先搜索&#xff08;BFS&#xff09;求解迷宫问题 在这篇文章中&#xff0c;我们将学习如何使用 广度优先搜索&#xff08;BFS&#xff09; 解决一个典型的迷宫问题&#xff0c;具体是从迷宫的一个入口出发&#xff0c;找到最近的出口。我们将一步步分析 BFS 是如…

初识CyberBattleSim

现在许多企业都在使用AD域服务进行管理&#xff0c;我们现在通俗理解里面蕴含着许多重要资产。 对于这个东西有下列的描述: 1、攻击他能够获得用户权限 2、里面存在许多的计算机资产&#xff0c;当攻击者攻击其中的一台机器&#xff0c;可以通过某种手段在域中的环境横向移动…