Spring+Mybatis IOC + AOP + 开启事务 模板

news2024/9/30 6:22:02

萌新小白刚入行Java 框架的可以试着自己拿着这个代码改一改,看看能不能运行成功

第一步:创建maven项目,在pom.xml文件中引入以下需要用到的jar包

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.example</groupId>
        <artifactId>mySpring</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>spring_mybatis</artifactId>
    <name>Archetype - spring_mybatis</name>
    <url>http://maven.apache.org</url>

    <dependencies>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.9.7</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.7</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.12</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.13</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.22</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.22</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>3.0.4</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.30</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
    <build>
       <resources>
           <resource>
               <directory>src/main/java</directory>
               <includes>
                   <include>**/*.xml</include>
               </includes>
               <filtering>true</filtering>
           </resource>
       </resources>
    </build>
</project>

 第二步:连接数据库操作.

填写User 和Password 点击连接,连接无误后显示下图红色圈起来的部分.

此时右键点击红色部分再点开 Properties.

选择你需要连接数据库 .

第三步: 我们新建pojo包,继续新建实体类用于存储对象

第四步:创建mapper包,生成对应的接口\接口实现\编写SQL.xml文件  注意:创建名称时相同

(1), 接口定义:

package com.mapper;

import com.pojo.User;

import java.util.List;

/**
 * @author helloZZ
 */
public interface UserMapper
{
     List<User> selectUsers();

     int addUser(User user);

     int deleteUser(String id);
}

(2). 接口实现:

package com.mapper;

import com.pojo.User;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.List;

/**
 * @author helloZZ
 */
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {

    @Override
    public List<User> selectUsers() {
        User user = new User("8","ZZ123",23,"男","beijing","123456");
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        mapper.addUser(user);
        mapper.deleteUser("8");
        return mapper.selectUsers();
    }

    @Override
    public int addUser(User user) {
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        return mapper.addUser(user);
    }

    @Override
    public int deleteUser(String id) {
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        return mapper.deleteUser(id);
    }
}

(3). UserMapper.xml文件 

<?xml version="1.0" encoding="UTF-8" ?>
        <!DOCTYPE mapper
                PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
                "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mapper.UserMapper">
    <insert id="addUser">
        insert into student(name,age,sex,addres,studentNumber) values(#{name},#{age},#{sex},#{addres},#{studentNumber})
    </insert>

    <delete id="deleteUser">
        delete from student where id = #{id}
    </delete>

    <select id="selectUsers" resultType="com.pojo.User">
    select * from student
</select>

</mapper>

第五步: 我们需要创建xml配置项一共有三个

(applicationContext.xml)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <import resource="spring-dao.xml"/>
    <bean id="userMapper" class="com.mapper.UserMapperImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
</beans>

(spring-dao.xml)

这里注意需要更改数据库的配置!不要一股脑的copy

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd"
>
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <!--1.3配置连接池需要的参数-->
            <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/填写数据库名称?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=UTC"/>
            <property name="username" value="填写数据库的用户名称"/>
            <property name="password" value="填写数据库的用户密码"/>
        </bean>
        
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:sqlMapConfig.xml"/>
        <property name="mapperLocations" value="classpath:com/mapper/*.xml"/>
    </bean>

<!--    SqlSessionTemplate 就是我们使用的sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg ref="sqlSessionFactory" index="0"/>
    </bean>
<!--    声明事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
<!--    配置事务-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <tx:attributes>
                <tx:method name="addUser" propagation="REQUIRED"/>
                <tx:method name="deleteUser" propagation="REQUIRED"/>
                <tx:method name="updateUser" propagation="REQUIRED"/>
                <tx:method name="queryUser" read-only="true"/>
                <tx:method name="*" propagation="REQUIRED"/>
            </tx:attributes>
    </tx:advice>

<!--配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
</beans>

(sqlMapConfig.xml)

<?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.pojo"/>
  </typeAliases>
</configuration>

第六步:创建test包下新建测试类,测试我们是否成功查询\删除\新增功能

 

import com.mapper.UserMapper;
import com.pojo.User;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;
import java.util.List;


public class Test01 {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
        List<User> users = userMapper.selectUsers();
        for (User user : users) {
            System.out.println(user);
        }
    }
}

 

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

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

相关文章

matlab2019b-2024b knnclassify无法识别的问题(亲测,已解决)

matlab2019a-2024b 已经移除了knnclassify分类&#xff0c;修改了名称和功能&#xff0c;如果你还想使用它&#xff0c;就必须在2018版本以前的旧版本中找相关的工具箱&#xff08;这是免费的哦&#xff0c;如果官网下载 需要付费&#xff09;。 这里本人从2014a中分离出的工具…

Docker启动 Redis提示:Can‘t initialize Background Jobg

问题说明: 在使用docker启动redis失败&#xff0c;但是查看容器日志&#xff0c;除了提示 Fatal:Cant initialize Background Jobg&#xff0c;没有其他错误信息。经过长时间查找资料及试错&#xff0c;现记录下可能的产生原因及解决方案&#xff0c;以便以后参考。 产生原因&…

【数据结构与算法】Z算法(扩展KMP)(C++和Python写法)

Z算法&#xff08;扩展KMP&#xff09; 文章目录 Z算法&#xff08;扩展KMP&#xff09;朴素求法线性求法力扣类型题变种题&#xff1a;[3303. 第一个几乎相等子字符串的下标](https://leetcode.cn/problems/find-the-occurrence-of-first-almost-equal-substring/) 所谓Z算法&…

[题解] Codeforces Round 976 (Div. 2) A ~ E

A. Find Minimum Operations 签到. void solve() {int n, k;cin >> n >> k;if (k 1) {cout << n << endl;return;}int ans 0;while (n) {ans n % k;n / k;}cout << ans << endl; }B. Brightness Begins 打表发现, 翻转完后的序列为: 0…

基于SSM+小程序的流浪动物领养管理系统(救助1)(源码+sql脚本+视频导入教程+文档)

&#x1f449;文末查看项目功能视频演示获取源码sql脚本视频导入教程视频 1、项目介绍 本系统功能为信息发布管理、领养记录管理、动物小圈管理、求助日报管理等。本系统的使用角色为管理员和用户&#xff0c;用户可以发布自己捡到的流浪动物、求领养信息、申请领养&#xff…

从零开发操作系统

没有操作系统 要考虑放到什么位置 org 07c00h 我用nasm&#xff08;汇编编译&#xff09; 放到7c00处 ibm兼容机 AX发生变化 -寄存器 不可能做存储 内存- 代码段数据段 if else --指令 代码 int a -数据段 必须告诉计算机代码段从哪里开始 改变cs寄存器里面的值可以改变推进寄…

【MYSQL】MYSQL约束

约束是在创建表的时候用的 1、概念 约束英文&#xff1a;constraint 约束实际上就是表中数据的限制条件 2、作用 表在设计的时候加入约束的目的就是为了保证表中的记录完整性和有效性&#xff0c;比如&#xff1a;用户表有些列的值&#xff08;手机号&#xff09;不能为空…

STM32自动下载电路分享及注意事项

文章目录 简介ISP下载启动配置 USB转串口芯片CH340C手动isp下载自动isp下载RTS、DTR电平变化分析注意事项 简介 在嵌入式开发中&#xff0c;使用STM32下载程序&#xff0c;可以通过仿真器下载&#xff0c;也可以通过串口下载。在stm32串口下载时&#xff0c;我们需要手动配置启…

gradle的入门及kotlin的了解

gradle项目创建方式 1.idea springboot initalizer 2.命令行 gradle目录结构 gradle命令 gradle wrapper 一个解决不同项目需要不同版本gradle的问题 比如&#xff0c;对方电脑没用安装gradle 对方电脑安装了gradle&#xff0c;但是版本太旧了 于是&#xff0c;在项目根目…

Qt 学习第十一天:QTableWidget 的使用

一、创建QTableWidget对象&#xff0c;设置大小&#xff0c;在窗口的位置 //创建tablewidgetQTableWidget *table new QTableWidget(this);table->resize(550, 300);table->move(100, 100); //移动 二、设置表头 //设置表头QStringList headerList; //定义headerList…

Webpack 特性探讨:CDN、分包、Tree Shaking 与热更新

文章目录 前言包准备CDN 集成代码分包Tree Shaking原理实现条件&#xff1a;解决 treeShaking 无效方案&#xff1a;示例代码&#xff1a; 热更新&#xff08;HMR&#xff09; 前言 Webpack 作为现代前端开发中的核心构建工具&#xff0c;提供了丰富的特性来帮助开发者优化和打…

63.5 注意力提示_by《李沐:动手学深度学习v2》pytorch版

系列文章目录 文章目录 系列文章目录注意力提示生物学中的注意力提示查询、键和值注意力的可视化使用 show_heatmaps 显示注意力权重代码示例 代码解析结果 小结练习 注意力提示 &#x1f3f7;sec_attention-cues 感谢读者对本书的关注&#xff0c;因为读者的注意力是一种稀缺…

Python 读取与处理出入库 Excel 数据实战案例(HTML 网页展示)

有如下数据&#xff0c;需要对数据合并处理&#xff0c;输出到数据库。 数据样例&#xff1a;&#x1f447; excel内容&#xff1a; 出入库统计表河北库.xlsx: 出入库统计表天津库.xlsx: 01实现过程 1、创建test.py文件&#xff0c;然后将下面代码复制到里面&#xff0c;最后…

original多因子图绘制

成品参考 首先导入数据 设置过程 设置X轴 设置图 双击空白部分设置图层宽度&#xff08;也需要设置高度&#xff09; 颜色配置 1.删除边框 合适的参数与颜色&#xff08;设置为单色&#xff09;

PDF转换为TIF,JPG的一个简易工具(含下载链接)

目录 0.前言&#xff1a; 1.工具目录 2.工具功能&#xff08;效果&#xff09;&#xff0c;如何运行 效果 PDF转换为JPG&#xff08;带颜色&#xff09; PDF转换为TIF&#xff08;LZW形式压缩&#xff0c;可以显示子的深浅&#xff09; PDF转换为TIF&#xff08;CCITT形…

Squaretest单元测试辅助工具使用

1、idea安装插件 Squaretest 然后关掉idea 2、安装字节码软件&#xff08;jclasslib&#xff09; 3、找到idea里面的Squaretest安装目录 找到包含TestStarter的jar包 4、打开 com.squaretest.c.f 打开后选择常量池 5、找到第16个修改 Long value值&#xff0c;修改的数字即为使…

英飞凌 PSoC6 评估板 Wi-Fi 无线通信

PSoC™ 62 with CAPSENSE™ evaluation kit 开发板&#xff08;以下简称 PSoC 6 RTT 开发板&#xff09;是英飞凌&#xff08;Infineon&#xff09;联合 RT-Thread 发布一款面向物联网开发者的 32 位双核 MCU 开发套件&#xff0c;其默认内置 RT-Thread 物联网操作系统。本文主…

[RabbitMQ] 7种工作模式详细介绍

&#x1f338;个人主页:https://blog.csdn.net/2301_80050796?spm1000.2115.3001.5343 &#x1f3f5;️热门专栏: &#x1f9ca; Java基本语法(97平均质量分)https://blog.csdn.net/2301_80050796/category_12615970.html?spm1001.2014.3001.5482 &#x1f355; Collection与…

【Linux】如何用shell脚本一键安装Java和Maven环境

Shell脚本安装环境 前言脚本Java安装脚本使用方式 Java卸载脚本Maven安装脚本Maven卸载脚本 前言 无论是在云服务器上部署Java项目 还是在本地的Linux虚拟机上运行Java项目 都需要Java的环境 设置环境则需要一些繁琐的操作 为了简化并复用这些操作 我们可以封装这些操作为一个…

AD导出gerber文件(光绘文件)

第一步&#xff1a; 英寸 2:5 勾选你想显示的层 默认默认 第二步&#xff1a; 第三步&#xff1a; 默认