<a href="http://www.mybatis.org/mybatis-3/zh/index.html">MyBatis SQL Mapper Framework for Java</a>
<a href="http://ibatis.apache.org/">iBatis</a>
MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
MyBatis与Hibernate同属于ORM解决方案之一,都是为了简化持久层的操作,它们都封装了JDBC。在效率上MyBatis高于Hibernate低于JDBC,MyBatis使用还是很简单的。
Demo<a href="http://download.csdn.net/detail/linjiqian/9764321"> http://download.csdn.net/detail/linjiqian/9764321</a>
引入MyBatis库
Paste_Image.pngMyBatis与Hibernate都是要配置实体和表的映射关系的配置文件,MyBatis的sql一般写在配置文件中,并且具有一定的动态性。
一个一对一的例子,建立学生表与班级表。,默认有三个班级。
-- create Database mybatisdb;
DROP TABLE student;
DROP TABLE classes;
-- 班级表
CREATE TABLE classes(
cls_id INT(5) PRIMARY KEY,
cls_name VARCHAR(10)
);
-- 学生表
CREATE TABLE student(
stu_id INT(5) PRIMARY KEY,
stu_name VARCHAR(10),
cls_id INT(5),
CONSTRAINT scid_fk FOREIGN KEY(cls_id) REFERENCES classes(cls_id)
);
-- 插入三个班级
INSERT INTO classes(cls_id,cls_NAME) VALUE(1,'乾坤大挪移');
INSERT INTO classes(cls_id,cls_NAME) VALUE(2,'降龙十八掌');
INSERT INTO classes(cls_id,cls_NAME) VALUE(3,'龟派气功');
Demo项目结构(idea开发):
Paste_Image.png班级实体:Classes.java
package cn.thinglin.demo.entity;
/**
* Created by mac on 2017/2/25.
*/
public class Classes {
private int id;
private String name;
public Classes(){}
public Classes(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public Classes setId(int id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
班级实体配置:ClassesMapper.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="classesNamespace">
<resultMap type="cn.thinglin.demo.entity.Classes" id="classesMap">
<id property="id" column="cls_id"/>
<result property="name" column="cls_name"/>
</resultMap>
</mapper>
学生实体:Student.java
package cn.thinglin.demo.entity;
/**
* Created by mac on 2017/2/25.
*/
public class Student {
private int id;
private String name;
private Classes classesId;
public Student(){}
public Student(int id, String name, Classes classesId) {
this.id = id;
this.name = name;
this.classesId = classesId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Classes getClassesId() {
return classesId;
}
public void setClassesId(Classes classesId) {
this.classesId = classesId;
}
}
学生实体配置: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="studentNamespace">
<!-- 配置实体与表的映射 -->
<resultMap type="cn.thinglin.demo.entity.Student" id="studentMap">
<id property="id" column="stu_id"/>
<result property="name" column="stu_name"/>
<association property="classesId" resultMap="classesNamespace.classesMap"/> <!-- 1对1映射 -->
</resultMap>
<select id="findById" parameterType="string" resultMap="studentMap">
select s.stu_id,s.stu_name,c.cls_name,c.cls_id
from student s inner join classes c
on s.cls_id = c.cls_id
and s.stu_id = #{id}
</select>
<!-- 一般findAll查询所有不需要条件,这里是为说明可以设置这样的条件 -->
<select id="findAll" parameterType="map" resultMap="studentMap">
select * from student
<!-- where开始设置条件 如果传进来的id不为null就设置条件表字段的id=传进来的id,这里可以动态设置条件也就是mybatis强大的动态sql -->
<where>
<if test="id!=null">
and stu_id = #{id}
</if>
<if test="name!=null">
and stu_name = #{name}
</if>
<if test="classesId!=null">
and cls_id = #{classesId}
</if>
</where>
<if test="index!=null">
limit #{index},#{size}
</if>
</select>
<!-- 判断数据实体的值,null?不增加这个字段:增加这个字段,所以if条件中写实体属性key,if结果写字段名 -->
<sql id="key">
<!-- trim suffixOverrides 去掉最后一个,号 -->
<trim suffixOverrides=",">
<if test="id!=null">
stu_id,
</if>
<if test="name!=null">
stu_name,
</if>
<if test="classesId!=null">
cls_id,
</if>
</trim>
</sql>
<!-- 判断数据是否为空,不为空填上实体数据做为value -->
<sql id="value">
<trim suffixOverrides=",">
<if test="id!=null">
#{id},
</if>
<if test="name!=null">
#{name},
</if>
<if test="classesId!=null">
#{classesId.id}, <!-- 取的映射对象的id值 -->
</if>
</trim>
</sql>
<!-- <include refid="key"/>和<include refid="value"/>表示引用上面定义的sql片段 -->
<insert id="add" parameterType="cn.thinglin.demo.entity.Student">
insert into student(<include refid="key"/>) values(<include refid="value"/>)
</insert>
<!-- 更新 -->
<update id="update" parameterType="cn.thinglin.demo.entity.Student">
update student set stu_name = #{name},cls_id = #{classesId.id} where stu_id = #{id}
</update>
<!-- 删除 -->
<delete id="delete" parameterType="cn.thinglin.demo.entity.Student">
delete from student where stu_id = #{id}
</delete>
</mapper>
MyBatis 总配置文件:mybatis.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"/>
<!-- 设置一个默认的连接环境信息 -->
<environments default="mysql_developer">
<!-- 连接环境信息 先后设置了mysql_developer与oracle_developer,在environments的default属性指向要使用的那个 -->
<environment id="mysql_developer">
<!-- mybatis使用jdbc事务管理方式 -->
<transactionManager type="jdbc"/>
<!-- mybatis使用连接池方式来获取连接 -->
<dataSource type="pooled">
<!-- 配置与数据库交互的4个必要属性 -->
<property name="driver" value="${mysql.driver}"/>
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
</dataSource>
</environment>
<environment id="oracle_developer">
<!-- mybatis使用jdbc事务管理方式 -->
<transactionManager type="jdbc"/>
<!-- mybatis使用连接池方式来获取连接 -->
<dataSource type="pooled">
<!-- 配置与数据库交互的4个必要属性 -->
<property name="driver" value="${oracle.driver}"/>
<property name="url" value="${oracle.url}"/>
<property name="username" value="${oracle.username}"/>
<property name="password" value="${oracle.password}"/>
</dataSource>
</environment>
</environments>
<!-- 加载实体映射文件-->
<mappers>
<mapper resource="cn/thinglin/demo/entity/StudentMapper.xml"/>
<mapper resource="cn/thinglin/demo/entity/ClassesMapper.xml"/>
</mappers>
</configuration>
MyBatis工具类:MyBatisUtil.java
package cn.thinglin.demo.util;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/**
* Created by mac on 2017/2/25.
*/
public class MyBatisUtil {
private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
private static SqlSessionFactory sqlSessionFactory;
private MyBatisUtil(){}
/**
* 加载mybatis.xml配置文件
*/
static{
try {
Reader reader = Resources.getResourceAsReader("mybatis.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 获取SqlSession
*/
public static SqlSession getSqlSession(){
//从当前线程中获取SqlSession对象
SqlSession sqlSession = threadLocal.get();
//如果SqlSession对象为空
if(sqlSession == null){
//在SqlSessionFactory非空的情况下,获取SqlSession对象
sqlSession = sqlSessionFactory.openSession();
//将SqlSession对象与当前线程绑定在一起
threadLocal.set(sqlSession);
}
//返回SqlSession对象
return sqlSession;
}
/**
* 关闭SqlSession与当前线程分开
*/
public static void closeSqlSession(){
//从当前线程中获取SqlSession对象
SqlSession sqlSession = threadLocal.get();
//如果SqlSession对象非空
if(sqlSession != null){
//关闭SqlSession对象
sqlSession.close();
//分开当前线程与SqlSession对象的关系,希望尽早回收内存
threadLocal.remove();
}
}
}
持久层:StudentDao.java
package cn.thinglin.demo.dao;
import cn.thinglin.demo.entity.Student;
import cn.thinglin.demo.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.List;
/**
* Created by mac on 2017/2/25.
*/
public class StudentDao {
/**
* 根据id查找
* @param id
* @return
* @throws Exception
*/
public Student findById(int id) throws Exception{
SqlSession sqlSession = null;
try{
sqlSession = MyBatisUtil.getSqlSession();
return sqlSession.selectOne("studentNamespace.findById",id);
}catch(Exception e){
e.printStackTrace();
throw e;
}finally{
MyBatisUtil.closeSqlSession();
}
}
/**
* 添加一个
* @param student
* @throws Exception
*/
public void add(Student student) throws Exception{
SqlSession sqlSession = null;
try{
sqlSession = MyBatisUtil.getSqlSession();
sqlSession.insert("studentNamespace.add",student);
sqlSession.commit();
}catch(Exception e){
e.printStackTrace();
sqlSession.rollback();
throw e;
}finally{
MyBatisUtil.closeSqlSession();
}
}
/**
* 查询所有符合条件的,并分页
*/
public List<Student> findAll(Integer id,String name,Integer classesId,Integer index,Integer size){
try{
SqlSession sqlSession = MyBatisUtil.getSqlSession();
Map<String,Object> map = new LinkedHashMap<String,Object>();
map.put("id",id);
map.put("name",name);
map.put("classesId",classesId);
map.put("index",index);
map.put("size",size);
return sqlSession.selectList("studentNamespace.findAll",map);
}catch(Exception e){
e.printStackTrace();
throw e;
}finally{
MyBatisUtil.closeSqlSession();
}
}
/**
* 更新
* @param stu
*/
public void updateById(Student stu){
SqlSession sqlSession = null;
try{
sqlSession = MyBatisUtil.getSqlSession();
sqlSession.update("studentNamespace.update",stu);
sqlSession.commit();
}catch(Exception e){
e.printStackTrace();
sqlSession.rollback();
throw e;
}finally{
MyBatisUtil.closeSqlSession();
}
}
/**
*删除
* @param stu
*/
public void deleteById(Student stu){
SqlSession sqlSession = null;
try{
sqlSession = MyBatisUtil.getSqlSession();
sqlSession.delete("studentNamespace.delete",stu);
sqlSession.commit();
}catch(Exception e){
e.printStackTrace();
sqlSession.rollback();
throw e;
}finally{
MyBatisUtil.closeSqlSession();
}
}
}
测试:Test.java
package cn.thinglin.demo.test;
import cn.thinglin.demo.dao.StudentDao;
import cn.thinglin.demo.entity.Classes;
import cn.thinglin.demo.entity.Student;
/**
* Created by mac on 2017/2/25.
*/
public class Test {
public static void main(String[] args) {
StudentDao dao = new StudentDao();
try {
//插入数据,三条cls_id =1 的
dao.add(new Student(1, "大侠", new Classes(1, null)));
dao.add(new Student(2, "大光头", new Classes(1, null)));
dao.add(new Student(3, "过大年", new Classes(1, null)));
dao.add(new Student(4, "活着", new Classes(2, null)));
dao.add(new Student(5, "余华", new Classes(2, null)));
System.out.println("分页查询:");
System.out.println(dao.findAll(null,null,null,0,4).size()+"条数据");
System.out.println("根据id查询:");
Student student = dao.findById(2);
System.out.println(student.getId()+" : "+student.getName() +" : " +student.getClassesId().getName() +" :cls_id = "+student.getClassesId().getId());
//更新这条数据的cls_id
student.setClassesId(student.getClassesId().setId(3));
System.out.println(""+student.getId()+" :: "+student.getClassesId().getId() );
dao.updateById(student);
System.out.println("查询所有cls_id=1的:");
System.out.println(dao.findAll(null,null,1,null,null).size()+"条数据");
//删除
dao.deleteById(student);
} catch (Exception e) {
e.printStackTrace();
}
}
}
demo_mybatis.gif
</br>
</br>
</br>
</br>
</br>
网友评论