Mybatis

用springboot+mybatis+mysql实现对user表的信息读取(初步,工具idea) 从头开始,写一个springboot+mybatis的小demo,对user表的信息进行管理、调用。 首先,在idea中新建一个项目,选择maven项目以及使用的SDK版本,然后点击下一步; 在GroupId中写上路径,ArtifactId处写上名称,可以将version设置成1.0.0,下一步,同样将名称改一下,finish即可,生成的项目目录如下。 使用springboot和mybatis,首先需要在pom中添加依赖和配置; <!--继承spring boot的父级项目的依赖 --&gt 阅读详情

介绍

作用于:持久层,是一个ORM框架!

基本配置使用

1.导包
1.核心包【mybatis-3.2.1.jar】
2.依赖包【asm-3.3.1.jar,cglib-2.2.2.jar,commons-logging-1.1.1.jar,javassist-3.17.1-GA.jar,log4j-1.2.17.jar,slf4j-api-1.7.2.jar,slf4j-log4j12-1.7.2.jar】
3.驱动包【mysql-connector-java-5.1.26-bin.jar,ojdbc14.jar】注意:根据不同的数据去选择不同的驱动包
2.核心配置文件‘【mybatis-config.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:配置根标签
 default:默认命名
     < transactionManager type="JDBC"/>:事务管理器的类型
     < dataSource type="POOLED">:连接池资源文件类型
     -- > 
< configuration>
    <!--读取资源文件-->
    <properties resource="dp.properties"/>
    <!--配置别名-->
    <typeAliases>
        < package name="需要设置别名的包"/>
    </typeAliases>
     <!--真实数据库环境(多个)-- >
    <environments default="development">
         <!--真实数据库环境 -- >
        <environment id="development">
            <transactionManager type="JDBC"/>
             <!--dataSource:数据源(连接池) -->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driverClassName}"/ >
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${ jdbc.username }"/  >
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    !--
           mappers:配置sql配置文件的映射关系读取
           可配置多个
    -- >
    <mappers>
        <mapper resource="映射包名"/>
    </mappers>
</configuration>

3.配置映射文件

<?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">
<!--
    namespace+id=:映射关系的唯一标识
    parameterType:参入类型  类型long=Long _long=long
    resultType:返回值类型 注意写完全限定名
-->
<mapper namespace="com.cn.domain.ProductMpper.xml">
<!--
	#{}:预编译sql 建议使用
	${}:不预编译sql  注意只能传对象
-->
    <select id="findOne" parameterType="long" resultType="Product">
              select * from product where id = #{id}
     </select>
</mapper>

代码使用展示

查询展示
【一】 生成domain类(使用idea生成)
【二】 dao层定义

public interface ProductDao {
    Product findOne(Long id);
}

【三】 dao层实现

public class IProductDaoImpl implements ProductDao {


    @Override
    public Product findOne(Long id) {
        /*1.准备拿到SqlSessionFactory对象
        * new SqlSessionFactoryBuilder().build("这里的参数是核心配置文件")
        * Mybatis有工具类Resources来读取核心配置文件
        * sqlSessionFactory.openSession();//获得sqlSession对象来持久化操作
        * sqlSession.selectOne("这里的参数是:映射关系的唯一标识",查询参数);
        * */

        try {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybtis-config.xml"));
            SqlSession sqlSession = sqlSessionFactory.openSession();
            return sqlSession.selectOne("com.cn.domain.ProductMpper.xml.selectOne",id);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

【四】 测试

public class MybatisText {

    ProductDao dao = new IProductDaoImpl();

    @Test
    public void seletOneTxet(){
        Product product= dao.findOne(20L);
        System.out.println(product);
    }
    /*
    	控制台数据:
Product{id=20, productName='可以不有', salePrice=699.0, supplier='罗技', brand='罗技', cutoff=0.79, costPrice=278.0, dir_id=4}

Process finished with exit code 0

    */
mybatis 和 mybatis-plus 配置文件: 用于配置数据库连接和 MyBatis 运行时所需的各种特性,包含了设置和影响 MyBatis 行为的属性、映射文件的位置。mapper接口和mapper.xml之间需要遵循一定规则,才能成功的让mybatis将mapper接口和mapper.xml绑定起来。创建IUserMapper接口: 用于操作数据库CURD的方法。文件:用于mybatis配置文件读取数据库信息。resources 目录下 创建。resources 目录下 创建。resources 目录下 的。类:用于跟数据库字段做映射。 阅读详情

相关推荐

Mybatis三剑客(mybatis-generator、mybatis-plugin、mybatis-pagehelper)介绍、配置及破解

本文用的是maven,idea15Mabatis三剑客分别是:mybatis-generator、mybatis-plugin、mybatis-pagehelper一、mybatis-generator根据我们的数据库自动生成pojo、dao和xml文件 pojo里面放的是跟数据库字段一一对应的对象、dao层是接口,供service使用,xml是这个dao层接口的实现,sql语句都写在xml里1.

不潜规则的胖小 1万+

初识MyBatis框架——MyBatis入门程序

在项目的src/main/resources目录下创建一个文件夹,在mapper文件夹下创建映射文件UserMapper.xml,该文件主要用于实现SQL语句和Java对象之间的映射,使SQL语句查询出来的关系型数据能够被封装成Java对象。:在项目的src/main/java目录下创建com.mac.pojo包,在com.mac.pojo包下创建User类,该类用于封装User对象的属性。

致力于分享在各类技术领域的学习与实践经验,涵盖编程、虚拟化、开源工具、网络安全等。 570

深度解析 MyBatis 生态三大主流框架:MyBatis-Flex、MyBatis-Plus 与 Fluent-MyBatis

本文对比分析了MyBatis三大增强框架:MyBatis-Flex、MyBatis-Plus和Fluent-MyBatis。MyBatis-Flex采用轻量级架构,无SQL解析设计使其性能最佳;MyBatis-Plus功能全面,企业级特性丰富;Fluent-MyBatis提供流式API,代码可读性强。三者各具特色,开发者可根据性能需求、功能要求和开发体验选择合适的框架。

awei0916的专栏 1944

mybatis用户User的增删改查实现idea

mybatis实现简单的增删改查项目结构添加maven依赖配置mybatis-config.xml创建UserMapper.xml创建dao层并写UserMapper创建实体类Domain层并写User在主程序中测试增删改查创建db数据库,建立user表运行结果 项目结构 添加maven依赖 创建好springboot项目后在pom.xml中添加 // An highlighted block <dependency> <groupId>org.mybatis</grou

weixin_43950187的博客 925

从零开始:使用Mask2Former训练你的专属数据集

本文详细介绍了如何从零开始使用Mask2Former训练自定义数据集。内容涵盖环境搭建、数据准备(将LabelMe格式转换为COCO格式)、数据集注册与模型配置、训练启动与调试,以及最终的模型推理与应用。通过实战步骤和常见问题解决方案,帮助读者掌握使用Mask2Former进行实例分割的核心流程,实现专属模型的训练与部署。

weixin_28678151的博客 455

团子杂记:SAP收入确认工具RAR(Revenue Recognition&Reporting)在新收入准则下的应用

SAP收入确认工具RAR知识分享

Lucas1211的博客 4284

mybatis学习之删除和更新用户例子

1、编写数据库映射文件(User.xml) 在配置文件中加入如下代码 <!-- 删除用户 根据ID删除用户 --> DELETE from user where id = #{id} <!-- 更新用户 需要传入用户的ID和更新的信息 parameterType指定User对象,注意:id必须存在

属于Alex的Java小世界 1656

修改注册表导致开机时电脑显示“无法登陆到你的账户”的问题解决方案

1.问题描述:开机电脑显示“无法登陆到你的账户:通常可以通过从你的账户注销,然后重新登陆来解决问题,如果不立即注销,你创建的任何文件或进行的任何更改都将会丢失。” 2.问题原因:想要修改cmd中的用户名(红色部分),修改了注册表,重启时出现问题。 3.问题解决: win+R输入cmd,确定进入注册表界面,将下面的地址复制进地址栏(你也可以自己按目录查找),双击ProfileImage...

qq_33835957的博客 7万+

Mybatis-Plus和Mybatis区别

核心关系:MyBatis-Plus 是 MyBatis 的增强版,完全兼容 MyBatis,不改变原有使用方式,仅做功能补充。核心差异:MP 提供了「通用 CRUD、条件构造器、分页插件、代码生成器」等开箱即用的功能,大幅减少重复代码;而原生 MyBatis 更侧重 SQL 的手动控制。选型建议:优先选 MyBatis-Plus(开发效率更高),遇到复杂 SQL 时,仍可像原生 MyBatis 一样手动编写,兼顾效率与灵活性。

weixin_53050448的博客 1241

macOS 发票查验全攻略:从证书导入到Safari调试

本文详细介绍了在macOS上进行发票查验的全流程,包括证书下载、钥匙串访问导入、Safari浏览器调试等关键步骤。重点解决了验证码不显示等常见问题,提供了证书信任设置和开发者工具使用的实用技巧,帮助用户顺利完成税务发票在线查验。

weixin_29204749的博客 547

告别Vivado自带编辑器!手把手教你用Sublime Text 4 + Icarus Verilog搭建FPGA开发环境(Windows 10/11)

本文详细介绍如何在Windows 10/11系统下,使用Sublime Text 4和Icarus Verilog搭建高效的FPGA开发环境,替代Vivado自带编辑器。通过配置语法检查、代码高亮和智能补全等功能,提升Verilog开发效率,实现专业级工作流。

weixin_30684743的博客 428

MYBATIS缓存

MYBATIS的第一缓存是SQLSession 并且这种缓存是即使在仅仅只有一个框架的情况下都是存在的, 因为第一缓存是默认开启的(default), 因为第一缓存级别使用的是SqlSession, 所以在调用同一个SqlSession, 并且在这同一个SqlSession当中多次查询同一个数据, 那么仅仅只会执行一次相应的SQL语句, 之后会直接从SQL缓存当中进行获取以我的测试类为例@Test结果如图所示, 跟我们预想的一样, 在第一级别的缓存下, 仅仅调用了一次相应的查询语句。

2303_79546217的博客 1432

【WRF-Chem教程第四期上】运行 WRF-Chem 模型

完整介绍运行 WRF-Chem 模型的详细步骤

WW、forever的博客 3114

MyBatis

mybatis、mybatis-spring、mybatis-springboot源码学习

parkerJ 647

MimicKit 人形机器人强化学习全身模仿控制算法使用教程

本文介绍了MimicKit运动模仿算法框架的使用指南。主要内容包括:1)安装IsaacGym和依赖项;2)训练模型命令及参数说明;3)测试模型的方法;4)分布式训练配置;5)使用TensorBoard可视化日志;6)动作数据格式说明。该框架支持DeepMimic、AMP、ASE、ADD等算法,包含PPO、AWR等强化学习算法,适用于物理仿真角色动画控制研究。

机器人控制与仿真应用 1203

YOLOv8【第十二章:数据增强与数据工程篇·第10节】主动学习(Active Learning):如何挑选最有价值的样本进行标注!

🏆 本文收录于 《YOLOv8实战:从入门到深度优化》 专栏。该专栏系统复现并梳理全网各类 YOLOv8 改进与实战案例(当前已覆盖分类 / 检测 / 分割 / 追踪 / 关键点 / OBB 检测等方向),坚持持续更新 + 深度解析,质量分长期稳定在 97 分以上,可视为当前市面上 覆盖较全、更新较快、实战导向极强 的 YOLO 改进系列内容之一。

**My Coding Family** 509

Mybatis的批量操作

每种方法都有其适用场景和限制。例如,使用 标签生成的批量 SQL 在某些数据库中可能因为 max_allowed_packet 大小限制而失败。因此,在选择批量处理方案时,需要根据具体的业务需求和数据库特性进行综合考虑。愿你我都能在各自的领域里不断成长,勇敢追求梦想,同时也保持对世界的好奇与善意!

weixin_45809780的博客 2603

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

MyBatis02-mybatis-config.xml配置文件讲解

mybatis-config.xml核心配置文件,内容的讲解

qq_31532983的博客 1405

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Spring Boot整合MyBatis实现简单的CRUD

这篇文章主要针对java初学者,详细介绍如何创建一个基本的springboot项目来对数据库进行crud操作。

沐雨橙风ιε的博客 4490

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

springboot整合mybatis(一)入门

mybatis

xiatianit的博客 3026

MyBatis缓存机制学习

MyBatis缓存机制解析:本文详细介绍了MyBatis的一级缓存和二级缓存机制。一级缓存默认开启,作用域为SqlSession,基于HashMap存储;二级缓存需手动配置,作用域为Mapper级别,支持第三方缓存框架如EhCache。文章通过代码示例演示了缓存特性,测试了缓存生效条件,并详细解析了缓存标签属性(回收策略、刷新间隔等)。同时介绍了MyBatis与EhCache的整合步骤,包括依赖配置、参数调整等。最后分析了二级缓存的适用场景(读多写少、非敏感数据)和局限性(分布式环境不一致、缓存粒度粗等问题

ywl470812087的博客 12万+

MyBatis是什么?MyBatis-Plus是什么?

MyBatis就是负责实现数据持久化的一套半成品程序,MyBatis-Plus是基于MyBatis的一个增强框架。

m0_58137791的博客 508

Mybatis动态查询条件构建的历史演进:MyBatis,MyBatis-Generator-Example,MyBatis-Plus,MyBatis-Flex

Mybatis动态查询条件构建的历史演进:MyBatis,MyBatis-Generator-Example,MyBatis-Plus,MyBatis-Flex。 MyBatis-Generator动态查询条件构建。 updateByExampleSelective的含义。

宋冠巡的博客 1843
下一篇: Mybatis基础
user_path
博客等级 码龄8年 4粉丝 7原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值