快速搭建
maven项目中的resources文件夹中存放的文件,默认放在类的根路径下(main文件夹)
引入依赖(Maven):
mybatis
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.13</version> </dependency>
mysql驱动
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.49</version> </dependency>
核心文件
在resources文件夹中新建一个 mybatis-config.xml
的文件用来存放核心配置,内容如下
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
目录结构
- configuration(配置)
- properties(属性)
- settings(设置)
- typeAliases(类型别名)
- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins(插件)
- environments(环境配置)
- environment(环境变量)
- transactionManager(事务管理器)
- dataSource(数据源)
- environment(环境变量)
- databaseIdProvider(数据库厂商标识)
- mappers(映射器)
标签含义:
configuration
:根标签properties
:里面用来配置属性,可以书写properties
配置文件environments
:存放环境;属性:default设置配置文件的默认环境environment
:存放数据库;属性:id是环境的唯一表识transactionManager
:事务管理器,type有两种值- JDBC:mybatis使用原生jdbc默认的事务管理方式;sql会话工厂对象调用openSession方法获取sql会话对象时会Connection类的setAutoCommit(#);方法传入false开启事务
- MANAGED:mybatis不再负责事务管理。交给其他容器负责。如spring,如果没有其他容器负责,则没有事务管理会自动提交
mappers
:存放映射器mapper
:存放的都是SQL执行;属性:resource 值为对应的Mapper.xml文件路径,默认从类路径下开始(main文件夹 url 路径可以是绝对路径也可以是网络资源package
:name属性,根据包设置包下面的所有mapper接口,这种方式适用于接口绑定
编写映射文件(XxxMapper.xml
)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.mybatis.example.BlogMapper">
<!-- SQL语句书写处 -->
</mapper>
所有的SQL的语句都是书写在<mapper>
标签里面的
namespace
属性:写的是接口的全路径
所有对数据进行更改的操作最后都要进行提交:
- 自动提交:使用
opensession
方法传true参数:sqlSessionFactory.openSession(true)
- 手动提交:使用
commit
进行提价:sqlsession.commit()
增
<insert id="insertType" useGeneratedKeys="true" keyProperty="id">
insert into type
values (null, #{name});
</insert>
useGeneratedKeys="true"
:使用自动生成的主键值
keyProperty="属性名”
:指定主键值赋值给对象的哪个属性
resultType="类型"
:返回的类型,文档
删
<delete id="deleteType">
delete
from type
where id = #{id};
</delete>
改
<update id="updateType">
update type
set name = #{name}
where id = #{id};
</update>
查
<select id="xxx" resultType="xxx">
select * from xxx;
</select>
id
:唯一表示IDresultType
:返回的类型(完整性类名)
selectKey
:可以在增删改之前或执行后进行运行<selectKey order="(BEFORM | AFTER)" keyProperty="id" resultType="int"> select count(id) form user; </selectKey>
order
BEFORM:SQL之前运行
AFTER:SQL之后运行
keyProperty:查找到的数据赋值给所指定的字段
resultType:返回的类型
实体映射
MyBatis 3 接口映射
mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mapper.BlogMapper">
<select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
</select>
</mapper>
mybatis-config.xml
在核心文件mappers
里面配置一下
<mapper namespace="org.mybatis.example.BlogMapper">
<mapper resource="mapper.xml"/>
</mapper>
mapper
属性:
resource
:填写resource文件夹下的路径class
:接口的全名称url
:。。。
java
public interface TypeMapper {
List<Blog> selectBlog();
}
注解映射
在接口中的方法中使用注解的方式映射(建议书写简单一点的SQL)
@Insert("SQL语句") // 增
@Delete("SQL语句") // 删
@Update("SQL语句") // 改
@Select("SQL语句") // 查
不常用,推荐使用XML方式编写SQL语句
注意
在添加mapper中对应的操作方法时
- 方法名要和mapper中对应的操作节点id要一致
- 返回类型要和mapper中的
resultType
一致 - mapper中对应的操作节点的参数必须要在参数方法中声明
mapper.xml中的namespace
必须要和接口的完整限定名要一致
注解方式和xml方式两者可以混用但是不可以同时存在
在使用maven项目时,建议接口地址和resource
文件夹下mapper
文件的地址一样
构建SqlSessionFactory
// import org.apache.ibatis.io.Resources;
// import org.apache.ibatis.session.SqlSessionFactory;
// import org.apache.ibatis.session.SqlSessionFactoryBuilder;
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSessionFactoryBuilder
:sql会话工厂构建者对象
- 通过build(构建)(传参核心配置文件的流,环境的id)来构建SqlSessionFactory对象
- 推荐使用 Resources类的getResourceAsStream方法传参(核心配置文件名)因为它默认从根路径查找资源(main文件夹)且可移植性强
SqlSessionFactory
:sql会话工厂对象
获取SqlSession
官方文档:mybatis – MyBatis 3 | 从-sqlsessionfactory-中获取-sqlsession
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
try {
TypeMapper mapper = sqlSession.getMapper(TypeMapper.class);
Type type = new Type();
mapper.insertType(type);
// 提交
sqlSession.commit();
} catch (Exception e) {
// 回滚
sqlSession.rollback();
} finally {
// 关闭连接
sqlSession.close();
}
}
SqlSession
:sql会话对象,执行对应语句使用对应方法
- insert 插入
- delete 删除
- update 更新
- selectOne 查询一条
- selectList 查询一组
openSession()
:为其中设置不同的参数会给SqlSession
后续的数据操作造成不同的影响
SqlSession openSession(boolean autoCommit)
:事务作用域将会开启(也就是不自动提交)SqlSession openSession(Connection connection)
:将由当前环境配置的 DataSource 实例中获取 Connection 对象SqlSession openSession(TransactionIsolationLevel level)
:事务隔离级别将会使用驱动或数据源的默认设置SqlSession openSession(ExecutorType execType)
:预处理语句不会被复用,也不会批量处理更新