MyBatis学习(一)
https://img2022.cnblogs.com/blog/1954882/202206/1954882-20220625013009089-1279856690.png一、什么是MyBatis根据官网介绍:
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射;
MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作;
MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
二、JDBC编程分析
首先按照以往使用JDBC的方式来访问数据库:
JDBC实现数据库操作 public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
//1.加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取数据库连接
DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8",
"root", "root");
//3.定义sql语句
String sql = "select * from user where username = ?";
//4.获取预处理对象
preparedStatement = connection.prepareStatement(sql);
//5.设置参数
preparedStatement.setString(1, "王五");
//6.查询数据库
resultSet = preparedStatement.executeQuery();
//7.遍历查询的结果集
while (resultSet.next()) {
System.out.println(resultSet.getString("id") + "--" +
resultSet.getString("username"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//8.释放资源
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
} 虽然上述未经封装的JDBC代码可实现查询数据库记录的操作,但是分析上述代码可发现以下问题:
[*]数据库连接创建、释放会很频繁,从而导致系统资源的浪费;
[*]SQL语句存在于代码中,而实际应用的过程中SQL语句可能时常发生变化,从而导致需要经常改动Java代码,造成代码不易维护;
[*]对结果集的解析存在硬编码(查询列名),SQL变化会导致解析代码变化,系统不易维护;
针对上述存在的问题,可采用下述办法进行解决:
[*]可通过数据库连接池来解决数据库连接频繁创建、释放问题;
[*]将SQL语句独立于代码存放用来解决SQL语句在代码中硬编码的问题;
[*]将数据库记录封装成POJO对象进行解析来解决结果集的解析存在硬编码问题;
而本次学习的MyBatis即可实现上述操作。
三、MyBatis快速入门
[*]创建Maven工程,导入相关依赖
pom.xml <dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
</dependencies>
[*]编写User实体类
User.javapublic class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", birthday=" + birthday + ", " +
"sex=" + sex + ", address=" + address + "]";
}
}
[*]编写持久层接口
UserDao.javapublic interface UserDao {
List<User> findAll();
}
[*]编写持久层接口的映射文件
UserDao.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" >
<mapper namespace="com.dcyl.dao.UserDao">
<select id="findALL" resultMap="com.dcyl.domain.User">
select * from user
</select>
</mapper>
[*]编写SqlMapConfig.xml文件
SqlMapConfig.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="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/dcyl/dao/UserDao.xml"/>
</mappers>
</configuration>
[*]编写测试类
MyBatisTestpublic class MybatisTest {
public static void main(String[] args) throws Exception {
//1.读取配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建SqlSessionFactory的构建者对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//3.使用构建者创建工厂对象SqlSessionFactory
SqlSessionFactory factory = builder.build(in);
//4.使用SqlSessionFactory生产SqlSession对象
SqlSession session = factory.openSession();
//5.使用SqlSession创建dao接口的代理对象
UserDao userDao = session.getMapper(UserDao.class);
//6.使用代理对象执行查询所有方法
List<User> users = userDao.findAll();
for (User user : users) {
System.out.println(user);
}
//7.释放资源
session.close();
in.close();
}
} 至此关于MyBatis的入门案例已经完成,接下来就是关于MyBatis的具体细节的讲解。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页:
[1]