当前位置:网站首页>MySQL off-topic [ORM thought analysis]
MySQL off-topic [ORM thought analysis]
2022-07-30 08:02:00 【The brain cannot be empty】
1. 什么是ORM?
对象关系映射(Object Relational Mapping,简称ORM)模式是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术.
简单的说,ORM是通过使用描述对象和数据库之间映射的元数据,将程序中的对象自动持久化到关系数据库中.
ORM在业务逻辑层和数据库层之间充当了桥梁的作用.
2. ORM解决了什么问题?
ORM解决的主要问题是对象和关系的映射.It usually has a one-to-one correspondence between a class and a table,类的每个实例对应表中的一条记录,类的每个属性对应表中的每个字段.
ORM提供了对数据库的映射,不用直接编写SQL代码,Data can be manipulated against the database by simply manipulating objects.
让软件开发人员专注于业务逻辑的处理,提高了开发效率.
3. 结合MyBatis理解ORM
3.1 MyBatis是什么?
Mybatisis an excellent semi-automaticORM框架,它对JDBC操作数据库的过程进行封装,原来我们使用JDBCwhen operating the database,需要手动的写代码去注册驱动、获取connection、获取statementand other hard-coded ways to achieve interaction with the database,现在Mybaits帮助我们把这些事情做了,so that we only need to focus on our businesssql即可,能大大提高我们的开发效率.
3.2 MyBatis使用
- 在Maven中引入MyBatis依赖
<!--引入依赖-->
<dependencies>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
<scope>runtime</scope>
</dependency>
</dependencies>
- 创建User实体类-User.java
@Data
@AllArgsConstructor // 全参构造函数
@NoArgsConstructor // 无参构造函数
public class User {
private Long id;
private Integer age;
private String username;
}
- 创建User对应的Mapper接口类-UserDao.java
public interface UserDao {
//查询所有用户
public List<User> findAll() throws Exception;
//根据条件进行用户查询
public User findByCondition(User user) throws Exception;
}
- 创建User的xml文件-UserMapper.xml
@Data
@AllArgsConstructor
@NoArgsConstructor
// namespace 必须是对应UserDao的路径
<mapper namespace = "com.my.dao.UserDao">
<!--查询所有数据-->
<select id="findAll" resultType="com.my.pojo.User" parameterType="com.my.pojo.User">
select * from user
</select>
<!--通过条件查询数据 id是UserDao中的方法 Correspondence is generated at the bottom layer namespace.id=UserDao.方法 It is found through the corresponding relationship when it is called mappedSattement对象 拿出sqlstatements and properties that need to be assignedsql参数填入 然后提交mysql执行-->
<select id="findByCondition" resultType="com.my.pojo.User" parameterType="com.my.pojo.User">
select * from user where id = #{id} and username = #{username}
</select>
</mapper>
- 编写mybatis配置信息-mybatis.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>
<!--加载外部的properties文件--数据库的配置信息-->
<properties resource="jdbc.properties"></properties>
<!--给实体类的全限定类名给别名-->
<typeAliases>
<!--给单独的实体起别名-->
<!-- <typeAlias type="com.my.pojo.User" alias="user"></typeAlias>-->
<!--批量起别名(推荐):该包下所有的类的本身的类名:别名还不区分大小写 比如user类 You can directly get the parameters in the return valueuserThere is no need to rewrite the full path of the class-->
<package name="com.my.pojo"/>
</typeAliases>
<!--environments:运行环境-->
<environments default="development">
<environment id="development">
<!--当前事务交由JDBC进行管理-->
<transactionManager type="JDBC"></transactionManager>
<!--当前使用mybatis提供的连接池-->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--引入映射配置文件-->
<mappers>
<!-- A single file for configuration -->
<!-- <mapper resource="UserMapper.xml"></mapper>-->
<!-- Directly configure the packages that need to be scanned(推荐)The underlying parsing will find the corresponding one based on the full path of the packagemamespace的xml find by method idSame as method for relational mapping -->
<package name="com.my.dao"/>
</mappers>
</configuration>
- 调用Mybatis
/** * By manual submission and definitionstatementmethod to invoke the query * @throws IOException */
@Test
public void test1() throws IOException {
//1.Resources工具类,配置文件的加载,把配置文件加载成字节输入流
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis.xml");
//2.解析了配置文件,并创建了sqlSessionFactory工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//3.生产sqlSession
// 默认开启一个事务,但是该事务不会自动提交,在进行增删改操作时,要手动提交事务
// 注:openSession(true) 传入trueThat is, to turn on auto-commit transactions
SqlSession sqlSession = sqlSessionFactory.openSession();
//4.sqlSession调用方法:查询所有selectList 查询单个:selectOne 添加:insert 修改:update 删除:delete
List<User> users = sqlSession.selectList("com.my.dao.IUserDao.findAll");
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void test6() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
IUserDao mapper = sqlSession.getMapper(IUserDao.class);
User user1 = new User();
user1.setId(4);
user1.setUsername("lucy");
List<User> all = mapper.findByCondition(user1);
for (User user : all) {
System.out.println(user);
}
}
3.3 Mybatis使用总结
- Maven添加MyBatis的坐标
- 创建User数据表
- 编写User实体类
- 编写映射文件UserMapper.xml
- 编写核心文件mybatis.xml
- 编写测试类
边栏推荐
- 预测人们对你的第一印象,“AI颜狗”的诞生
- 【MySQL】MySQL中如何实现分页操作
- golang: Gorm配置Mysql多数据源
- interface
- Ali two sides: Sentinel vs Hystrix comparison, how to choose?
- STL source code analysis: conceptual understanding of iterators, and code testing.
- 新人误删数据,组长巧用MySQL主从复制延迟挽回损失
- bin文件夹下的roslyn文件夹
- B站崩了,如果是你是那晚负责的开发人员你会怎么做?
- 阿里二面:列出 Api 接口优化的几个技巧
猜你喜欢

C# 使用RestSharp 实现Get,Post 请求(2)

2020 ACM | MoFlow: An Invertible Flow Model for Generating Molecular Graphs

Go 结合Gin导出Mysql数据到Excel表格

Pioneer in Distributed Systems - Leslie Lambert

VR机器人教你如何正确打乒乓球

Process and Scheduled Task Management

DNS domain name resolution services

Keil软件中map文件解析

STL源码剖析:bound friend template friend代码测试和理解

从 Google 离职,前Go 语言负责人跳槽小公司
随机推荐
roslyn folder under bin folder
2020 数学建模之旅
node.js中实现对数据库的链式操作
Polygon 3D(三维平面多边形)的法向量的计算(MeshLab默认的计算)
go : go-redis set操作
2020年度总结——品曾经,明得失,展未来
The calculation of the determinant of the matrix and its source code
go : go gin返回JSON数据
go : 使用 grom 删除数据库数据
The first artificial intelligence safety competition officially launched
window.open()的用法,js打开新窗体
bean的生命周期
golang : Zap log integration
Linx common directory & file management commands & VI editor usage introduction
Ali two sides: Sentinel vs Hystrix comparison, how to choose?
不会吧,Log4j 漏洞还没有完全修复?
ArrayList
Go uses the mencached cache
Vue项目通过node连接MySQL数据库并实现增删改查操作
空间直线到平面上的交点的计算证明及其源码