当前位置:网站首页>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基础篇【命名规范】
- golang : Zap log integration
- Station B collapsed, what would you do if you were the developer in charge that night?
- How to understand plucker coordinates (geometric understanding)
- roslyn folder under bin folder
- MySQL什么时候用表锁,什么时候用行锁?
- 理解和熟悉递归中的尝试
- The introduction of AI meta-learning into neuroscience, the medical effect is expected to improve accurately
- interface
猜你喜欢
Rodrigues: vector representation of rotation matrices
Test Development Engineer Growth Diary 010 - CI/CD/CT in Jenkins (Continuous Integration Build/Continuous Delivery/Continuous Testing)
大飞机C919都用了哪些新材料?
Huawei released "ten inventions", including computing, intelligent driving and other new fields
MYSQL下载及安装完整教程
从 Google 离职,前Go 语言负责人跳槽小公司
New material under the plastic restriction order - polylactic acid (PLA)
什么是微服务?
B站崩了,如果是你是那晚负责的开发人员你会怎么做?
你被MySQL 中的反斜杠 \\坑过吗?
随机推荐
什么是微服务?
Electron使用romote报错 : Uncaught TypeError: Cannot read property ‘BrowserWindow‘ of undefined
让百度地图生成器里的“标注”内容展开--解决方案
Proof of distance calculation from space vertex to plane and its source code
Vue2进阶篇-编程式路由导航、缓存路由组件、路由的激活与失活
Redis download and installation
Is it possible to use the same port for UDP and TCP?
头条二面:MySQL中有几种常见的 SQL 错误用法?
ETL为什么经常变成ELT甚至LET?
相机坐标系,世界坐标系,像素坐标系三者转换,以及OPENGLDEFocal Length和Opengl 的 Fov转换
上传文件--文件类型大全,图片类型,文档类型,视频类型,压缩包类型
go : 使用gorm查询记录
go : create database records using gorm
C# 使用RestSharp 实现Get,Post 请求(2)
bin文件夹下的roslyn文件夹
千万级数据量的表,怎样最快速度查询?
向量的导数运算和向量叉乘以及点乘的导数运算
识别“数据陷阱”,发现数据的可疑之处
Headline 2: there are several kinds of common SQL errors in MySQL usage?
RAID disk array