【愚公系列】2023年05月 Java教学课程 115-Mybatis的基本使用

举报
愚公搬代码 发表于 2023/05/31 22:22:52 2023/05/31
【摘要】 一.Mybatis快速入门1.1 框架介绍框架是指一种软件或编程语言的结构或基础,可以帮助开发人员快速构建复杂的应用程序。框架通常包括一系列的工具、库和规范,以便开发人员更容易地编写、测试和维护代码。框架可以帮助开发人员提高生产力、降低开发成本、提高代码质量和可维护性,同时也能够提供一些常用的功能和模块,使得开发者能够快速构建出具有一定规模和复杂度的应用程序。常见的框架包括Web开发框架、移...

一.Mybatis快速入门

1.1 框架介绍

框架是指一种软件或编程语言的结构或基础,可以帮助开发人员快速构建复杂的应用程序。框架通常包括一系列的工具、库和规范,以便开发人员更容易地编写、测试和维护代码。框架可以帮助开发人员提高生产力、降低开发成本、提高代码质量和可维护性,同时也能够提供一些常用的功能和模块,使得开发者能够快速构建出具有一定规模和复杂度的应用程序。常见的框架包括Web开发框架、移动开发框架、游戏开发框架等。

1.2 ORM介绍

ORM(Object-Relational Mapping)是一种将对象和关系型数据库进行映射的技术,它可以将数据库操作转化为面向对象的操作,从而简化了开发人员的工作。ORM将数据库中的表映射为对象,将表中的行映射为对象的属性,将表中的列映射为对象的字段。通过ORM,开发人员只需要使用面向对象的方式操作数据库,无需关心底层数据库的细节。

ORM的优点包括:

• 简化了开发,提高了开发效率。

• 可以减少开发人员编写SQL语句的工作量。

• 使开发人员可以使用面向对象的方式操作数据库,降低了学习成本。

• 可以提高代码的可读性和可维护性。

• 可以自动创建数据库表和字段,减少了手动管理数据库的工作量。

ORM的缺点包括:

• 可能会影响系统的性能和效率。

• 需要额外的资源和工具的支持。

• ORM的映射可能不够灵活,无法满足复杂的查询需求。

• 对于复杂的数据模型,ORM可能会存在一定的限制。

ORM是一种非常有用的技术,可以简化开发人员的工作,提高开发效率,但同时也需要开发人员在使用时注意其性能和灵活性。

1.3 什么是Mybatis

Mybatis是一款基于Java语言的ORM框架,它的全称是MyBatis SQL Mapper Framework。Mybatis的主要功能是将Java对象和数据库中的记录进行映射,使得Java程序员可以使用面向对象的方式来操作数据库,同时也可以提高开发效率和代码的可维护性。Mybatis具有以下特点:

• 映射文件配置简单,易于维护。

• 支持动态SQL语句,可以根据不同的条件生成不同的SQL语句。

• 提供了多种查询方式,包括简单查询、复杂查询、分页查询等。

• 支持事务管理,可以保证数据的完整性和一致性。

• 可以与Spring等框架集成,提供更加便捷的开发方式。

• 性能优异,具有高并发、低延迟等特点。

MyBatis官网地址:http://www.mybatis.org/mybatis-3/

1.4 Mybatis的快速入门

MyBatis开发步骤:

1. 添加MyBatis的jar包

2. 创建Student数据表

3. 编写Studentr实体类

4. 编写映射文件StudentMapper.xml

5. 编写核心文件MyBatisConfig.xml

6. 编写测试类

1.4.1 环境搭建

1)导入MyBatis的jar包

• mysql-connector-j-8.0.32.jar

• mybatis-3.5.13.jar

• log4j-1.2.17.jar

1. 创建student数据表


1. 编写Student实体

package com.itheima.bean;

public class Student {
private Integer id;
private String name;
private Integer age;

public Student() {
}

public Student(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}

4)编写jdbc.properties映射文件

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/db1
username=root
password=123456

5)编写log4j.properties映射文件

# Global logging configuration
# ERROR WARN INFO DEBUG
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n


6)编写MyBatisConfig.xml映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!--MyBatis的DTD约束-->
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">

<!--configuration 核心根标签-->
<configuration>

<!--引入数据库连接的配置文件-->
<properties resource="jdbc.properties"/>

<!--配置LOG4J-->
<settings>
<setting name="logImpl" value="log4j"/>
</settings>

<!--起别名-->
<typeAliases>
<typeAlias type="com.itheima.bean.Student" alias="student"/>
<!--<package name="com.itheima.bean"/>-->
</typeAliases>

<!--environments配置数据库环境,环境可以有多个。default属性指定使用的是哪个-->
<environments default="mysql">
<!--environment配置数据库环境 id属性唯一标识-->
<environment id="mysql">
<!-- transactionManager事务管理。 type属性,采用JDBC默认的事务-->
<transactionManager type="JDBC"></transactionManager>
<!-- dataSource数据源信息 type属性 连接池-->
<dataSource type="POOLED">
<!-- property获取数据库连接的配置信息 -->
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
</environments>

<!-- mappers引入映射配置文件 -->
<mappers>
<!-- mapper 引入指定的映射配置文件 resource属性指定映射配置文件的名称 -->
<mapper resource="StudentMapper.xml"/>
</mappers>
</configuration>

7)编写StudentMapper.xml映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!--MyBatis的DTD约束-->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--
mapper:核心根标签
namespace属性:名称空间
-->
<mapper namespace="StudentMapper">
<!--
select:查询功能的标签
id属性:唯一标识
resultType属性:指定结果映射对象类型
parameterType属性:指定参数映射对象类型
-->
<select id="selectAll" resultType="student">
SELECT * FROM student
</select>

<select id="selectById" resultType="student" parameterType="int">
SELECT * FROM student WHERE id = #{id}
</select>

<insert id="insert" parameterType="student">
INSERT INTO student VALUES (#{id},#{name},#{age})
</insert>

<update id="update" parameterType="student">
UPDATE student SET name = #{name},age = #{age} WHERE id = #{id}
</update>

<delete id="delete" parameterType="int">
DELETE FROM student WHERE id = #{id}
</delete>
</mapper>

1.4.2 StudentMapper搭建

package com.itheima.service;

import com.itheima.bean.Student;

import java.util.List;
/*
业务层接口
*/
public interface StudentService {
//查询全部
public abstract List<Student> selectAll();

//根据id查询
public abstract Student selectById(Integer id);

//新增数据
public abstract Integer insert(Student stu);

//修改数据
public abstract Integer update(Student stu);

//删除数据
public abstract Integer delete(Integer id);
}

package com.itheima.mapper.impl;

import com.itheima.bean.Student;
import com.itheima.mapper.StudentMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/*
持久层实现类
*/
public class StudentMapperImpl implements StudentMapper {

/*
查询全部
*/
@Override
public List<Student> selectAll() {
List<Student> list = null;
SqlSession sqlSession = null;
InputStream is = null;
try{
//1.加载核心配置文件
is = Resources.getResourceAsStream("MyBatisConfig.xml");

//2.获取SqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

//3.通过工厂对象获取SqlSession对象
sqlSession = sqlSessionFactory.openSession(true);

//4.执行映射配置文件中的sql语句,并接收结果
list = sqlSession.selectList("StudentMapper.selectAll");

} catch (Exception e) {
e.printStackTrace();
} finally {
//5.释放资源
if(sqlSession != null) {
sqlSession.close();
}
if(is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

//6.返回结果
return list;
}

/*
根据id查询
*/
@Override
public Student selectById(Integer id) {
Student stu = null;
SqlSession sqlSession = null;
InputStream is = null;
try{
//1.加载核心配置文件
is = Resources.getResourceAsStream("MyBatisConfig.xml");

//2.获取SqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

//3.通过工厂对象获取SqlSession对象
sqlSession = sqlSessionFactory.openSession(true);

//4.执行映射配置文件中的sql语句,并接收结果
stu = sqlSession.selectOne("StudentMapper.selectById",id);

} catch (Exception e) {
e.printStackTrace();
} finally {
//5.释放资源
if(sqlSession != null) {
sqlSession.close();
}
if(is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

//6.返回结果
return stu;
}

/*
新增功能
*/
@Override
public Integer insert(Student stu) {
Integer result = null;
SqlSession sqlSession = null;
InputStream is = null;
try{
//1.加载核心配置文件
is = Resources.getResourceAsStream("MyBatisConfig.xml");

//2.获取SqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

//3.通过工厂对象获取SqlSession对象
sqlSession = sqlSessionFactory.openSession(true);

//4.执行映射配置文件中的sql语句,并接收结果
result = sqlSession.insert("StudentMapper.insert",stu);

} catch (Exception e) {
e.printStackTrace();
} finally {
//5.释放资源
if(sqlSession != null) {
sqlSession.close();
}
if(is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

//6.返回结果
return result;
}

/*
修改功能
*/
@Override
public Integer update(Student stu) {
Integer result = null;
SqlSession sqlSession = null;
InputStream is = null;
try{
//1.加载核心配置文件
is = Resources.getResourceAsStream("MyBatisConfig.xml");

//2.获取SqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

//3.通过工厂对象获取SqlSession对象
sqlSession = sqlSessionFactory.openSession(true);

//4.执行映射配置文件中的sql语句,并接收结果
result = sqlSession.update("StudentMapper.update",stu);

} catch (Exception e) {
e.printStackTrace();
} finally {
//5.释放资源
if(sqlSession != null) {
sqlSession.close();
}
if(is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

//6.返回结果
return result;
}

/*
删除功能
*/
@Override
public Integer delete(Integer id) {
Integer result = null;
SqlSession sqlSession = null;
InputStream is = null;
try{
//1.加载核心配置文件
is = Resources.getResourceAsStream("MyBatisConfig.xml");

//2.获取SqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

//3.通过工厂对象获取SqlSession对象
sqlSession = sqlSessionFactory.openSession(true);

//4.执行映射配置文件中的sql语句,并接收结果
result = sqlSession.delete("StudentMapper.delete",id);

} catch (Exception e) {
e.printStackTrace();
} finally {
//5.释放资源
if(sqlSession != null) {
sqlSession.close();
}
if(is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

//6.返回结果
return result;
}
}

1.4.3 StudentService搭建

package com.itheima.service;

import com.itheima.bean.Student;

import java.util.List;
/*
业务层接口
*/
public interface StudentService {
//查询全部
public abstract List<Student> selectAll();

//根据id查询
public abstract Student selectById(Integer id);

//新增数据
public abstract Integer insert(Student stu);

//修改数据
public abstract Integer update(Student stu);

//删除数据
public abstract Integer delete(Integer id);
}

package com.itheima.service.impl;

import com.itheima.bean.Student;
import com.itheima.mapper.StudentMapper;
import com.itheima.mapper.impl.StudentMapperImpl;
import com.itheima.service.StudentService;

import java.util.List;
/*
业务层实现类
*/
public class StudentServiceImpl implements StudentService {

//创建持久层对象
private StudentMapper mapper = new StudentMapperImpl();

@Override
public List<Student> selectAll() {
return mapper.selectAll();
}

@Override
public Student selectById(Integer id) {
return mapper.selectById(id);
}

@Override
public Integer insert(Student stu) {
return mapper.insert(stu);
}

@Override
public Integer update(Student stu) {
return mapper.update(stu);
}

@Override
public Integer delete(Integer id) {
return mapper.delete(id);
}
}

1.4.4 StudentController搭建

package com.itheima.controller;

import com.itheima.bean.Student;
import com.itheima.service.StudentService;
import com.itheima.service.impl.StudentServiceImpl;

import java.util.List;

/*
控制层测试类
*/
public class StudentController {
//创建业务层对象
private StudentService service = new StudentServiceImpl();

//查询全部功能测试
public void selectAll() {
List<Student> students = service.selectAll();
for (Student stu : students) {
System.out.println(stu);
}
}

//根据id查询功能测试
public void selectById() {
Student stu = service.selectById(3);
System.out.println(stu);
}

//新增功能测试
public void insert() {
Student stu = new Student(4,"赵六",26);
Integer result = service.insert(stu);
System.out.println(result);
}

//修改功能测试
public void update() {
Student stu = new Student(4,"赵六",16);
Integer result = service.update(stu);
System.out.println(result);
}

//删除功能测试
public void delete() {
Integer result = service.delete(4);
System.out.println(result);
}
}

1.4.5 运行

package com.itheima;

import com.itheima.controller.StudentController;

public class Main {
public static void main(String[] args) {
StudentController stu=new StudentController();
stu.selectAll();
}
}


二、MyBatis的相关api

1.1 Resources

• org.apache.ibatis.io.Resources:加载资源的工具类。

• 核心方法


1.2 构建器SqlSessionFactoryBuilder

• org.apache.ibatis.session.SqlSessionFactoryBuilder:获取 SqlSessionFactory 工厂对象的功能类

• 核心方法


• 通过加载mybatis的核心文件的输入流的形式构建一个SqlSessionFactory对象

String resource = "org/mybatis/builder/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(inputStream);

其中, Resources 工具类,这个类在 org.apache.ibatis.io 包中。Resources 类帮助你从类路径下、文件系统或一个 web URL 中加载资源文件。

1.3 工厂对象SqlSessionFactory

• org.apache.ibatis.session.SqlSessionFactory:获取 SqlSession 构建者对象的工厂接口。

• 核心api



1.4 SqlSession会话对象

• org.apache.ibatis.session.SqlSession:构建者对象接口。用于执行 SQL、管理事务、接口代理。

• 核心api

SqlSession 实例在 MyBatis 中是非常强大的一个类。在这里你会看到所有执行语句、提交或回滚事务和获取映射器实例的方法。


【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。