音乐网站开发可行性分析,智慧团建网站pc端,网站建设与运营 市场分析,电子商务主要学什么内容文章目录MyBatisMyBatis基本介绍MyBaits快速入门Mapper代理开发MyBatis配置文件MyBatis
MyBatis基本介绍
什么是MyBatis? MyBatis 是一款优秀的持久层框架#xff0c;用于简化 JDBC 开发 MyBatis 本是 Apache 的一个开源项目iBatis, 2010年这个项目由apache software found…
文章目录MyBatisMyBatis基本介绍MyBaits快速入门Mapper代理开发MyBatis配置文件MyBatis
MyBatis基本介绍
什么是MyBatis? MyBatis 是一款优秀的持久层框架用于简化 JDBC 开发 MyBatis 本是 Apache 的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code并且改名为MyBatis 。2013年11月迁移到Github 官网https://mybatis.org/mybatis-3/zh/index.html 持久层: 负责将数据到保存到数据库的那一层代码 JavaEE三层架构表现层、业务层、持久层 框架: 框架就是一个半成品软件是一套可重用的、通用的、软件基础代码模型 在框架的基础之上构建软件编写更加高效、规范、通用、可扩展 JDBC的缺点: 1.硬编码: 把不固定的变量, 固定成了字符串 2.操作繁琐: 需要手动的设置参数, 获取封装结果集 MyBatis是将硬编码的注册驱动或者编写SQL语句, 放到配置文件中编写: MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作 dataSource typePOOLED!--数据库连接信息--property namedriver valuecom.mysql.jdbc.Driver/property nameurl valuejdbc:mysql:///mybatis?useSSLfalse/property nameusername valueroot/property namepassword value1234/
/dataSourceMyBaits快速入门
案例: 使用MyBatis查询user表中所有数据 首先mysql中准备数据库mybatis, 在mybatis中创建tb_user表添加数据 create database mybatis;
use mybatis;create table tb_user(id int primary key auto_increment,username varchar(20),password varchar(20),gender char(1),addr varchar(30)
);INSERT INTO tb_user VALUES (1, zhangsan, 123, 男, 北京);
INSERT INTO tb_user VALUES (2, 李四, 234, 女, 天津);
INSERT INTO tb_user VALUES (3, 王五, 11, 男, 西安);创建Maven模块导入坐标配置文件 dependencygroupIdjunit/groupIdartifactIdjunit/artifactIdversion3.8.1/versionscopetest/scope
/dependencydependency!-- mybatis依赖 --groupIdorg.mybatis/groupIdartifactIdmybatis/artifactIdversion3.5.5/version
/dependencydependency!-- mysql驱动 --groupIdmysql/groupIdartifactIdmysql-connector-java/artifactIdversion5.1.46/version
/dependency!-- 添加slf4j日志api --
dependencygroupIdorg.slf4j/groupIdartifactIdslf4j-api/artifactIdversion1.7.20/version
/dependency
!-- 添加logback-classic依赖 --
dependencygroupIdch.qos.logback/groupIdartifactIdlogback-classic/artifactIdversion1.2.3/version
/dependency
!-- 添加logback-core依赖 --
dependencygroupIdch.qos.logback/groupIdartifactIdlogback-core/artifactIdversion1.2.3/version
/dependency
/dependencies因为使用到了日志, 所以需要配置日志打印文件: logback.xml ?xml version1.0 encodingUTF-8?
configuration!-- CONSOLE 表示当前的日志信息是可以输出到控制台的。--appender nameConsole classch.qos.logback.core.ConsoleAppenderencoderpattern[%level] %blue(%d{HH:mm:ss.SSS}) %cyan([%thread]) %boldGreen(%logger{15}) - %msg %n/pattern/encoder/appenderlogger namecom.itheima levelDEBUG additivityfalseappender-ref refConsole//logger!--level:用来设置打印级别大小写无关TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF 默认debugroot可以包含零个或多个appender-ref元素标识这个输出位置将会被本日志级别控制。--root levelDEBUGappender-ref refConsole//root
/configuration编写SQL映射文件: UserMapper.xml 用于统一管理sql语句解决硬编码问题 ?xml version1.0 encodingUTF-8 ?
!DOCTYPE mapperPUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttps://mybatis.org/dtd/mybatis-3-mapper.dtd!-- namespace 名称空间 --
mapper namespacetest!-- id是sql语句的唯一标识, resultType返回值类型 --select idselectAll resultTypecom.chenyq.pojo.UserSELECT * FROM tb_user;/select
/mapper配置mybatis核心配置文件: mybatis-config.xm, 配置数据库连接环境, 已经加载sql映射文件l ?xml version1.0 encodingUTF-8 ?
!DOCTYPE configurationPUBLIC -//mybatis.org//DTD Config 3.0//ENhttp://mybatis.org/dtd/mybatis-3-config.dtd
configurationtypeAliasespackage namecom.chenyq.pojo//typeAliases!--environments配置数据库连接环境信息。可以配置多个environment通过default属性切换不同的environment--environments defaultdevelopmentenvironment iddevelopmenttransactionManager typeJDBC/dataSource typePOOLED!--数据库连接信息--property namedriver valuecom.mysql.jdbc.Driver/property nameurl valuejdbc:mysql:///mybatis?useSSLfalse/property nameusername valueroot/property namepassword value123456789//dataSource/environment/environmentsmappers!--加载sql映射文件--mapper resourceUserMapper.xml//mappers
/configuration编码: 定义实体类User public class User {private Integer id;private String username;private String password;private char gender;private String addr;public User() {}public User(Integer id, String username, String password, char gender, String addr) {this.id id;this.username username;this.password password;this.gender gender;this.addr addr;}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 String getPassword() {return password;}public void setPassword(String password) {this.password password;}public char getGender() {return gender;}public void setGender(char gender) {this.gender gender;}public String getAddr() {return addr;}public void setAddr(String addr) {this.addr addr;}Overridepublic String toString() {return User{ id id , username username \ , password password \ , gender gender , addr addr \ };}
}加载核心配置文件获取 SqlSessionFactory 对象获取 SqlSession 对象执行 SQL 语句释放资源 public static void main(String[] args) throws Exception {// 1. 加载MyBatis的核心配置文件, 获取SqlSessionFactory对象String resource mybatis-config.xml;InputStream inputStream Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory new SqlSessionFactoryBuilder().build(inputStream);// 2. 获取SqlSession对象, 用来执行sql语句SqlSession sqlSession sqlSessionFactory.openSession();// 3. 执行sql语句ListUser users sqlSession.selectList(test.selectAll);System.out.println(users);// 4. 释放资源sqlSession.close();
}Mapper代理开发
目的: 解决原生方式中的硬编码 简化后期执行SQL 使用Mapper代理分为下面三个步骤: 需要定义一个与SQL映射文件同名的Mapper接口并且将Mapper接口和SQL映射文件放置在同一目录下 注意, 我们不要将配置文件直接放到同名Mapper接口中去, 我们可以在配置文件中创建一个与接口所在文件相同的目录, 在编译过后会自动在同一目录下(声明目录时, 使用/分隔) 设置SQL映射文件的namespace属性为Mapper接口全限定名 !-- UserMapper.xml --?xml version1.0 encodingUTF-8 ?
!DOCTYPE mapperPUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttps://mybatis.org/dtd/mybatis-3-mapper.dtd!-- namespace 设置名称空间为接口全限名称 --
mapper namespacecom.chenyq.mapper.UserMapper!-- id是sql语句的唯一标识, resultType返回值类型 --select idselectAll resultTypecom.chenyq.pojo.UserSELECT * FROM tb_user;/select
/mapper在 Mapper 接口中定义方法方法名就是SQL映射文件中sql语句的id并保持参数类型和返回值类型一致 public interface UserMapper {// 方法名和映射文件中sql语句的id 返回User类型的集合ListUser selectAll();
}细节如果Mapper接口名称和SQL映射文件名称相同并在同一目录下则可以在mybatis-config.xml核心配置文件中使用包扫描的方式简化SQL映射文件的加载 mappers!--加载sql映射文件--!-- mapper resourcecom/chenyq/mapper/UserMapper.xml/--!--Mapper代理的方式--package namecom.chenyq.mapper/
/mappersMyBatis配置文件
MyBatis 核心配置文件的顶层结构如下 配置各个标签时需要遵守前后顺序 类型别名(typeAliases):
typeAliases!-- 相当于给pojo包下的实体类取了一个别名 --package namecom.chenyq.pojo/
/typeAliases配置别名后, pojo文件中的实体类类名就不在区分大小写, 并且不用带包名了; 例如在Mapper映射文件中, 声明返回值类型就可以简化 !-- namespace 设置名称空间为接口全限名称 --
mapper namespacecom.chenyq.mapper.UserMapper!-- 不需要再带包名, 且不区分大小写 --select idselectAll resultTypeUserSELECT * FROM tb_user;/select
/mapperenvironments: 配置数据库连接环境信息。可以配置多个(environment)数据库配置环境信息通过default属性切换不同的environment定义的数据库
!-- default表示当前使用的是id为test的environment配置的数据库 --
environments defaulttestenvironment iddevelopment!-- 事务的管理方式: JDBC事务 --transactionManager typeJDBC/!-- 数据库连接池 --dataSource typePOOLED!--数据库连接信息--property namedriver valuecom.mysql.jdbc.Driver/property nameurl valuejdbc:mysql:///mybatis?useSSLfalse/property nameusername valueroot/property namepassword value123456789//dataSource/environmentenvironment idtesttransactionManager typeJDBC/dataSource typePOOLED!--数据库连接信息--property namedriver valuecom.mysql.jdbc.Driver/property nameurl valuejdbc:mysql:///mybatis?useSSLfalse/property nameusername valueroot/property namepassword value123456789//dataSource/environment
/environments