mybatis是一个优秀的基于java的持久层框架,它内部封装了jdbc,使开发者只需要关注sql语句本身,而不需要花费精力去处理加载驱动、创建连接、创建statement等繁杂的过程。
mybatis通过xml或注解的方式将要执行的各种statement配置起来,并通过java对象和statement中sql的动态参数进行映射生成最终执行的sql语句。
最后mybatis框架执行sql并将结果映射为java对象并返回。采用ORM思想解决了实体和数据库映射的问题,对jdbc进行了封装,屏蔽了jdbc api底层访问细节,使我们不用与jdbc api打交道,就可以完成对数据库的持久化操作。
1、创建数据库表格
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `phone`
-- ----------------------------
CREATE TABLE `phone` (
`phone_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '手机编号',
`brand_id` int(11) NOT NULL DEFAULT '0' COMMENT '品牌编号',
`model_number` varchar(50) NOT NULL COMMENT '型号',
`capacity` int(11) NOT NULL COMMENT '存储容量',
PRIMARY KEY (`phone_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of phone
-- ----------------------------
INSERT INTO `phone` VALUES ('1', '1', 'mate60', '256');
INSERT INTO `phone` VALUES ('2', '1', 'p60', '128');
INSERT INTO `phone` VALUES ('3', '2', 'x50', '128');
2、添加相关依赖
mysql
mysql-connector-java
8.0.33
org.mybatis
mybatis
3.4.6
junit
junit
4.12
test
org.projectlombok
lombok
1.18.20
3、创建对应实体类Phone
package com.cqgcxy.entity;
import lombok.Data;
@Data
public class Phone {
// 手机编号
private Integer phoneId;
// 品牌编号
private Integer brandId;
// 手机型号
private String modelNumber;
// 手机容量
private Integer capacity;
}
4、在resources文件夹下创建并编写映射文件mapper/PhoneMapper.xml
INSERT phone VALUES (NULL,#{brandId},#{modelNumber},#{capacity});
DELETE FROM phone
WHERE phone_id = #{phoneId}
UPDATE phone SET brand_id = #{brandId},model_number = #{modelNumber},capacity = #{capacity}
WHERE phone_id = #{phoneId}
5、在resources文件夹下创建并编写核心配置文件SqlMapConfig.xml
properties标签:该标签可以加载外部的properties文件
typeAliases标签:设置类型别名
settings:功能设置,如:开启驼峰命名转换
mappers标签:加载映射配置
environments标签:环境配置
其中,事务管理器(transactionManager)类型有两种:
JDBC:这个配置就是直接使用了JDBC的提交和回滚设置,它依赖于从数据源得到的连接来管理事务作用域。
MANAGED:这个配置几乎没做什么。它从来不提交或回滚一个连接,而是让容器来管理事务的整个生命周期(比如JEE应用服务器的上下文)。默认情况下它会关闭连接,然而一些容器并不希望这样,因此需要将closeConnection属性设置为false来阻止它默认的关闭行为。
其中,数据源(dataSource)类型有三种:
UNPOOLED:这个数据源的实现只是每次被请求时打开和关闭连接。
POOLED:这种数据源的实现利用“池”的概念将JDBC连接对象组织起来。
JNDI:这个数据源的实现是为了能在如EJB或应用服务器这类容器中使用,容器可以集中或在外部配置数据源,然后放置一个JNDI上下文的引用。
6、测试
package com.cqgcxy.mapper;
import com.cqgcxy.entity.Phone;
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.IOException;
import java.io.InputStream;
import java.util.List;
public class MybatisTest {
@Test
public void insertPhoneTest() throws IOException {
InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqLSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlsession = sqLSessionFactory.openSession();
Phone phone = new Phone();
phone.setBrandId(1);
phone.setModelNumber("mate60plus");
phone.setCapacity(512);
int insert = sqlsession.insert("insertPhone", phone);
sqlsession.commit();
if(insert>0){
System.out.println("新增成功!");
}
sqlsession.close();
}
@Test
public void deleteByIdTest() throws IOException {
InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqLSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlsession = sqLSessionFactory.openSession();
int delete = sqlsession.delete("deleteById",4);
sqlsession.commit();
if(delete>0){
System.out.println("删除成功!");
}
sqlsession.close();
}
@Test
public void updateByIdTest() throws IOException {
InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqLSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlsession = sqLSessionFactory.openSession();
Phone phone = new Phone();
phone.setPhoneId(4);
phone.setBrandId(1);
phone.setModelNumber("mate60plus");
phone.setCapacity(1024);
int update = sqlsession.update("updateById",phone);
sqlsession.commit();
if(update>0){
System.out.println("更新成功!");
}
sqlsession.close();
}
@Test
public void selectByIdTest() throws IOException {
InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqLSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlsession = sqLSessionFactory.openSession();
Phone phone = sqlsession.selectOne("selectById",4);
System.out.println(phone);
sqlsession.close();
}
@Test
public void selectAllTest() throws IOException {
InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqLSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlsession = sqLSessionFactory.openSession();
List phoneList = sqlsession.selectList("selectAll");
phoneList.forEach(s->{
System.out.println(s);
});
sqlsession.close();
}
}
响应API
(1)Resources 工具类,这个类在org.apache.ibatis.io包中。Resources从类路径下、文件系统或一个web URL中加载资源文件。
(2)SqlSessionFactory build(InputStream inputStream)加载mybatis的核心文件输入流构建一个SqlSessionFactory对象。
(3)SqlSessionFactory有多个个方法创建sqlSession实例。常用的有如下两个:
openSession()默认开启一个事务,不会自动提交,如更新数据需要手动提交事务。
openSession(boolean autoCommit)参数如果设置为true则自动提交事务。
(4)SqlSession会话对象
SqlSession实例在MyBatis 中是非常强大的一个类。在这里你会看到所有执行语句、提交或回滚事务和获取映射器实例 的方法。
7、测试代理方式
1)创建PhoneMapper接口
package com.cqgcxy.mapper;
import com.cqgcxy.entity.Phone;
import java.util.List;
public interface PhoneMapper {
int insertPhone(Phone phone);
int deleteById(Integer id);
int updateById(Phone phone);
Phone selectById(Integer id);
List selectAll();
}
2)修改PhoneMapper.xml中namespace为PhoneMapper的完全限定名
3)修改测试类
package com.text;
import com.dao.PhoneMapper;
import com.entity.Phone;
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.IOException;
import java.io.InputStream;
import java.util.List;
public class MybatisTest {
@Test
public void insertPhoneTest() throws IOException {
InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqLSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlsession = sqLSessionFactory.openSession();
Phone phone = new Phone();
phone.setBrandId(1);
phone.setModelNumber("mate60plus");
phone.setCapacity(512);
// int insert = sqlsession.insert("insertPhone", phone);
sqlsession.commit();
PhoneMapper phoneMapper = sqlsession.getMapper(PhoneMapper.class);
int insert = phoneMapper.insertPhone(phone);
if(insert>0){
System.out.println("新增成功!");
}
sqlsession.close();
}
@Test
public void deleteByIdTest() throws IOException {
InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqLSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlsession = sqLSessionFactory.openSession();
// int delete = sqlsession.delete("deleteById",4);
PhoneMapper phoneMapper = sqlsession.getMapper(PhoneMapper.class);
int delete = phoneMapper.deleteById(4);
sqlsession.commit();
if(delete>0){
System.out.println("删除成功!");
}
sqlsession.close();
}
@Test
public void updateByIdTest() throws IOException {
InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqLSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlsession = sqLSessionFactory.openSession();
Phone phone = new Phone();
phone.setPhoneId(4);
phone.setBrandId(1);
phone.setModelNumber("mate60plus");
phone.setCapacity(1024);
// int update = sqlsession.update("updateById",phone);
PhoneMapper phoneMapper = sqlsession.getMapper(PhoneMapper.class);
int update = phoneMapper.updateById(phone);
sqlsession.commit();
if(update>0){
System.out.println("更新成功!");
}
sqlsession.close();
}
@Test
public void selectByIdTest() throws IOException {
InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqLSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlsession = sqLSessionFactory.openSession();
//Phone phone = sqlsession.selectOne("selectById",4);
PhoneMapper phoneMapper = sqlsession.getMapper(PhoneMapper.class);
Phone phone = phoneMapper.selectById(4);
System.out.println(phone);
sqlsession.close();
}
@Test
public void selectAllTest() throws IOException {
InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqLSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlsession = sqLSessionFactory.openSession();
//List phoneList = sqlsession.selectList("selectAll");
PhoneMapper phoneMapper = sqlsession.getMapper(PhoneMapper.class);
List phoneList = phoneMapper.selectAll();
phoneList.forEach(s->{
System.out.println(s);
});
sqlsession.close();
}
}
增删改查语句使用对应标签
有参数的指定参数类型、有返回值的指定返回值类型
Sql语句中使用#{实体属性名}方式引用实体中的属性值
操作使用的API是sqlSession.对应方法(“命名空间.id”[,实体对象]);
涉及数据库数据变化的要使用sqlSession对象显示的提交事务,即sqISession.commit()