MyBatis
持久化层简介
- 小工具:
- JDBC
- jdbc Template
- 执行过程:
- 编写SQL
- 预编译
- 设置参数
- 执行SQL
- 封装结果
- 特点:功能简单、SQL编写在代码里,硬编码,高耦合的方式。
- 框架:(整体解决方案)
Hibernate(全自动ORM框架)(Object Relation Mapping)旨在消除SQL
封装了以下步骤:
- 编写SQL
- 预编译
- 设置参数
- 执行SQL
- 封装结果
缺点:无法编写SQL,失去了灵活性。MyBatis(半自动,轻量级)
- 封装了以下步骤:
- 预编译
- 设置参数
- 执行SQL
- 封装结果
使用配置文件编写SQL。
- 优点:
1.SQL与代码分离
2。SQL由开发人员控制,方便SQL优化。
Helloword(Maven)
- 添加依赖:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>x.x.x</version>
</dependency>
- 新建一个实体类 User
- 创建一个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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
/*修改相应的数据源*/
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/qingdb"/>
<property name="username" value="root"/>
<property name="password" value="1213151"/>
</dataSource>
</environment>
</environments>
<mappers>
/*注册SQL的XML文件*/
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
- 创建一个类实现以下功能 :
- 从XML 中构建 SqlSessionFactory
/*根据config配置文件(全局配置文件)创建一个SqlSessionFactory 对象*/
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- 创建SQL的一个XML文件
<?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:唯一标识符
resultType:
*/
<mapper namespace="com.chase.qing.MyBatis.UserMappers">
<select id="selectQingUser" resultType="com.chase.qing.entity.QingUser">
select * from quser where unumber = #{unumber}
/*如果字段名和数据库不匹配,可以使用别名的方式*/
/*解决异常*/
<if test="_parameter != null">
and unumber = #{unumber}
</if>
</select>
</mapper>
- 从 SqlSessionFactory 中获取 SqlSession
SqlSession session = sqlSessionFactory.openSession();
try {
User user = (User) session.selectOne("org.mybatis.example.UserMapper.selectBlog", 101);
} finally {
session.close();
}
/*更推荐的方式,避免直接使用sqlSession*/
SqlSession session = sqlSessionFactory.openSession();
try {
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.selectBlog(101);
} finally {
session.close();
}
喜欢的话可以点点关注,或者添加作者微信,欢迎随时来撩