1 MyBatis是一种支持sql语句和存储过程的实现ORM的框架,是对JDBC的封装,是一种优秀的持久层框架。
2 搭建MyBatis环境:
导入依赖的包;
在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>
<typeAliases>
<typeAlias type="com.web.entity.Student" alias="Student" />
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:XE" />
<property name="username" value="orcl" />
<property name="password" value="newsnews" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/web/entity/StudentMapper.xml" />
<!-- <mapper class="com.web.dao.StudenMapper"/> -->
</mappers>
</configuration>
创建持久化类及映射文件;
Student
package com.web.entity;
public class Student {
private Integer studentId;
private String studentName;
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
}
StudentMapper.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="com.pb.dao.StudentDao">
<resultMap type="Student" id="studentResultMap">
<id column="studentId" property="studentId" />
<result column="studentName" property="studentName" />
</resultMap>
<insert id="saveStudent" parameterType="Student">
insert into student(studentId,studentName) values(#{studentId},#{studentName})
</insert>
<update id="updateStudent" parameterType="Student">
update student set studentName=#{studentName} where studentId=#{studentId}
</update>
<delete id="deleteStudent" parameterType="Student">
delete from student where studentId=#{studentId}
</delete>
<select id="selectStudent" parameterType="Integer" resultType="Student">
select * from student where studentId=#{id}
</select>
<select id="selectAll" resultType="Student">
select * from student
</select>
<!-- <insert id="insertStudent" parameterType="Student"
useGeneratedKeys="true" keyProperty="id">
insert into t_student
(stu_name,stu_email,stu_birthday) values
(#{name},#{email},#{birthday})
</insert>
<select id="selectStudentById1" parameterType="int"
resultType="com.pb.domain.Student">
select stu_id id,stu_name name,stu_email email,stu_birthday
birthday
from
t_student where stu_id =#{id}
</select>
<select id="selectStudentById" parameterType="int" resultMap="studentResultMap">
select *
from
t_student where stu_id =#{id}
</select>
<select id="selectStudentByPage1" parameterType="Student"
resultMap="studentResultMap">
select *
from
t_student where 1=1
<if test="name!=null and name!=''">
and stu_name like concat('%',#{name},'%')
</if>
<if test="email!=null and email!=''">
and stu_email like concat('%',#{email},'%')
</if>
</select>
<select id="selectStudentByPage2" parameterType="Student"
resultMap="studentResultMap">
select *
from
t_student
<where>
<if test="name!=null and name!=''">
stu_name like concat('%',#{name},'%')
</if>
<if test="email!=null and email!=''">
and stu_email like concat('%',#{email},'%')
</if>
</where>
</select>
<select id="selectStudentByPage3" parameterType="Student"
resultMap="studentResultMap">
select *
from
t_student
<trim prefix="WHERE" prefixOverrides="AND |OR ">
<if test="name!=null and name!=''">
stu_name like concat('%',#{name},'%')
</if>
<if test="email!=null and email!=''">
and stu_email like concat('%',#{email},'%')
</if>
</trim>
</select>
<select id="selectStudentByIdList" parameterType="list"
resultMap="studentResultMap">
select *
from
t_student
WHERE stu_id in
<foreach item="item" index="index" collection="list" open="("
separator="," close=")">
#{item}
</foreach>
</select>
<select id="selectStudentByPage" parameterType="map"
resultMap="studentResultMap">
select *
from
t_student
<where>
<if test="student.name!=null and student.name!=''">
stu_name like concat('%',#{student.name},'%')
</if>
<if test="student.email!=null and student.email!=''">
and stu_email like concat('%',#{student.email},'%')
</if>
</where>
limit #{from},10
</select>
<delete id="deleteStudent" parameterType="int">
delete from t_student where stu_id = #{id}
</delete>
<update id="updateStudent" parameterType="Student">
update t_student set stu_name = #{name}, stu_email = #{email},stu_birthday=#{birthday} where stu_id = #{id}
</update>
<select id="selectStudentByProperty" parameterType="Student"
resultMap="studentResultMap">
select *
from
t_student
</select> -->
</mapper>
获取SqlSessionFactory及SqlSession进行操作:
package com.web.dao;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.web.entity.Student;
public class StudentDao {
private int res=-1;
private SqlSession sqlSession=null;
public SqlSession getSqlSession(){
try{
String resource="mybatis-config.xml";
InputStream is=Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(is);
sqlSession=sqlSessionFactory.openSession(true);
}catch(Exception e){
System.out.println("出错");
e.printStackTrace();
}
return sqlSession;
}
public int saveStudent(Student s){
sqlSession=getSqlSession();
res=sqlSession.insert("saveStudent",s);
// StudenMapper studentMapper=sqlSession.getMapper(StudenMapper.class);
// studentMapper.save(s);
return res;
}
public int updateStudent(Student s){
sqlSession=getSqlSession();
res=sqlSession.update("updateStudent", s);
return res;
}
public int deleteStudent(Student s){
sqlSession=getSqlSession();
res=sqlSession.delete("deleteStudent", s);
return res;
}
public Student findStudentById(Integer id){
sqlSession=getSqlSession();
Student s=sqlSession.selectOne("selectStudent", id);
return s;
}
public List<Student> findAll(){
sqlSession=getSqlSession();
List<Student> ls= sqlSession.selectList("selectAll");
return ls;
}
}
3 通过注解的形式进行操作:
保留之前的配置文件,去掉映射文件,用注解代替映射文件。在MyBatis可以创建一个接口来代替映射文件;
接口StudentMapper:
package com.web.dao;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.web.entity.Student;
public interface StudenMapper {
@Insert("insert into student(studentId,studentName) values(#{studentId},#{studentName})")
public void save(Student student);
@Update("update student set studentName=#{studentName} where studentId=#{studentId}")
public void update(Student student);
@Delete("delete from student where studentId=#{studentId}")
public void delete(Integer studentId);
@Select("select * from student where studentId=#{studentId}")
public Student findById(Integer studentId);
@Select("select * from student")
public List<Student> findAll();
}
在配置文件里:
<mappers>
<!-- <mapper resource="com/web/entity/StudentMapper.xml" /> -->
<mapper class="com.web.dao.StudenMapper"/>
</mappers>
用这个接口换掉之前的映射文件;
通过SqlSession获取接口的引用,调用接口中对应方法
StudenMapper studentMapper=sqlSession.getMapper(StudenMapper.class);
studentMapper.save(s);
4 Mybatis一级缓存:
MyBatis的一级缓存类似hibernate的一级缓存,是SqlSession级别的,当SqlSession关闭或清空就不存在类,多个SqlSession不能共享一级缓存;
public void findStudent(){
sqlSession=getSqlSession();
Student s=sqlSession.selectOne("findone", 1);
System.out.println(s.getStudentName());
// sqlSession.clearCache();
Student s1=sqlSession.selectOne("findone",1);
System.out.println(s1.getStudentName());
}
两次查询发出一条sqL说明第二次查询是在缓存中查询的;
调用sqlSession.clearCache();后,发出两条sql,一级缓存被清空。
5 MyBatis 二级缓存:
二级缓存是同一个映射文件的namespace级别,同时持久化类需要实现Serializable接口,在映射文件加入<cache></cache>就可以使用二级缓存。‘
方法的第一个sqlsession缓存的时候一定要commit(),否则不会被缓存。
映射文件
<?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.pb.dao.StudentDao">
<cache></cache>
<select id="findone" parameterType="Integer" resultType="Student">
select * from student s where s.studentid=#{studentId}
</select>
</mapper>
持久化类:
package com.web.entity;
import java.io.Serializable;
public class Student implements Serializable{
private Integer studentId;
private String studentName;
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
}
方法:
public void findStudent() throws IOException{
String resource="mybatis-config.xml";
InputStream is=Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession=sqlSessionFactory.openSession();
Student s=sqlSession.selectOne("findone", 1);
System.out.println(s.getStudentName());
sqlSession.commit();
SqlSession sqlSession1=sqlSessionFactory.openSession();
Student s1=sqlSession.selectOne("findone",1);
System.out.println(s1.getStudentName());
sqlSession1.commit();
}
可以看出来结果只发送一条sql
sqlSession需要commit否则不会使用二级缓存;