定义
MyBatis 是⼀款优秀的持久层框架,它⽀持⾃定义 SQL、存储过程以及⾼级映射。
MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的⼯作。
MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
mybatis使用图示.png
特点
1.轻量级自身不依赖其他任何JAR,但需要提供JDBC实现
2.灵活,更加适⽤于需求变化频繁的互联网应用
3.学习成本低,相⽐ORM框架而言,掌握MyBatis的使用是很轻松的
入门使用
1.在项目中引入依赖
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
</dependencies>
2.在resource下提供配置文件
2.1 resource下创建mybatis-config.xml作为mybatis全局配置
<?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>
<environments default="development">
<!-- 可配置多个环境 并指定默认使用的环境-->
<environment id="development">
<!-- 指定事务管理器-->
<transactionManager type="JDBC"/>
<!-- 指定数据源 就是数据来自哪里 这里默认使用MyBatis⾃自带的连接池-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<!-- //表示本机localhost &==& xml中&需要转译-->
<property name="url" value="jdbc:mysql:///mybatisDB? serverTimezone=Asia/Shanghai&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="admin"/>
</dataSource>
</environment>
</environments>
<!-- 指定要加载的映射文件-->
<mappers>
<mapper resource="mapper/ProductsMapper.xml"/>
</mappers>
</configuration>
2.2 log4j日志配置log4j.properties
# Global logging configuration
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
3.创建测试数据库表
CREATE DATABASE IF NOT EXISTS `mybatisDB` CHARACTER SET utf8;
USE `mybatisDB`;
DROP TABLE IF EXISTS `products`;
CREATE TABLE `products` (
`pid` int(11) NOT NULL AUTO_INCREMENT,
`pname` varchar(20) DEFAULT NULL,
`price` double DEFAULT NULL,
`pdate` date DEFAULT NULL,
`cid` varchar(20) DEFAULT NULL,
PRIMARY KEY (`pid`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
INSERT INTO `products` VALUES (2,'新疆大枣',38,NULL,'s002'),
(3,'新疆切糕',68,NULL,'s001'),
(4,'十三⾹香',10,NULL,'s002'),
(5,'老干妈',20,NULL,'s002'),
(6,'泰国咖喱2',50.5,'2020-01-02','s001'),
(7,'泰国咖喱2',50.5,'2020-01-02','s001');
4.使用(通过session+id)
4.1 在resources/mapper下创建mybatis映射ProductsMapper.xml
*创建完成后必须在mybatis-config.xml中<mappers>标签中进行配置该映射文件
<!-- 名称空间 用来区分多个不同包下的相同语句 通常是对应的包名称 -->
<mapper namespace="">
<!-- parameterType是输入的参数类型 resultType是期望的返回结果类型
#{}用于取出输入的参数如果参数只有一个括号里面任意 -->
<select id="selectByID" parameterType="int" resultType="com.pojo.Product">
select * from products where pid = #{pid}
</select>
<!-- sql中需要多个参数 -->
<select id="selectByNameAndPrice" parameterType="map" resultType="com.pojo.Product">
select * from products where pname = #{pname} and price = #{price}
</select>
<!-- 模糊查询 -->
<select id="selectByNameLike" resultType="com.pojo.Product" parameterType="String">
select *from products where pname like "%${name}%"
</select>
<update id="updateByID" parameterType="com.pojo.Product">
update products set pname = #{pname}, price = #{price}, pdate = #{pdate}, cid = #{cid} where pid = #{pid}
</update>
<delete id="deleteById" parameterType="int">
delete from products where pid = #{pid}
</delete>
<!-- mysql中插入后获取主键的方式 -->
<insert id="insertProduct" parameterType="com.pojo.Product" keyProperty="pid" useGeneratedKeys="true">
insert into products values (null,#{pname},#{price},#{pdate},#{cid})
</insert>
<!-- 如果数据库不支持自增 -->
<insert id="insertProduct2" parameterType="com.pojo.Product">
<selectKey keyProperty="pid" resultType="int" order="AFTER">
select last_insert_id();
</selectKey>
insert into products values (#{pid},#{pname},#{price},#{pdate},#{cid})
</insert>
</mapper>
4.2 调用
*当sql为update、insert、delete时需要commit才会生效,SqlSession默认不自动提交的,可以在获取 SqlSession时指定自动提交,也可以在执行完后手动调用commit;
public class Product {
private int pid;
private String pname;
private double price;
private Date pdate;
private String cid;
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Date getPdate() {
return pdate;
}
public void setPdate(Date pdate) {
this.pdate = pdate;
}
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
@Override
public String toString() {
return "Products{" +
"pid=" + pid +
", pname='" + pname + '\'' +
", price=" + price +
", pdate=" + pdate +
", cid='" + cid + '\'' +
'}';
}
}
public class MyTest {
private SqlSessionFactory factory;
//将SqlSessionFactoryBuilder的创建提取出来,避免每次操作都需要重复创建
@Before
public void before() throws IOException {
//读取配置文件的输入流
InputStream stream = Resources.getResourceAsStream("mybatis-config.xml");
//构建一个会话工厂
factory = new SqlSessionFactoryBuilder().build(stream);
}
@Test
public void selectTest() {
//创建一个会话
SqlSession session = factory.openSession();
//执行sql
Product product = session.selectOne("selectByID", 2);
System.out.println(product);
}
@Test
public void selectTest2() {
try (SqlSession session = factory.openSession()) {
HashMap<String, Object> map = new HashMap<>();
map.put("pname", "十三香");
map.put("price", 10);
Product product = session.selectOne("selectByNameAndPrice", map);
System.out.println(product);
}
}
@Test
public void selectTest3() {
try (SqlSession session = factory.openSession()) {
List<Product> products = session.selectList("selectByNameLike", "新疆");
System.out.println(products);
}
}
@Test
public void updateTest() {
//参数为是否自动提交
try (SqlSession session = factory.openSession(true)) {
//先查出一个对象
Product product = session.selectOne("selectByID", 3);
//修改
product.setPrice(399);
int c = session.update("updateByID", product);
System.out.println(c);
//手动提交
//session.commit();
}
}
@Test
public void deleteTest() {
//参数为是否自动提交
try (SqlSession session = factory.openSession(true)) {
int c = session.delete("deleteById", 5);
System.out.println(c);
}
}
//由于session不是线程安全的对象 所以不建议多个地方使用同一个
@Test
public void insertTest() {
//参数为是否自动提交
try (SqlSession session = factory.openSession(true)) {
Product product = new Product();
product.setPname("棉花糖");
product.setPrice(3.5);
product.setCid("s1");
product.setPdate(new Date());
int c = session.insert("insertProduct2", product);
System.out.println(c);
System.out.println(product.getPid());
}
}
}
5.使用(通过动态代理)
5.1 在resources/mapper下创建mybatis映射ProductsMapper.xml
*创建完成后必须在mybatis-config.xml中<mappers>标签中进行配置该映射文件
<mapper namespace="com.mapper.ProductsMapper">
<select id="selectProductByName" parameterType="string" resultType="com.pojo.Products">
select *from products where pname = #{name}
</select>
</mapper>
5.2 创建调用接口类
package com.mapper;
import com.pojo.Products;
/*
*必须保证mapper.xml中的namespace与接口的全限定名称一致
*方法的名称必须与对应的sql statement的id一致
*方法的参数必须与对应的sql statement的parameterType一致
*方法的返回值必须与对应的sql statement的resultType一致
*
* */
public interface ProductsMapper {
//根据name查询一个Products
public Products selectProductByName(String name);
}
5.3 调用
@Test
public void proxyTest(){
SqlSession session = factory.openSession();
ProductsMapper mapper = session.getMapper(ProductsMapper.class);
Products product = mapper.selectProductByName("泰国咖喱");
System.out.println(product);
session.close();
}
网友评论