持久层框架:Mybatis快速入门

article/2025/10/14 8:28:39

这里写图片描述

Mybatis/Hibernate/JPA作为持久层使用广泛的框架,在实际的项目中有很多的追随者。这篇文章将会通过简单的实例让完全不知道Mybatis为何物的入门者迅速Catchup,对于有一些Java基础的入门者应该能够很快学会如何使用Mybatis进行CRUD(增查改删)操作。

Mybatis的前世今生

时间详细
2002iBATIS一词来源于“internet”+“abatis”,是由Clinton Begin在2002年发起的开放源代码项目。是Apache旗下的项目
2010由ASF(Apache Software Foundation) 迁到了Google Code,并改名为MyBatis
2013迁到Github(https://github.com/mybatis/mybatis-3)。目前最新版本为3.4.1

目标

通过阅读和练习,预定达到以下目标

项番详细内容
No.1Mybatis项目环境搭建
No.2使用Mybatis进行CRUD操作

预估练习时长:15分钟以内

事前准备

下载Mybatis

项目详细信息
类型Mybatis的JAR文件
版本3.4.1
URLhttps://github.com/mybatis/mybatis-3/releases

下载JDBC驱动

项目详细信息
类型MySQL的JDBC驱动
版本5.1.40
URLhttp://dev.mysql.com/downloads/connector/j/

DB设定

DB使用MySQL5.7,详细安装以及创建DB和Table请参看同样是持久层框架的Hibernate的如下入门内容。

项番内容URL
No.1概要及准备http://blog.csdn.net/liumiaocn/article/details/53555787
No.2JDBC方式访问数据库http://blog.csdn.net/liumiaocn/article/details/53559810

创建项目

创建项目,将上面下载的JAR文件加入到Dependencies中即可。

mybatis设定文件

在src根目录创建mybatis-config.xm设定文件,具体内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><environments default="DEV"><environment id="DEV"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/hbtestdb?useSSL=false"/><property name="username" value="hbtestuser01"/><property name="password" value="hbtestuser01"/></dataSource></environment></environments><mappers><mapper class="com.liumiao.entity.UserMapper"/></mappers>
</configuration>

mapper也可以使用resouce的方式,使用xml进行mapping,本文将使用注解方式。

创建User类和UserMapper接口

User类

package com.liumiao.entity;public class User {private int userid;private String username;private String country;public User() {}public User(int userid, String username, String country) {this.userid = userid;this.username = username;this.country = country;}public int getUserid() {return userid;}public void setUserid(int userid) {this.userid = userid;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getCountry() {return country;}public void setCountry(String country) {this.country = country;}@Overridepublic String toString(){return "User Information: "+userid+":"+username+":"+country;}
}

UserMapper接口

package com.liumiao.entity;import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;public interface UserMapper {@Insert("insert into hbtableuser (userid, username, country) values(#{userid},#{username}, #{country})")public int insertUser(User user);@Delete("delete from hbtableuser where userid = #{userid}")public  int deleteUser(int userid);@Delete("delete from hbtableuser")public int deleteAllUser();@Update("update hbtableuser set username=#{username}, country=#{country} where userid=#{userid}")public  int updateUser(User user);@Select("select userid, username, country from hbtableuser where userid=#{userid}")public User retrieveUserByUserid(int userid);
}

Demo演示代码

import com.liumiao.entity.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.liumiao.entity.User;public class Main {public static void main(String[] args) {try {//Get SessionFactory & SessionSqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));SqlSession sqlSession = sqlSessionFactory.openSession();System.out.println("Successfully got sqlSession from session factory.");//Get UserMapperUserMapper userMapper = sqlSession.getMapper(UserMapper.class);//CRUD: Delete All UsersuserMapper.deleteAllUser();sqlSession.commit();//CRUD: Create: Add user : 1001 liumiaocnSystem.out.println("CRUD: Create: add 1001 ");User user = new User(1001,"liumiaocn","China");System.out.println("Now Begin to add user 1001: "+ user);userMapper.insertUser(user);sqlSession.commit();System.out.println("CRUD: Create: add 1002 ");user = new User(1002,"Michael","PRC");System.out.println("Now Begin to add user 1002: "+ user);userMapper.insertUser(user);sqlSession.commit();System.out.println();//CRUD: Retrieve:  user : 1001System.out.println("CRUD: Retrieve:  1001 ");user = userMapper.retrieveUserByUserid(1001);sqlSession.commit();System.out.println("Retrieved user data: "+user);//CRUD: Retrieve:  user : 1002System.out.println("CRUD: Retrieve:  1002 ");user = userMapper.retrieveUserByUserid(1002);sqlSession.commit();System.out.println("Retrieved user data: "+user);System.out.println();//CRUD: Update:  user : 1001System.out.println("CRUD: Update:  1001 ");User tmpUser = new User(1001,"MichaelLiu","PRC");userMapper.updateUser(tmpUser);sqlSession.commit();System.out.println("Retrieved user data: "+user);//CRUD: Retrieve:  user : 1001System.out.println("CRUD: Retrieve:  1001 ");user = userMapper.retrieveUserByUserid(1001);sqlSession.commit();System.out.println("Retrieved user data after Update : "+user);System.out.println();//CRUD: DeleteSystem.out.println("CRUD: Delete:  1002 ");userMapper.deleteUser(1002);sqlSession.commit();sqlSession.close();}catch(Exception e){System.out.println("Exception happened...");e.printStackTrace();}}
}

实施结果确认

Successfully got sqlSession from session factory.
CRUD: Create: add 1001 
Now Begin to add user 1001: User Information: 1001:liumiaocn:China
CRUD: Create: add 1002 
Now Begin to add user 1002: User Information: 1002:Michael:PRCCRUD: Retrieve:  1001 
Retrieved user data: User Information: 1001:liumiaocn:China
CRUD: Retrieve:  1002 
Retrieved user data: User Information: 1002:Michael:PRCCRUD: Update:  1001 
Retrieved user data: User Information: 1002:Michael:PRC
CRUD: Retrieve:  1001 
Retrieved user data after Update : User Information: 1001:MichaelLiu:PRCCRUD: Delete:  1002 

http://chatgpt.dhexx.cn/article/JjXxOaNY.shtml

相关文章

持久层框架JPA与Mybatis该如何选型

一、现状描述 目前java 持久层ORM框架应用最广泛的就是JPA和Mybatis。JPA只是一个ORM框架的规范, 对该规范的实现比较完整就是Spring Data JPA&#xff08;底层基于Hibernate实现&#xff09;&#xff0c;是基于Spring的数据持久层框架&#xff0c;也就是说它只能用在Spring环…

Java持久层框架之mybatis使用

一.什么是框架,框架从何而来,为什么使用框架? 框架(framework): 1.是一系列jar包,其本质是对JDK功能的拓展.(jar包,jar:class文件的压缩包) 2.框架是一组程序的集合,包含了一系列的最佳实践,作用是解决某一个领域的问题. 最佳实践(Best Practice):实际上是无数程序员经历过无数…

数据持久层框架Mybatis

目录 1.软件开发3层架构 2.什么是框架&#xff1f; 3.传统JDBC开发的不足&#xff1f; 4.什么是Mybatis&#xff1f; 5.Mybatis入门案例&#xff1f; 6.Mybatis增删改查案例&#xff1f; 7.Mybatis代理实现DAO开发&#xff1f; 8.Mybatis高级映射 1.软件开发3层架构 软…

常见持久层框架赏析,到底是什么让你选择 MyBatis?

在绝大多数在线应用场景中&#xff0c;数据是存储在关系型数据库中的&#xff0c;当然&#xff0c;有特殊要求的场景中&#xff0c;我们也会将其他持久化存储&#xff08;如 ElasticSearch、HBase、MongoDB 等&#xff09;作为辅助存储。但不可否认的是&#xff0c;关系型数据库…

Java持久层框架

一、ORM框架 ORM:对象关系映射(英语:(Object Relational Mapping&#xff0c;简称ORM&#xff0c;或O/RM&#xff0c;或O/R mapping)&#xff0c;是一种程序技术&#xff0c;用于实现面向对象编程语言里不同类型系统的数据之间的转换 。从效果上说&#xff0c;它其实是创建了一…

17-Spring持久层框架整合

上一篇&#xff1a;16-Spring 基于注解的AOP编程、AOP总结https://blog.csdn.net/fsjwin/article/details/109482768 1.为什么Spring要与持久层框架进行整合 spring是一个优秀的框架&#xff0c;他的优秀支持就是能整合所有程序员想要让他整合的框架&#xff0c;这里所说的持…

MyBatis持久层框架

文章目录 一、Maven搭建1、本地maven仓库以及本地依赖2、idea搭建maven环境3、配置Product实体类4、配置Product接口5、配置db.properties文件6、配置SqlMapperConfig.xml文件7、配置ProductMapper.xml8、配置测试类9、运行 一、Maven搭建 1、本地maven仓库以及本地依赖 2、id…

Java数据持久层框架

一、前言 1.持久层 Java数据持久层&#xff0c;其本身是为了实现与数据源进行数据交互的存在&#xff0c;其目的是通过分层架构风格&#xff0c;进行应用&数据的解耦。 我从整体角度&#xff0c;依次阐述JDBC、Mybatis、MybatisPlus。 前者总是后者的依赖。只有在了解前…

三大框架 —— 持久层框架MyBatis

持久层框架MyBatis 1. mybatis介绍2. 执行流程3. 使用步骤代码实现举例&#xff1a;商品分类CRUD操作 4. 关联关系4.1 一对一4.2 一对多 5. 参数占位符6. 复杂搜索6.1 动态SQL语句6.2 集合参数 1. mybatis介绍 传统框架的缺点&#xff1a; 使用jdbc需要程序员创建连接&#xff…

持久层框架(Mybatis)

持久层框架 工具和框架 工具&#xff1a; JDBC -> DbUtils(QueyRunner) -> JdbcTemplate: 功能简单&#xff0c;SQL语句编写在Java代码中&#xff0c;这是硬编码&#xff0c;高耦合。 框架&#xff1a; 框架是整体解决方案。 如何进行事务控制&#xff0c;如何实现查询缓…

【Java必学框架】一文搞懂Java持久层框架Mybatis,由浅入深

文章目录 一.简介二.快速入门三.映射文件配置详解1.基本增删改查标签、属性2.动态sql2.1\标签2.2\标签 四.核心配置文件1.核心配置文件标签层级关系及作用2.配置示例3.事务管理器4.数据源5.Mapper标签6.自定义类型转换器7.插件机制 五.相应API1.工具对象2.openSession方法3.Sql…

python怎么输入根号

今天我们来说一说Python中如何实现对一个数字开平方。有三种解决办法、 下面我们分别来演示Python中数字开平方的三种方法 第一种方法&#xff1a;使用math模块&#xff0c;使用之前需要先调用,如下 第二种方法&#xff1a;使用内置函数pow(),如下 第三种方法&#xff1a;使用数…

Python-开根号的几种方式

文章目录 前言方法一方法二方法三 前言 使用Python中的自带库math、自带函数pow和自带库cmath来对数字进行开根号运算 方法一 使用&#xff1a;math.sqrt(数字) import math n int(input(数字:)) x math.sqrt(n) print(x) print(type(x)) #开根号后的类型为float方法二 使用&…

chatgpt赋能python:Python开根号:从入门到精通

Python开根号&#xff1a; 从入门到精通 Python是一种通用的高级编程语言&#xff0c;被广泛应用于数据、人工智能、网络应用、图像处理等多个领域。其中&#xff0c;数学计算是使用Python的常见场景之一&#xff0c;而在数学计算中&#xff0c;常常需要对数值进行开根号运算。…

求解任意正整数n开根号的值,不用函数求解√2(根号二),二分法求根号,定义函数fun()求根号,二分法查找

求解任意正整数n开根号的值 提示&#xff1a;理解二分法、函数调用 定义函数double fun(int n)实现 #include<bits/stdc.h> //万能函数头文件 using namespace std; double fun(int n); //定义一个求解根号的函数声明 int main() { int n;cout<<"输入想…

C语言根号作用,c语言中如何开根号运算

用math.h里封装好的函数&#xff0c;具体如下&#xff1a; 求平方根&#xff1a;double sqrt(double x) 例&#xff1a; #include #include int main(void) { double x 4.0, result; result sqrt(x); printf("The square root of %lf is %lf ", x, result); retu…

JavaScript中的乘方和开根号的使用方法

1、乘方 <script>var ikun Math.pow(4,3);console.log(ikun); </script> 2、开根号 <script>var ikun Math.sqrt(64);console.log(ikun); </script> 我们在开根号后还可以再次开根号 <script>var ikun Math.sqrt( Math.sqrt(81));console.…

python三种方法开根号(穷举法、二分法、牛顿拉夫逊法)

文章目录 方法一&#xff1a;穷举法方法二&#xff1a;二分法方法三&#xff1a;牛顿-拉夫逊算法总结 方法一&#xff1a;穷举法 positive_num int(input("输入一个正数:")) #无穷逼近法 answer0 #正数的根号结果 numGuess0 #循环次数 epsilon0.01 …

计算机开根号原理,根号的原理_怎么开的根号,有原理吗

怎么开的根号,有原理吗 JPG&#xff0c;526x296&#xff0c;128KB&#xff0c;444_250 怎么在数轴上画出根号3,求详细过程和原理 JPG&#xff0c;600x293&#xff0c;231KB&#xff0c;514_250 求根号 X 2 2 9 根号 X 3 2 4 的最小值 JPG&#xff0c;598x800&#xff0c;128KB&…

python中根号怎么输入_python中根号怎么表示

sqrt() 方法返回数字x的平方根。 以下是 sqrt() 方法的语法:&#xff08;推荐学习&#xff1a;Python视频教程&#xff09;import math math.sqrt( x ) 注意&#xff1a;sqrt()是不能直接访问的&#xff0c;需要导入 math 模块&#xff0c;通过静态对象调用该方法。 参数 x…