目录
一、创建MyBatis项目
1.在maven中导入依赖
注:老师创建的不是maven项目,直接调用libraries中的jar包,所以不需要配置pom.xml
如果你创建的是Maven项目,则需要在pom.xml中添加这两条依赖
<!--mybatis依赖-->
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<dependencies>
其中,mybatis是mybatis的依赖,mysql-connector-java是JDBC依赖,让我们能执行sql
2.核心配置文件--mybatis-config
(1)位置:在主包下,mybatis-config.xml
(2)代码:
<configuration>
<typeAliases><!-- 别名 -->
<typeAlias alias="role" type="com.learn.ssm.chapter3.pojo.Role"/>
</typeAliases>
<!-- 数据库环境 -->
<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/chapter3"/>
<property name="username" value="root"/>
<property name="password" value="12345"/>
</dataSource>
</environment>
</environments>
<!-- 映射文件 -->
<mappers>
<mapper resource="com/learn/ssm/chapter3/mapper/RoleMapper.xml"/>
<mapper class="com.learn.ssm.chapter3.mapper.RoleMapper2"/>
</mappers>
</configuration>
(3)解析:
其中,四个<property>根据本地环境自行修改,该文档可在官网下载。
映射文件:url是你的mapper的配置文件(.xml)
你的映射文件应该对应于mapper包中实现接口的配置文件,见7.在核心配置中对mapper进行注册
3.创建实体类--接收表单信息
在项目中,在pojo文件夹下创建了一个实体类Role
这个类中的成员变量为表的列名
并且要创建get和set方法以及toString方法(可以用Generate快速构建)
public class Role {
private Long id;
private String roleName;
private String note;
/** setter and getter **/
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
总而言之,这个类用其对象来储存数据库表单数据
4.创建工厂类--返回Session对象
public class SqlSessionFactoryUtils {
private final static Class<SqlSessionFactoryUtils> LOCK = SqlSessionFactoryUtils.class;
private static SqlSessionFactory sqlSessionFactory = null;
private SqlSessionFactoryUtils() {
}
//单例设计模式
public static SqlSessionFactory getSqlSessionFactory() {
synchronized (LOCK) {
if (sqlSessionFactory != null) {
return sqlSessionFactory;
}
String resource = "mybatis-config.xml";
InputStream inputStream;
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return sqlSessionFactory;
}
}
//代码生成SqlSessionFactory
public static SqlSessionFactory getSqlSessionFactory2() {
synchronized (LOCK) {
//数据库连接池信息
PooledDataSource dataSource = new PooledDataSource();
dataSource.setDriver("com.mysql.jdbc.Driver");
dataSource.setUsername("root");
dataSource.setPassword("123456");
dataSource.setUrl("jdbc:mysql://localhost:3306/chapter3");
dataSource.setDefaultAutoCommit(false);
//采用MyBatis的JDBC事务方式
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
//创建Configuration对象
Configuration configuration = new Configuration(environment);
//注册一个MyBatis上下文别名
configuration.getTypeAliasRegistry().registerAlias("role", Role.class);
//加入一个映射器
configuration.addMapper(RoleMapper.class);
configuration.addMapper(RoleMapper2.class);
//使用SqlSessionFactoryBuilder构建SqlSessionFactory
sqlSessionFactory =
new SqlSessionFactoryBuilder().build(configuration);
return sqlSessionFactory;
}
}
public static SqlSession openSqlSession() {
if (sqlSessionFactory == null) {
getSqlSessionFactory();
}
return sqlSessionFactory.openSession();
}
}
(1) 创建线程锁LOCK: 保证SqlSessionFactory对象只存在一个(见详情)
(2) 生成SqlSessionFactory工厂的方法getSqlSessionFactory():
关于SqlSessionFactory工厂的详情: 见(1)SqlSessionFactory
这个类中有两个方法, 可以用 getSqlSesssionFactory() 方法或 getSqlSessionFactory2() 方法来获取工厂,我们重点关注第一种方法。
首先,看这行代码:(简化版)
InputStream inputStrem = Resources.getResourceAsStream("mybatis-config.xml");
Resources.getResourceAsStream(url)将配置文件(mybatis-config.xml) 按照Stream类型参数进行读取。
当前传入方法的url是相对路径,直接使用文件名,路径指明该文件在主包下。
接下来我们看第二行代码:
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
在这行代码中,通过向工厂类对象的build()方法中传入InputStream类型的xml配置文件,获取工厂类的对象。(接下来我们将通过这个工厂来获取SqlSession对象)
方法一和方法二的区别在于,一个用配置文件来生成sqlSessionFactory,另一个使用代码生成。
(3)获得SqlSession对象的方法openSqlSession():
看这一行代码:return sqlSessionFactory.openSession();
通过使用工厂对象的openSqlSession()方法来获取SqlSession类的对象,接下来,我们可以将通过SqlSession对象所提供的方法来操作数据库
现在,你可以随时在主类中通过这个工厂类(SqlSessionFactoryUtil)的openSqlSession()方法来创建SqlSession对象,在通过调用这个对象来执行sql语句。
5.创建接口--指定sql操作
(1) 在mapper文件夹中创建接口:
(2) 在接口中指定要实现的sql功能:
public interface RoleMapper {
public int insertRole(Role role); //插入行
public int deleteRole(Long id); //删除行
public int updateRole(Role role); //更新表数据
public Role getRole(Long id); //获取行信息(根据id)
public List<Role> findRoles(String roleName); //打印表单信息
}
6.配置映射文件--接口功能的实现
(1)在mapper包中添加xml文件:
(2)编写sql语句
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.learn.ssm.chapter3.mapper.RoleMapper">
<insert id="insertRole" parameterType="role">
insert into t_role(role_name, note) values(#{roleName}, #{note})
</insert>
<delete id="deleteRole" parameterType="long">
delete from t_role where id= #{id}
</delete>
<update id="updateRole" parameterType="role">
update t_role set role_name = #{roleName}, note = #{note} where id= #{id}
</update>
<select id="getRole" parameterType="long" resultType="role">
select id,
role_name as roleName, note from t_role where id = #{id}
</select>
<select id="findRoles" parameterType="string" resultType="role">
select id, role_name as roleName, note from t_role
where role_name like concat('%', #{roleName}, '%')
</select>
</mapper>
在<mapper>的namespace属性后添加配置文件绑定的接口,以指明这个文件是对接口的实现。
<select>标签下的属性:
id属性:对应于接口的成员方法,相当于实现了同名方法。
parameterType属性:对应传递给方法的参数。
resultType属性:对应于方法返回的参数类型。
#{roleName}: 解析role对象中的成员变量roleName值,#{note}同理。
7.在核心配置中对mapper进行注册
回到这个mybatis-config.xml配置文件,我们对它的映射注册进行讲解:
<mappers>
<mapper resource="com/learn/ssm/chapter3/mapper/RoleMapper.xml"/>
<mapper class="com.learn.ssm.chapter3.mapper.RoleMapper2"/>
</mappers>
(1)resource:注册一个接口的映射文件,这个映射文件会与一个接口进行绑定,RoleMapper.xml中的绑定方式如下:(与RoleMapper接口进行绑定)
<!--这是RoleMapper.xml文件,namespace属性进行绑定-->
<mapper namespace="com.learn.ssm.chapter3.mapper.RoleMapper">
...
</mapper>
(2)class:注册一个接口,如果这个接口有映射文件(与其绑定的.xml文件),则这两个文件应该在一个文件夹下。RoleMapper2的配置如下,使用注解完成sql语句的实现,故不用绑定.xml文件。
public interface RoleMapper2 {
//注解中的值就是sql语句的实现
@Select("select id, role_name as roleName, note from t_role where id=#{id}")
public Role getRole(Long id);
}
//这是主类中sqlSession对接口进行代理的方法
RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
(1) sqlSession通过getMapper方法读取接口(RoleMapper和RoleMapper2)中的方法。
(2) 接口(RoleMapper和RoleMapper2)通过配置文件来实现功能。
8.创建主类--对MyBatis进行测试
在main包下创建一个主类,对sql对象实现执行操作
代码:
public class Chapter3Main {
public static void main(String[] args) {
testRoleMapper();
testRoleMapper2();
}
private static void testRoleMapper() {
Logger log = Logger.getLogger(Chapter3Main.class);
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionFactoryUtils.openSqlSession();
//获取代理类对象
RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
//打印执行sql语句获得的信息
Role role = roleMapper.getRole(1L);
log.info(role.getRoleName());
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
}
}
解析:
(1) 通过工厂类的静态方法来获取Session对象:
sqlSession = sqlSessionFactoryUtils.openSqlSession();
(2) 通过SqlSession的getMapper()方法传入你的接口的class,创建接口(Dao接口)RoleMapper的代理对象:
RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
(3) 使用代理对象执行接口提供的方法(getRole()方法):
Role role = roleMapper.getRole(1L); //获取编号为1L的行信息,信息储存在这个role对象中
二、MyBatis中的常用对象
1.SqlSessionFactory对象:
(1)SqlSessionFactory是MyBatis的对象,它是单个数据库映射关系经过编译后的内存镜像。
(2)SqlSessionFactory对象的实例可以通过SqlSessionFactoryBuilder类获得。
(3)SqlSessionFactory一旦被创建,应该在执行期间都存在,在应用运行期间不需要重复多次,故建议使用单例设计模式。
public static SqlSessionFactory getSqlSessionFactory() {
synchronized (LOCK) {
if (sqlSessionFactory != null) {
return sqlSessionFactory;
}
String resource = "mybatis-config.xml";
InputStream inputStream;
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return sqlSessionFactory;
}
}
这是类中获取SqlSessionFactory对象的方法,在类中SqlSessionFactory对象是一个私有的成员变量,通过这种单例设计模式来保证它的对象只存在一个。
(4)SqlSessionFactory是创建SqlSession的工厂,通过调用自己的openSession()方法来生成SqlSession对象。
2.SqlSession对象
sqlSession是MyBatis的关键对象,是执行持久化操作的对象,类似于JDBC中的Connection。它是应用程序与持久层之间执行交互操作的一个单线程对象。SqlSession对象完全包含以数据库为背景的所有执行SQL操作的方法,它的底层封装了JDBC连接,可以使用SqlSession实例来直接执行被映射的SQL语句。
三、参考博客
Mybatis基本使用教程(小白向)_mybatis使用教程-CSDN博客