mybatis 作为目前十分流行的持久层框架,比起hibernate有很大优势
hibernate特点:hql,虽然说屏蔽了数据库差异,但是过于笨重,不方便进行sql优化,,特点比较”鸡肋“
mybatis特点:轻便,对持久层进行轻量的封装,可直接使用sql语句进行查询,提供动态sql,强大的 resultMap。
一。一个简单的案例
mybatis-cfg.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="jdbc.properties"></properties>
<environments default="mybatis-demo">
<environment id="mybatis-demo">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="TeacherMapper.xml"></mapper>
<mapper class="xatu.zsl.dao.student.TestMapper"></mapper>
</mappers>
</configuration>
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="xatu.zsl.dao.student.StudentMapper">
<resultMap id="studentMapper" type="xatu.zsl.entity.Student">
<id column="id" property="id"></id>
<result property="name" column="name"></result>
</resultMap>
<select id="selectAllStudent" resultMap="studentMapper">
SELECT id,name FROM student
</select>
</mapper>
MainTest.java
package xatu.zsl.main;
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 xatu.zsl.entity.Student;
import java.io.*;
import java.util.List;
/**
* Created by zsl on 2017/8/2.
*/
public class MainTest {
public static void main(String[] args) throws Exception {
InputStream is = Resources.getResourceAsStream("mybatis-cfg.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession session = sessionFactory.openSession();
List<Student> students = session.selectList("xatu.zsl.dao.student.StudentMapper.selectAllStudent");
for (Student student : students
) {
System.out.println(student.getName() + " " + student.getId());
}
session.close();
}
}
(1).读取配置文件(一个就好适合单例)
Resources.getResourceAsStream("mybatis-cfg.xml");
当然也可以读取成其他格式,getResourceAsStream,,这个方法提供多种读取方式
(2)构建SqlSessionFactory(一个就好,适合单例)
通过建造者模式,构建出SqlSessionFactory,,,建造者模式解释
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
当然 build提供多种构建方式。。。。
(3)获取SqlSession(线程私有,需要关闭)
SqlSession,是与数据库的一次回话,需要关闭,session.close();,,
所以是以打开形式创建的。
SqlSession session = sessionFactory.openSession();
(4)使用SqlSession,操作数据库
SqlSession提供众多方法供使用。
session.selectList("xatu.zsl.dao.student.StudentMapper.selectAllStudent");
二。使用注解方式更方便
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import xatu.zsl.entity.Student;
/**
* Created by zsl on 2017/8/4.
*/
public interface TestMapper {
@Insert("INSERT INTO student(id,name) VALUES (#{id},#{name})")
public int insertStudent(Student student);
}
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-cfg.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession session = sessionFactory.openSession(true);
// 创建学生
Student xiaoming = new Student();
xiaoming.setId(22);
xiaoming.setName("小明");
//获取mapper
TestMapper mapper = session.getMapper(TestMapper.class);
mapper.insertStudent(xiaoming);
session.close();
}
注意:此处木有session.commit()居然提交成功了,,,,
原因是:sessionFactory.openSession(true);
不加true,需要commit()
三。注意事项
所有的 mapper,,不管是xml,还是java的,,都需要在mybatis-cfg.xml中进行配置
下面分别是配置,文件和class
<mappers>
<mapper resource="TeacherMapper.xml"></mapper>
<mapper class="xatu.zsl.dao.student.TestMapper"></mapper>
</mappers>
否则会出现错误:
Exception in thread "main" org.apache.ibatis.binding.BindingException: Type interface xatu.zsl.dao.student.TestMapper is not known to the MapperRegistry.
at org.apache.ibatis.binding.MapperRegistry.getMapper(MapperRegistry.java:47)
at org.apache.ibatis.session.Configuration.getMapper(Configuration.java:675)
at org.apache.ibatis.session.defaults.DefaultSqlSession.getMapper(DefaultSqlSession.java:250)
at xatu.zsl.main.MainTest.main(MainTest.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)