MyBatis简单使用教程
一、MyBatis简介
Mybatis是当前主流的Java持久层框架之一,是一种ORM(Object/Relational Mapping,即对象关系映射)框架,支持普通SQL查询、储存过程以及高级映射。它使用简单的XML或者注解进行配置和原始映射,用以将接口和Java的POJO(Plain Old Java Object,普通Java对象)映射成数据库中的记录,使得Java开发人员可以使用面向对象的编程思想来操作数据库。
二、与Hibernate比较
Hibernate是一个全表映射的框架。不需要熟练的掌握SQL语句的编写,Hibernate会根据指定的储存逻辑,自动生成对应的SQL,并调用JDBC接口来执行,所以开发效率要高于Mybatis。但它存在一些缺点:在多表查询时,对SQL查询的支持较差;更新数据时,需要发送所有字段;不支持储存过程;不能通过优化SQL来优化性能。所以Hibernate只适合场景不太复杂且对性能要求不高的项目。
三、MyBatis简单使用
1.导包
将MyBatis的核心Jar包导入项目。
2.配置日志文件
在src目录创建log4j.properties文件,写入配置信息
模板如下(可在mybatis文档的logging章节中找到):
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# 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.核心配置文件
在src目录创建核心配置文件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>
<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>
4.映射文件
在业务相关的包中创建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="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
</select>
</mapper>
5.Java类调用
Java类中使用MyBatis分为如下步骤:
(1)使用Java标准I/O流读入核心配置文件
(2)使用SqlSessionFactoryBuilder的build方法(传入核心配置文件的I/O流)构建SqlSessionFactory对象。
(3)使用SqlSessionFactory的openSession方法构建SqlSession对象。
(4)使用SqlSession对象的相关方法进行CRUD。
(5)使用完毕,调用SqlSessio的close方法,关闭Session。
例如:
public class MybatisTest {
@Test
public void findCustomerByIdTest() throws Exception{
String resource = "mybatis_config.xml";
InputStream inputStream =
Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
//构建映射文件中映射的位置(ID)
Customer customer = sqlSession.selectOne("com.itheima.mapper" +
".CustomerMapper.findCustomerById",1);
System.out.println(customer.toString());
sqlSession.close();
}
}
四、IDEA创建自定义文件模板
依次点击File->Other Settings->Default Settings。搜索“Template”,找到“File and Code Templates”。
点击加号新建文件格式,输入名字和后缀,点击“Enable Live Templates”,Apply。