最近在重新看mybatis文档时,又将mybatis的基本操作又练了练手。mybatis的操作,是通过SqlSessionFactory对象来操作数据sql,官网也写了两种SqlSessionFactory对象的创建方式,下面说一下两种方式不同的区别,一种是基于XML配置文件的创建方式,一种是JAVA代码的方式。今天想记录这篇博客也是因为中间通过Java代码创建方式的时候,中间遇到些问题。
XML配置文件方式
主要归结于一下几个步骤:
1、根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象;
2、书写sql映射文件;配置了每一个sql,以及sql的封装规则等。
3、将sql映射文件注册在全局配置文件中
4、写代码:
1)、根据全局配置文件得到SqlSessionFactory(通过SqlSessionFactoryBuilder工厂方法创建);
2)、使用sqlSession工厂,获取到sqlSession对象使用他来执行增删改查; 一个sqlSession就是代表和数据库的一次会话,用完关闭
3)、使用sql的唯一标志来告诉MyBatis执行哪个sql。sql都是保存在sql映射文件中的。
实现细节
数据源
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3308/SPRINGBOOT
jdbc.username=root
jdbc.password=123456
首先全局配置文件(mybatis-config.xml)
<?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>
<properties resource="db.properties"></properties>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="logImpl" value="LOG4J"/>
<!--<setting name="logPrefix" value="mapper." />-->
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<!--mapper sql映射文件-->
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
UserMapper(interface)
public interface UserMapper {
//根据ID查询
User findById(Integer id);
}
UserMapper(xml映射文件)
<?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="mapper.UserMapper">
<select id="findById" resultType="domain.User">
select * from USER where id = #{id}
</select>
</mapper>
通过配置文件实现
@Test
public void test() throws Exception {
String resource = "mybatis-config.xml";
//获取配置文件流
InputStream resourceAsStream = Resources.getResourceAsStream(resource);
//创建SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession session = sqlSessionFactory.openSession();
User u = session.selectOne("mapper.UserMapper.findById", 1);
System.out.println("user:" + u);
session.close();
}
通过JAVA代码的方式创建
上面就是通过全局配置文件的实现方式,官网文档介绍:
注意该例中,configuration 添加了一个映射器类(mapper class)。映射器类是 Java 类,它们包含 SQL 映射语句的注解从而避免了 XML 文件的依赖。不过,由于 Java 注解的一些限制加之某些 MyBatis 映射的复杂性,XML 映射对于大多数高级映射(比如:嵌套 Join 映射)来说仍然是必须的。有鉴于此,如果存在一个对等的 XML 配置文件的话,MyBatis 会自动查找并加载它(这种情况下, BlogMapper.xml 将会基于类路径和 BlogMapper.class 的类名被加载进来)
@Test
public void test5() throws Exception {
//创建连接池
DataSource dataSource = new PooledDataSource("com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3308/SPRINGBOOT", "root", "123456");
//事务
TransactionFactory transactionFactory = new JdbcTransactionFactory();
//创建环境
Environment environment = new Environment("development", transactionFactory, dataSource);
//创建配置
Configuration configuration = new Configuration(environment);
//开启驼峰规则
configuration.setMapUnderscoreToCamelCase(true);
//加入资源(Mapper接口)
configuration.addMapper(UserMapper.class);
//
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
SqlSession session = sqlSessionFactory.openSession();
try {
//statement:sql唯一标识(mapper.xml映射文件中的id标识)
//parament:参数
User user = session.selectOne("mapper.UserMapper.findById", 1);
System.out.println(user);
//操作数据时,需要有提交操作
session.commit();
} finally {
session.close();
}
}
这里使用IDEA实现的话,可能会报下面的错误
org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for mapper.UserMapper.findById
### Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for mapper.UserMapper.findById
这里是idea编译的问题,他默认不是编译java文件夹下的.xml文件,这里我们可以在配置文件中添加这块的编译;我这里使用的Maven方式,我们只需要在pom文件中,添加build标签中,添加需要编译的xml文件位置;也可以直接放到resource资源文件中,也就是类路径;这里可以添加多个。
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>classpath</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
通过以上方式实现SqlSessionFactory的对象创建。
代码的仓库地址: github地址