定义
MyBatis 是⼀款优秀的持久层框架,它⽀持⾃定义 SQL、存储过程以及⾼级映射。
MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的⼯作。
MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
特点
1.轻量级自身不依赖其他任何JAR,但需要提供JDBC实现
2.灵活,更加适⽤于需求变化频繁的互联网应用
3.学习成本低,相⽐ORM框架而言,掌握MyBatis的使用是很轻松的
入门使用
1.在项目中引入依赖
org.mybatis
mybatis
3.5.3
mysql
mysql-connector-java
8.0.17
log4j
log4j
1.2.17
junit
junit
4.13
2.在resource下提供配置文件
2.1 resource下创建mybatis-config.xml作为mybatis全局配置
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中
update products set pname = #{pname}, price = #{price}, pdate = #{pdate}, cid = #{cid} where pid = #{pid}
delete from products where pid = #{pid}
insert into products values (null,#{pname},#{price},#{pdate},#{cid})
select last_insert_id();
insert into products values (#{pid},#{pname},#{price},#{pdate},#{cid})
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 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 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中
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();
}