1、Mybatis概念
(1)mybatis :是 一个基于Java的持久层框架
(2)持久层框架 : jdbc , springjdbc,jpa,springdatajpa , mybatis
(3)mybatis 它是一个持久层框架,同时又是ORM的框架
2、Mybatis特点
(1)MyBatis 是一个支持普通 SQL查询,存储过程(数据库mysql/oracle)和高级映射的优秀持久层框架。
(2)MyBatis 消除了几乎所有的JDBC代码和手工设置参数以及结果集的检索。
(3)MyBatis 使用简单的 ****XML*或 注解 用于配置和原始映射,将接口和 Java 的*POJOs****(Plain Old Java Objects,普通的 Java对象 Employee/User/Entity/Domain)映射成数据库中的记录。 SQL映射方式
xxxMapper.xml 文件(crud sql语句)
3、使用Mybatis
(1) 创建项目 导入jar包
a)创建一个普通项目 , 创建一个文件夹lib (jar包)
b)数据库创建一个表 Product
c)创建结构
cn.itsource.mybatis.domain
cn.itsource.mybatis.dao
cn.itsource.mybatis.service
(2) 写配置文件
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">
<!--这是配置的其中一个环境 id是这个环境的唯一id-->
<environment id="development">
<!--事务管理 type:JDBC(支持事务)/MANAGED(没有事务)-->
<transactionManager type="JDBC" />
<!--数据源(数据库连接池)-->
<dataSource type="POOLED">
<!--链接数据库的四个参数-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///mybatis"/>
<property name="username" value="test"/>
<property name="password" value="123"/>
</dataSource>
</environment>
</environments>
<!--product对应的映射文件-->
<mappers>
<mapper resource="ProductMapper.xml"/>
</mappers>
</configuration>
ProductMapper.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:命名空间
通过namespace+id 调用对应的语句
-->
<mapper namespace="cn.itsource.domain.ProductMapper">
<!--
select:表示查询标签
id: 方法名称 必须唯一
resultType:返回值类型
-->
<select id="findAll" resultType="cn.itsource.domain.Product">
select * from product
</select>
</mapper>
(3)写测试方法查询数据
public List<Product> findAll() throws IOException {
//读取配置
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
//SqlSessionFactory类似于JPA的EntityManagerFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
//SqlSession类似于JPA的EntityManager
SqlSession sqlSession = sqlSessionFactory.openSession();
//调用findAll +namespace+id
List<Product> products = sqlSession.
selectList("cn.itsource.mybatis.domain.ProductMapper.findAll");
return products;
}
4、完成CRUD
ProductMapper.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:命名空间
通过namespace+id 调用对应的语句
-->
<mapper namespace="cn.itsource.domain.ProductMapper">
<!--
select:表示查询标签
id: 方法名称 必须唯一
resultType:返回值类型
-->
<select id="findAll" resultType="cn.itsource.domain.Product">
select * from product
</select>
<!--新增
parameterType新增数据类型(传入参数)
-->
<insert id="save" parameterType="cn.itsource.domain.Product">
insert into product(productName,salePrice,costPrice,cutoff)
values (#{productName},#{salePrice},#{costPrice},#{cutoff})
</insert>
<!--修改
parameterType新增数据类型(传入参数)
-->
<insert id="update" parameterType="cn.itsource.domain.Product">
update product set productName=#{productName},salePrice=#{salePrice},
costPrice=#{costPrice},cutoff=#{cutoff} where id=#{id}
</insert>
<!--删除
这里的long等价于java.util.Long
-->
<delete id="delete" parameterType="long">
delete from product where id=#{id}
</delete>
<!--查询一条数据-->
<select id="findOne" parameterType="long" resultType="cn.itsource.domain.Product">
select * from product where id=#{id}
</select>
</mapper>
5、抽取工具类
MybatisUtil.java
public enum MybatisUtil {
INSTANCE;
private static SqlSessionFactory sqlSessionFactory;
static {
Reader reader=null;
try {
reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
}catch (IOException e){
e.printStackTrace();
}
}
public SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
6、Mybatis使用细节
1、细节一:主键id
保存数据到数据库之后,可以立即拿到主键id
具体ProductMapper.xml配置
<insert id="save" parameterType="cn.itsource.domain.Product"
useGeneratedKeys="true" keyColumn="id" keyProperty="id">
insert into product(productName,salePrice,costPrice,cutoff)
values(#{productName},#{salePrice},#{costPrice},#{cutoff})
</insert>
2、细节二:日志
(1)使用日志原因
使用日志框架可以帮助我们进行分析与排错
(2)日志框架
a)自己写
b)log4j框架
c)日志框架标准——slf4j(抽象标准) -->诸多实现 logging,logback,log4j
(3)使用日志框架
a)导入jar包
b)写配置文件
log4j.properties
#log4j.rootLogger=ERROR, stdout
#日志等级: OFF level > FATAL(致命) > ERROR(错误) > WARN (警告)>
# INFO (提示)> DEBUG (调试)> trace > ALL level(所有)
#输出效果 如果你设置日志级别是trace,则大于等于这个级别的日志都会输出
log4j.rootLogger=ERROR, stdout
log4j.logger.cn.itsource=trace
#log4j.rootLogger=NONE 这个是关闭日志输出
# ERROR为严重错误 主要是程序的错误、
# WARN为一般警告,比如session丢失、
# INFO为一般要显示的信息,比如登录登出、
# DEBUG为程序的调试信息
# TRACE 堆栈信息
# cn.itsource扫描这个包下面的日志
#ConsoleAppender:输出控制台
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#layout:输出的日志格式
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#采用如下的格式输出
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
7、动态sql
高级查询
ProductMapper.xml
<!--高级查询-->
<sql id="whereSql">
<where>
<if test="productName!=null">
and productName=#{productName}
</if>
<if test="id!=null">
and id=#{id}
</if>
</where>
</sql>
<!--根据条件查询-->
<select id="queryByCondition" parameterType="cn.itsource.query.ProductQuery"
resultType="cn.itsource.domain.Product" >
select * from product
<include refid="whereSql"/>
</select>
8、批量删除
ProductMapper.xml
<!--批量删除-->
<delete id="deleteBatch" parameterType="java.util.List">
delete from product where id in
<foreach collection="list" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</delete>