- 程序中框架【代码半成品】
- 生活中“框架”
- 手抓饼
- 买毛坯房
- SSM【Spring+SpringMVC+Mybatis】
- Mybatis:JDBC【dao层】半成品
- SpringMVC:Servlet【表示层、表述层、控制层、表现层】半成品
- Spring:大管家
-
Mybatis前身Ibatis
-
Mybatis是一个半自动化的持久化层ORM框架
- ORM:Object Relational Mapping【对象关系映射】
- 理解:将对象中属性与表中字段进行关联映射
- 优势: *** 作对象中属性,就可以影响表中字段数据
- ORM:Object Relational Mapping【对象关系映射】
-
Mybatis与Hibernate对比
- Hibernate全自动化持久层ORM框架
- 不需要手写sql【不方便优化SQL】
- Mybatis半自动化持久层ORM框架
- 需要手写sql【方便优化SQL】
- Hibernate全自动化持久层ORM框架
-
POJO(Plain Ordinary Java Object,普通的Java对象)
- POJO作用等同于JavaBean
- 下载网址:https://github.com/mybatis/mybatis-3
- 文档网址:https://mybatis.org/mybatis-3/
- 导入框架所需jar包【坐标】
- 编写配置文件【不同框架配置文件不同】
- 使用框架核心类库【不同框架核心类库不同】
-
准备
- 建库建表建约束
- 准备maven工程
-
导入mybatis所需jar包
<dependency> <groupId>mysqlgroupId> <artifactId>mysql-connector-javaartifactId> <version>8.0.26version> dependency> <dependency> <groupId>org.mybatisgroupId> <artifactId>mybatisartifactId> <version>3.5.6version> dependency> <dependency> <groupId>junitgroupId> <artifactId>junitartifactId> <version>4.12version> <scope>testscope> dependency>
-
编写mybatis-config.xml核心配置文件
-
名称:没有具体要求,建议使用mybatis-config.xml
-
位置:src/main/resources
-
作用:设置mybatis基本行为
-
示例代码
DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/db220227"/> <property name="username" value="root"/> <property name="password" value="root"/> dataSource> environment> environments> <mappers> <mapper resource="mapper/EmployeeMapper.xml"/> mappers> configuration>
-
-
编写POJO及对应接口【CRUD】
package com.atguigu.mapper; import com.atguigu.pojo.Employee; public interface EmployeeMapper { /** * 通过员工id获取员工信息 */ public Employee selectEmpById(int empId); }
-
编写映射文件【xxxMapper.xml】
-
名称:要求与接口名称一致
-
位置:src/main/resouces/mapper/
-
主要作用:为接口中的方法定义SQL语句【三点一致】
- 映射文件名称与接口名称一致
- 映射文件中mapper标签的namespace属性,与接口的全类名一致
- 映射文件中sql语句的id属性值,与接口中方法名一致
-
示例代码
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.dudu.mapper.EmployeeMapper"> <select id="selectEmpById" resultType="com.atguigu.pojo.Employee"> SELECT id, last_name lastName, email, salary FROM tbl_employee WHERE id = #{empId} select> mapper>
-
-
使用核心类库进行测试
-
核心类库:SqlSession
-
先获取SqlSessionFactory,再获取SqlSession,最后通过SqlSession获取接口的代理对象,进行测试
-
示例代码
@Test public void testHw() throws Exception{ //定义mybatis核心配置文件路径 String resource = "mybatis-config.xml"; //使用IO流,读取配置文件 InputStream inputStream = Resources.getResourceAsStream(resource); //通过SqlSessionFactoryBuilder构建SqlSessionFactory对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //通过sqlSessionFactory获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //最后通过SqlSession获取接口的代理对象,进行测试 //旧版本玩法:sqlSession.select(); EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class); //测试 Employee employee = employeeMapper.selectEmpById(1); System.out.println("employee = " + employee); }
-
- 为相应框架添加日志功能【可以看到框架内部执行细节】
-
导入log4j的jar包
<dependency> <groupId>log4jgroupId> <artifactId>log4jartifactId> <version>1.2.17version> dependency>
-
编写配置文件
-
名称:log4j.xml
-
位置:src/main/resources
-
示例代码
DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender"> <param name="Encoding" value="UTF-8" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" /> layout> appender> <logger name="java.sql"> <level value="debug" /> logger> <logger name="org.apache.ibatis"> <level value="info" /> logger> <root> <level value="debug" /> <appender-ref ref="STDOUT" /> root> log4j:configuration>
-
- MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。
- 配置文件中包含一个根标签【configuration】,九个子标签【需要掌握其中6个子标签】
-
根标签:configuration,主要作用就是包含子标签
-
子标签
-
properties子标签
-
语法:
-
作用:定义property属性,也可以引入外部属性文件
-
示例代码
<properties resource="db.properties">properties>
-
-
db.driverClassName=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/db220227?serverTimeZone=UTC
db.username=root
db.password=123456
-
settings子标签
-
语法:
-
作用:这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。
-
常用属性
- mapUnderscoreToCamelCase:是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。【注意字母必须全部相同才可以自动映射】
- false:默认值
- true:开启驼峰式命名自动映射
- cacheEnabled
- lazyLoadingEnabled
- useGeneratedKeys
- mapUnderscoreToCamelCase:是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。【注意字母必须全部相同才可以自动映射】
-
示例代码
<settings> <setting name="mapUnderscoreToCamelCase" value="true"/> settings>
-
-
typeAliases子标签
-
语法:
-
作用:定义类型别名【类型别名可为 Java 类型(POJO)设置一个缩写名字。】
-
示例代码
<typeAliases> <typeAlias type="com.dudu.pojo.Employee" alias="employee">typeAlias> typeAliases> <typeAliases> <package name="com.dudu.pojo"/> typeAliases>
-
-
environments子标签
-
作用:设置数据库环境【多个】,最终会使用Spring管理数据源&事务管理器
-
示例代码
<environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${db.driverClassName}"/> <property name="url" value="${db.url}"/> <property name="username" value="${db.username}"/> <property name="password" value="${db.password}"/> dataSource> environment> environments>
-
-
mappers子标签
-
作用:设置映射文件路径【加载映射文件】
-
示例代码
<mappers> <mapper resource="mapper/EmployeeMapper.xml"/> mappers>
-
-
总结Mybatis核心配置文件【mybatis-config.xml】
- 子标签有顺序要求的,参考顺序详情见官网
DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties resource="db.properties">properties> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> settings> <typeAliases> <package name="com.dudu.pojo"/> typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${db.driverClassName}"/> <property name="url" value="${db.url}"/> <property name="username" value="${db.username}"/> <property name="password" value="${db.password}"/> dataSource> environment> environments> <mappers> <mapper resource="mapper/EmployeeMapper.xml"/> mappers> configuration>
- MyBatis 的真正强大在于它的语句映射,这是它的魔力所在。由于它的异常强大,映射器的 XML 文件就显得相对简单。
- 如果拿它跟具有相同功能的 JDBC 代码进行对比,你会立即发现省掉了将近 95% 的代码。
- MyBatis 致力于减少使用成本,让程序员能更专注于 SQL 代码。
-
根标签【一个】
-
语法:
<mapper namespace="com.dudu.mapper.EmployeeMapper">mapper>
-
作用:定义当前映射文件的namespace【设置目标接口】
-
-
子标签【共有9个,需要掌握8个】
-
insert:定义添加SQL语句
id 的内容要和EmployeeMapper中的方法名一致
<insert id="addEmp">
INSERT INTO
tbl_employee (last_name,email,salary)
VALUES
(#{lastName},#{email},#{salary})
insert>
- delete:定义删除SQL语句
<delete id="deleteEmp">
delete from
tbl_employee
where
id=#{id}
delete>
- update:定义修改SQL语句
<update id="updateEmp">
update tbl_employee
set
last_name=#{lastName},
email=#{email},
salary=#{salary}
where
id=#{id}
update>
- select:定义查询SQL语句
根据 id
<select id="selectEmployeeById" resultType="employee">
SELECT
id,
last_name,
email,
salary
FROM
tbl_employee
WHERE
id = #{empId}
select>
查询所有
<select id="selectAllEmp" resultType="employee">
select
id,
last_name,
email,
salary
FROM
tbl_employee
select>
-
注意:查询语句必须定义resultType或resultMap,否则报如下错
Caused by: org.apache.ibatis.executor.ExecutorException: A query was run and no Result Maps were found for the Mapped Statement ‘com.atguigu.mapper.EmployeeMapper.selectAllEmp’. It’s likely that neither a Result Type nor a Result Map was specified.
-
sql:定义SQL片段
-
resultMap标签:自定义映射,resultType解决不了的问题,交个resultMap
-
cache:定义当前名称空间的缓存配置
-
cache-ref:定义当前名称空间的缓存引用
- resultType:定义结果集预期返回的类型【全类名(类的全限定名)或别名】
- 注意
- 如果返回的是集合,那应该设置为集合包含的类型,而不是集合本身的类型。
- resultType 和 resultMap 之间只能同时使用一个。
- 注意
CREATE TABLE tbl_employee(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
last_name VARCHAR(50),
email VARCHAR(50),
salary DOUBLE(10,2)
);
Employee
package com.dudu.pojo;
/**
* @author:嘟嘟
* @date:2022/5/7
*/
public class Employee {
private Integer id;
private String lastName;
private String email;
private Double salary;
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", salary=" + salary +
'}';
}
public Employee() {
}
public Employee(Integer id, String lastName, String email, Double salary) {
this.id = id;
this.lastName = lastName;
this.email = email;
this.salary = salary;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
}
EmployeeMapper
public interface EmployeeMapper {
public Employee selectEmployeeById(int empId);
public List<Employee> selectAllEmp();
public void addEmp(Employee employee);
public void updateEmp(Employee employee);
public void deleteEmp(int id);
}
EmployeeMapper.xml
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dudu.mapper.EmployeeMapper">
<select id="selectEmployeeById" resultType="employee">
SELECT
id,
last_name,
email,
salary
FROM
tbl_employee
WHERE
id = #{empId}
select>
<select id="selectAllEmp" resultType="employee">
select
id,
last_name,
email,
salary
FROM
tbl_employee
select>
<insert id="addEmp">
INSERT INTO
tbl_employee (last_name,email,salary)
VALUES
(#{lastName},#{email},#{salary})
insert>
<update id="updateEmp">
update tbl_employee
set
last_name=#{lastName},
email=#{email},
salary=#{salary}
where
id=#{id}
update>
<delete id="deleteEmp">
delete from
tbl_employee
where
id=#{id}
delete>
mapper>
db.properties
db.driverClassName=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/db220227?serverTimeZone=UTC
db.username=root
db.password=123456
log4j.xml
DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
layout>
appender>
<logger name="java.sql">
<level value="debug" />
logger>
<logger name="org.apache.ibatis">
<level value="info" />
logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
root>
log4j:configuration>
mybatis_config.xml
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="db.properties">properties>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true" />
settings>
<typeAliases>
<package name="com.dudu.pojo"/>
typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${db.driverClassName}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="mapper/EmployeeMapper.xml"/>
mappers>
configuration>
TestMapper
import com.dudu.mapper.EmployeeMapper;
import com.dudu.pojo.Employee;
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.InputStream;
import java.time.LocalDate;
import java.util.List;
/**
* @author:嘟嘟
* @date:2022/5/7
*/
public class TesyMapper {
@Test
public void test() throws Exception {
//定义mybatis核心配置文件路径
String resource = "mybatis_config.xml";
//使用IO流,读取配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
//通过SqlSessionFactoryBuilder构建SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//通过sqlSessionFactory获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//最后通过SqlSession获取接口的代理对象,进行测试
//旧版本玩法:sqlSession.select();
EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
//测试
Employee employee = employeeMapper.selectEmployeeById(1);
System.out.println("employee = " + employee);
}
@Test
public void testCRUD() throws Exception {
//定义mybatis核心配置文件路径
String resource = "mybatis_config.xml";
//使用IO流,读取配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
//通过SqlSessionFactoryBuilder构建SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//通过SqlSessionFactory获取SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
List<Employee> employees = mapper.selectAllEmp();
//添加员工
//mapper.addEmp(new Employee(null,"王二","944@qq.com",5000.50));
//更新员工
//mapper.updateEmp(new Employee(1,"大傻子","124@qq.com",500.5));
//删除员工
mapper.deleteEmp(1);
System.out.println(employees);
sqlSession.commit();
LocalDate date=LocalDate.of(2022,10,1);
System.out.println(date);//2022-10-01
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)