Mybatis学习笔记
Mybatis是一种面向sql的orm持久层框架,类似于hibernate。
iBatis前身,Mybatis底层依赖jdbc驱动程序,它把传统的jdbc连接数据库过程进行了封装,大大渐少了开发人员的工作量,是开发人员只需要专注于sql本身,而且方便代码维护,和持久利用,不用像传统mybatis那样对sql语句做频繁的修改。
那么先回顾一下传统的jdbc访问数据库过程:
- 加载数据库驱动
- 创建数据库连接
- 创建statement
- 创建sql语句
- 设置查询参数(占位符)
- 执行查询,得到resultSet
- 遍历resultSet,得到结果
- 关闭连接,释放资源(大大消耗了系统资源)
JDBC缺点:
- 频繁创建,打开,关闭数据连接,太消耗资源
- sql语句存在硬编码嫌疑,不利于维护
- sql参数设置硬编码,不利于维护
- 结果集获取与遍历复杂,存在硬编码,不利于维护,期望查询完成后能返回一个Java对象
在idea开发环境中,新建一个mybatis工程,实现表的增删查改
在数据库中建立一张user表
create table user ( ID INT(11) PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(18) DEFAULT NULL, AGE INT(11) DEFAULT NULL )
目录结构:
pom文件配置
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.ming</groupId> <artifactId>hhyMybatis</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> </dependencies> </project>
建立sqlMapConfig来配置数据库信息:
<?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> <!--环境配置,连接的数据库,这里使用的是MySQL--> <environments default="development"> <environment id="development"> <!--指定事务管理的类型,这里简单使用Java的JDBC的提交和回滚设置--> <transactionManager type="JDBC"/> <!--dataSource 指连接源配置,POOLED是JDBC连接对象的数据源连接池的实现--> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?charset=utf8&useSSL=false&allowPublicKeyRetrieval=true"/> <property name="username" value="root"/> <property name="password" value="hhyuan"/> </dataSource> </environment> </environments> <mappers> <!--这是告诉Mybatis区哪找持久化类的映射文件,对于在src下的文件直接写文件名, 如果在某包下,则要写明路径,如:com/mybatistest/config/User.xml--> <mapper resource="User.xml"/> </mappers> </configuration>
建立user.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="test"> <!--跟据id进行查询--><!--statementid,整个select叫做statement--> <select id="GetUserByID" parameterType="int" resultType="com.ming.User"> select * from user where id = #{value} </select> <!--跟据name进行查询--> <select id="GetUserByNAME" parameterType="java.lang.String" resultType="com.ming.User"> select * from user where name like #{value} </select> <insert id="AddUser" parameterType="com.ming.User"> -- 由于id是自增的,所以下面映射的时候不能写id,不写id的情况下,就算手动setid也不会按照你手动添加的id插入,而是自增长的id insert into user(name,age) values (#{name},#{age}) </insert> <update id="ChangeUser" parameterType="com.ming.User"> update user set name=#{name},age=#{age} where id=#{ID} </update> <delete id="DeleteUser" parameterType="java.lang.Integer"> delete from user where id=#{ID} </delete> </mapper> <!--zi zeng zhang yao you zhu jian -->
建立测试类,测试查询:
package com.ming; 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.*; import org.junit.Test; import java.io.InputStream; import java.util.List; /** * @Information: * @Author: HeHaoYuan * @Date: Created at 13:18 on 2020/2/3 * @Package_Name: com.ming */ public class mybatisTest { private SqlSessionFactory sqlSessionFactory = null; @Before public void testInit() { //每执行一次Test都会先执行一遍testInit() InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream("mybatisconfig.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (Exception e){ e.printStackTrace(); } } //通过id查询 @Test public void testGetUserByID(){ SqlSession sqlSession = null; try { sqlSession = sqlSessionFactory.openSession(); User user = sqlSession.selectOne("test.GetUserByID",10); System.out.print("查询结果:"+user); System.out.println("主键返回"+user.getID()); }catch (Exception ex){ ex.printStackTrace(); } finally { sqlSession.close(); } } //通过名字模糊查询 @Test public void testGetUserByNAME(){ SqlSession sqlSession = null; try { sqlSession = sqlSessionFactory.openSession(); List<User> list = sqlSession.selectList("test.GetUserByNAME","%ming%"); System.out.println("模糊查询结果:"+list); }catch (Exception ex){ ex.printStackTrace(); } finally { sqlSession.close(); } } //增 @Test public void testAddUser(){ SqlSession sqlSession = null; try { sqlSession = sqlSessionFactory.openSession(); User user = new User(); user.setName("xiaoming"); user.setAge(36); sqlSession.insert("test.AddUser",user); sqlSession.commit(); System.out.println("添加成功..."); }catch (Exception ex){ ex.printStackTrace(); } finally { sqlSession.close(); } } //改 @Test public void testChangeUser(){ SqlSession sqlSession = null; try { sqlSession = sqlSessionFactory.openSession(); User user = new User(); user.setID(1); user.setAge(23); user.setName("hhyuan"); //sqlSession.insert("test.ChangeUser",user); sqlSession.update("test.ChangeUser",user); sqlSession.commit(); System.out.println("修改成功..."); }catch (Exception ex){ ex.printStackTrace(); } finally { sqlSession.close(); } } //删 @Test public void testDeleteUser(){ SqlSession sqlSession = null; try { sqlSession = sqlSessionFactory.openSession(); User user = new User(); sqlSession.delete("test.DeleteUser",107); sqlSession.commit(); System.out.println("删除成功..."); }catch (Exception ex){ ex.printStackTrace(); } finally { sqlSession.close(); } } }
执行结果: