MyBatis从未入门到放弃

2023-10-19 16:32
文章标签 入门 放弃 mybatis 从未

本文主要是介绍MyBatis从未入门到放弃,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1. 前戏

  • 本地创建ssm数据库
  • 创建student表
CREATE TABLE `student` (`id` int(11) NOT NULL,`name` varchar(255) DEFAULT NULL,`email` varchar(255) DEFAULT NULL,`age` int(11) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  • 插入两条数据
INSERT INTO `student` VALUES (1001, '曹操', '10010@qq.com', 20);
INSERT INTO `student` VALUES (1002, '刘备', '10086@qq.com', 28);

2. 搭建项目

  • Maven搭建普通的Java项目
Mybatis  // 根目录,工程名
|---src  // 源代码
|---|---main  // 主程序
|---|---|---java  // 主程序的Java源码
|---|---|---resources  // 主程序的配置文件
|---|---test  // 测试程序
|---|---|---java  // 测试程序的Java源码
|---|---|---resources  // 测试程序的配置文件
|---pom.xml  // maven工程的核心配置文件
  • Maven搜索 MySQL和MyBatis坐标加入到pom.xml
<!-- MySQL驱动 -->
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.12</version>
</dependency>
<!-- Mybatis驱动 -->
<dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.6</version>
</dependency>
  • 加入编译插件
<build><resources><resource><directory>src/main/java</directory><!--所在的目录--><includes><!--包括目录下的.properties,.xml 文件都会扫描到--><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource></resources>
</build>
  • src/main/resources下创建连接数据库的配置文件config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!-- settings控制mybatis全局行为的 --><settings><!-- 设置Mybatis输出日志 --><setting name="logImpl" value="STDOUT_LOGGING" /></settings><!-- 环境配置:数据库的连接信息default: 表示默认使用某个数据库信息配置--><environments default="develop"><!-- environment: 一个数据库信息的配置id: 唯一值,表示环境的名称 --><environment id="develop"><!-- transactionManager: mybatis的事务类型type: JDBC(表示使用jdbc中的Connection对象的commit、rollback做事务处理) --><transactionManager type="JDBC"/><!-- dataSource: 表示数据源,连接数据库的type表示数据源的类型,POOLED表示使用连接池 --><dataSource type="POOLED"><!-- driver、user、password是固定的 --><!-- 数据库的驱动类名 --><property name="driver" value="com.mysql.cj.jdbc.Driver"/><!-- 连接数据库的url字符串  --><property name="url" value="jdbc:mysql://localhost:3306/ssm?useSSL=false&amp;serverTimezone=Asia/Shanghai"/><!-- 访问数据库的用户名 --><property name="username" value="root"/><!-- 访问数据库的密码 --><property name="password" value="root"/></dataSource></environment><environment id="test"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="${driver}"/><property name="url" value="${url}"/><property name="username" value="${username}"/><property name="password" value="${password}"/></dataSource></environment><environment id="online"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="${driver}"/><property name="url" value="${url}"/><property name="username" value="${username}"/><property name="password" value="${password}"/></dataSource></environment></environments><!-- sql mapper(sql映射文件)的位置 --><mappers><!-- 一个mapper标签指定一个文件的位置从类路径开始的路径信息,就是编译后target/classes开始的操作类配置路径--><mapper resource="com/buddha/dao/StudentDao.xml"/></mappers></configuration>

3. 编写代码

  • src/main/java下创建包com.buddha,并在包下创建两个目录domain和dao目录
  • domain目录下创建Student类
package com.buddha.domain;public class Student {private Integer id;private String name;private String email;private Integer age;public Student() {}public Student(Integer id, String name, String email, Integer age) {this.id = id;this.name = name;this.email = email;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 String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}@Overridepublic String toString() {return "Student{" +"id=" + id +", name='" + name + '\'' +", email='" + email + '\'' +", age=" + age +'}';}
}
  • dao目录下创建StudentDao操作接口
package com.buddha.dao;import com.buddha.domain.Student;import java.util.List;// 接口操作Student表
public interface StudentDao {// 查询student表的所有数据public List<Student> selectStudent();
}
  • dao目录下创建StudentDao.xml操作配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.buddha.dao.StudentDao"><!--select: 表示查询操作id: 执行sql语句的唯一标识,mybatis会使用这个id的值来找到要执行的sql语句,可以自定义,但是要求使用接口中的方法名称resultType: 表示结果类型,是sql语句执行后得到的ResultSet,遍历这个ResultSet得到的Java对象的类型。值写的是类型的全限定名称--><select id="selectStudent" resultType="com.buddha.domain.Student">select id,name,email,age from student order by id</select>
</mapper>
<!--sql映射文件,写sql语句的,mybatis会执行这些sql1. 指定约束文件<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">mybatis-3-mapper.dtd是约束文件的名称,扩展名是dtd2. 约束文件作用:限制,检查在当前文件中出现的标签,属性必须符合mybatis的要求3. mapper 是当前文件的根标签,必须的。namespace 叫做命名空间,唯一值,可以是自定义的字符串。要求你使用dao接口的全限定名称4. 在当前文件中,可以使用特定的标签,表示数据库的特定操作<select>: 表示执行查询,放的是查询语句<update>: 表示执行更新,放的是更新语句<insert>: 表示执行插入,放的是插入语句<delete>: 表示执行删除,放的是删除语句
-->

4. 编写测试代码

  • src/test/resources目录下添加配置文件config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!-- settings控制mybatis全局行为的 --><settings><!-- 设置Mybatis输出日志 --><setting name="logImpl" value="STDOUT_LOGGING" /></settings><!-- 环境配置:数据库的连接信息default: 表示默认使用某个数据库信息配置--><environments default="develop"><!-- environment: 一个数据库信息的配置id: 唯一值,表示环境的名称 --><environment id="develop"><!-- transactionManager: mybatis的事务类型type: JDBC(表示使用jdbc中的Connection对象的commit、rollback做事务处理) --><transactionManager type="JDBC"/><!-- dataSource: 表示数据源,连接数据库的type表示数据源的类型,POOLED表示使用连接池 --><dataSource type="POOLED"><!-- driver、user、password是固定的 --><!-- 数据库的驱动类名 --><property name="driver" value="com.mysql.cj.jdbc.Driver"/><!-- 连接数据库的url字符串  --><property name="url" value="jdbc:mysql://localhost:3306/ssm?useSSL=false&amp;serverTimezone=Asia/Shanghai"/><!-- 访问数据库的用户名 --><property name="username" value="root"/><!-- 访问数据库的密码 --><property name="password" value="root"/></dataSource></environment><environment id="test"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="${driver}"/><property name="url" value="${url}"/><property name="username" value="${username}"/><property name="password" value="${password}"/></dataSource></environment><environment id="online"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="${driver}"/><property name="url" value="${url}"/><property name="username" value="${username}"/><property name="password" value="${password}"/></dataSource></environment></environments><!-- sql mapper(sql映射文件)的位置 --><mappers><!-- 一个mapper标签指定一个文件的位置从类路径开始的路径信息,就是编译后target/classes开始的操作类配置路径--><mapper resource="com/buddha/dao/StudentDao.xml"/></mappers></configuration>
  • src/test/java下创建com.buddha,并创建测试类TestStudent类
package com.buddha;import com.buddha.domain.Student;
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 org.junit.Test;import java.io.IOException;
import java.io.InputStream;
import java.util.List;public class TestStudent {@Testpublic void testSelectStudent() throws IOException {// 访问mybatis读取student数据// 1. 定义mybatis主配置文件的名称,从类路径的根开始(target/classes)String config = "config.xml";// 2. 读取这个config表示的文件InputStream is = Resources.getResourceAsStream(config);// 3. 创建SqlSessionFactoryBuilder对象SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();// 4. 创建SqlSessionFactory对象SqlSessionFactory build = builder.build(is);// 5. [重要]从SqlSessionFactory中获取SqlSession对象SqlSession sqlSession = build.openSession();// 6. [重要]指定要执行的sql语句标识,sql映射文件中的命名空间 + "." + idString sqlId = "com.buddha.dao.StudentDao" + "." + "selectStudent";// 7. 通过sqlId找到sql语句,然后执行sql语句List<Student> studentList = sqlSession.selectList(sqlId);// 8. 输出结果// studentList.forEach(stu -> System.out.println(stu));for (Student stu : studentList) {System.out.println(stu);}// 9. 关闭SqlSession对象sqlSession.close();}
}

5. 增删改查

package com.buddha.dao;import com.buddha.domain.Student;import java.util.List;public interface StudentDao {// 查询public List<Student> selectStudent();// 插入public int insertStudent(Student student);// 更新public int updateStudent(Student student);// 删除public int deleteStudent(Student student);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.buddha.dao.StudentDao"><!-- 查询 --><select id="selectStudent" resultType="com.buddha.domain.Student">select id,name,email,age from student order by id</select><!-- 插入 --><insert id="insertStudent">INSERT INTO student VALUES (#{id},#{name},#{email},#{age})</insert><!-- 更新 --><update id="updateStudent">UPDATE student SET age = #{age} WHERE id = #{id}</update><delete id="deleteStudent">DELETE FROM student WHERE id = #{id}</delete>
</mapper>
package com.buddha;import com.buddha.domain.Student;
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 org.junit.Test;import java.io.IOException;
import java.io.InputStream;
import java.util.List;public class TestStudent {@Testpublic void testSelectStudent() throws IOException {// 访问mybatis读取student数据// 1. 定义mybatis主配置文件的名称,从类路径的根开始(target/classes)String config = "config.xml";// 2. 读取这个config表示的文件InputStream is = Resources.getResourceAsStream(config);// 3. 创建SqlSessionFactoryBuilder对象SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();// 4. 创建SqlSessionFactory对象SqlSessionFactory build = builder.build(is);// 5. [重要]从SqlSessionFactory中获取SqlSession对象SqlSession sqlSession = build.openSession();// 6. [重要]指定要执行的sql语句标识,sql映射文件中的命名空间 + "." + idString sqlId = "com.buddha.dao.StudentDao" + "." + "selectStudent";// 7. 通过sqlId找到sql语句,然后执行sql语句List<Student> studentList = sqlSession.selectList(sqlId);// 8. 输出结果// studentList.forEach(stu -> System.out.println(stu));for (Student stu : studentList) {System.out.println(stu);}// 9. 关闭SqlSession对象sqlSession.close();}@Testpublic void testInsertStudent() throws IOException {String config = "config.xml";InputStream is = Resources.getResourceAsStream(config);SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();SqlSessionFactory build = builder.build(is);SqlSession sqlSession = build.openSession();String sqlId = "com.buddha.dao.StudentDao" + "." + "insertStudent";Student stu = new Student(1005, "大乔", "10002@qq.com", 18);int i = sqlSession.insert(sqlId, stu);sqlSession.commit();System.out.println("插入数据影响行数:" + i);sqlSession.close();}@Testpublic void testUpdateStudent() throws IOException {String config = "config.xml";InputStream is = Resources.getResourceAsStream(config);SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();SqlSessionFactory build = builder.build(is);SqlSession sqlSession = build.openSession();String sqlId = "com.buddha.dao.StudentDao" + "." + "updateStudent";Student stu = new Student();stu.setId(1005);stu.setAge(25);int i = sqlSession.update(sqlId, stu);sqlSession.commit();System.out.println("更新数据影响行数:" + i);sqlSession.close();}@Testpublic void testDeleteStudent() throws IOException {String config = "config.xml";InputStream is = Resources.getResourceAsStream(config);SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();SqlSessionFactory build = builder.build(is);SqlSession sqlSession = build.openSession();String sqlId = "com.buddha.dao.StudentDao" + "." + "deleteStudent";Student stu = new Student();stu.setId(1005);int i = sqlSession.delete(sqlId, stu);sqlSession.commit();System.out.println("删除数据影响行数:" + i);sqlSession.close();}
}

6. 优化公共部分代码

package com.buddha.utils;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;public class MyBatisUtils {private static SqlSessionFactory factory = null;static {String config = "config.xml";try {InputStream is = Resources.getResourceAsStream(config);factory = new SqlSessionFactoryBuilder().build(is);} catch (IOException e) {e.printStackTrace();}}public static SqlSession getSqlSession() {SqlSession sqlSession = null;if (factory != null) {sqlSession = factory.openSession();}return sqlSession;}
}
package com.buddha;import com.buddha.domain.Student;
import com.buddha.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;import java.io.IOException;
import java.util.List;public class TestStudent {@Testpublic void testSelectStudent() throws IOException {SqlSession sqlSession = MyBatisUtils.getSqlSession();String sqlId = "com.buddha.dao.StudentDao" + "." + "selectStudent";List<Student> studentList = sqlSession.selectList(sqlId);for (Student stu : studentList) {System.out.println(stu);}sqlSession.close();}
}

7. 动态代理机制

package com.buddha;import com.buddha.dao.StudentDao;
import com.buddha.domain.Student;
import com.buddha.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;import java.io.IOException;
import java.util.List;public class TestStudent {@Testpublic void testSelectStudent() throws IOException {/*** 使用MyBatis的动态代理机制,使用sqlSession.getMapper(dao接口)* getMapper能获取dao接口对于实现类对象*/SqlSession sqlSession = MyBatisUtils.getSqlSession();StudentDao dao = sqlSession.getMapper(StudentDao.class);// 调用dao的方法,执行数据库的操作List<Student> students = dao.selectStudent();for (Student student : students) {System.out.println(student);}sqlSession.close();}
}

这篇关于MyBatis从未入门到放弃的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/241025

相关文章

MyBatis ResultMap 的基本用法示例详解

《MyBatisResultMap的基本用法示例详解》在MyBatis中,resultMap用于定义数据库查询结果到Java对象属性的映射关系,本文给大家介绍MyBatisResultMap的基本... 目录MyBATis 中的 resultMap1. resultMap 的基本语法2. 简单的 resul

Mybatis的分页实现方式

《Mybatis的分页实现方式》MyBatis的分页实现方式主要有以下几种,每种方式适用于不同的场景,且在性能、灵活性和代码侵入性上有所差异,对Mybatis的分页实现方式感兴趣的朋友一起看看吧... 目录​1. 原生 SQL 分页(物理分页)​​2. RowBounds 分页(逻辑分页)​​3. Page

MyBatis Plus 中 update_time 字段自动填充失效的原因分析及解决方案(最新整理)

《MyBatisPlus中update_time字段自动填充失效的原因分析及解决方案(最新整理)》在使用MyBatisPlus时,通常我们会在数据库表中设置create_time和update... 目录前言一、问题现象二、原因分析三、总结:常见原因与解决方法对照表四、推荐写法前言在使用 MyBATis

Mybatis Plus Join使用方法示例详解

《MybatisPlusJoin使用方法示例详解》:本文主要介绍MybatisPlusJoin使用方法示例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,... 目录1、pom文件2、yaml配置文件3、分页插件4、示例代码:5、测试代码6、和PageHelper结合6

MyBatis设计SQL返回布尔值(Boolean)的常见方法

《MyBatis设计SQL返回布尔值(Boolean)的常见方法》这篇文章主要为大家详细介绍了MyBatis设计SQL返回布尔值(Boolean)的几种常见方法,文中的示例代码讲解详细,感兴趣的小伙伴... 目录方案一:使用COUNT查询存在性(推荐)方案二:条件表达式直接返回布尔方案三:存在性检查(EXI

MyBatis编写嵌套子查询的动态SQL实践详解

《MyBatis编写嵌套子查询的动态SQL实践详解》在Java生态中,MyBatis作为一款优秀的ORM框架,广泛应用于数据库操作,本文将深入探讨如何在MyBatis中编写嵌套子查询的动态SQL,并结... 目录一、Myhttp://www.chinasem.cnBATis动态SQL的核心优势1. 灵活性与可

Python中OpenCV与Matplotlib的图像操作入门指南

《Python中OpenCV与Matplotlib的图像操作入门指南》:本文主要介绍Python中OpenCV与Matplotlib的图像操作指南,本文通过实例代码给大家介绍的非常详细,对大家的学... 目录一、环境准备二、图像的基本操作1. 图像读取、显示与保存 使用OpenCV操作2. 像素级操作3.

Mybatis嵌套子查询动态SQL编写实践

《Mybatis嵌套子查询动态SQL编写实践》:本文主要介绍Mybatis嵌套子查询动态SQL编写方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录前言一、实体类1、主类2、子类二、Mapper三、XML四、详解总结前言MyBATis的xml文件编写动态SQL

Mybatis Plus JSqlParser解析sql语句及JSqlParser安装步骤

《MybatisPlusJSqlParser解析sql语句及JSqlParser安装步骤》JSqlParser是一个用于解析SQL语句的Java库,它可以将SQL语句解析为一个Java对象树,允许... 目录【一】jsqlParser 是什么【二】JSqlParser 的安装步骤【三】使用场景【1】sql语

mybatis的mapper对应的xml写法及配置详解

《mybatis的mapper对应的xml写法及配置详解》这篇文章给大家介绍mybatis的mapper对应的xml写法及配置详解,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,... 目录前置mapper 对应 XML 基础配置mapper 对应 xml 复杂配置Mapper 中的相