1. 首先了解ORM 对象-关系映射(Object Relational Mapping )
ORM是通过使用描述对象和数据库之间映射的原数据,将Java程序中的对象自动持久化到关系数据库中。
2.iBatis 是Apache的一个开源项目,是ORM的解决方案
3.iBatis环境搭建:
1)需要导入包:ibatis-2.3.0.677.jar 、mysql-connector-java-5.1.6-bin.jar
2)需要编写的文件:
JDBC需要连接的属性文件,SqlMap.properties
总配置文件,SqlMapConfig.xml
关于每个实体的映射文件(map文件)
4.进行一个Demo,实现将个人信息存入和取出
下面直接进行学习新内容:Mybatis
1.MyBatis的前身就是iBatis,iBatis本是由Clinton Begin开发,后来捐给Apache基金会,成立了iBatis开源项目。2010年5月该项目由Apahce基金会迁移到了Google Code,并且改名为MyBatis。
2.工作流程:
![]()
3.全局基础配置文件:
configuration.xml是系统的核心配置文件,包含数据源和事务管理器等设置和属性信息,XML文档结构如下:
Ø
configuration
配置
Ø
l
properties
可以配置在
Java
属性配置文件中
Ø
l
settings
修改
MyBatis
在运行时的行为方式
Ø
l
typeAliases
为
Java
类型命名一个短的名字
Ø
l
typeHandlers
类型处理器
Ø
l
objectFactory
对象工厂
Ø
l
plugins
插件
Ø
l
environments
环境
Ø
environment
环境变量
Ø
transactionManager
事务管理器
Ø
dataSource
数据源
Ø
mappers
l
映射器
4.每个对象的映射xml
l
SQL
映射文件结构
:
Ø
l
cache -
配置给定命名空间的缓存。
Ø
l
cache-ref –
从其他命名空间引用缓存配置。
Ø
l
resultMap
–
最复杂,也是最有力量的元素,用来描述如何从数据库结果集中来加载对象。
l
Ø
l
sql
–
可以重用的
SQL
块,也可以被其他语句引用。
Ø
l
insert –
映射插入语句
Ø
l
update –
映射更新语句
Ø
l
delete –
映射删除语句
Ø
l
select –
映射查询语句
其中3、4的详细解析见
5.下面介绍个例子:
配置文件
configuration.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>
<settings >
<setting name="defaultExecutorType" value="REUSE" />
</settings>
<typeAliases>
<typeAlias alias="Student" type="com.demo.mybatis.dto.Student" />
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="jdbc" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/mybatis" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/demo/mybatis/mapper/StudentMapper.xml" />
</mappers>
</configuration>
映射文件 mapper.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.demo.mybatis.mapper.StudentMapper">
<resultMap id="studentResultMap" type="Student">
<id property="id" column="id" />
<result property="name" column="name" />
<result property="gender" column="gender" />
<result property="major" column="major" />
<result property="grade" column="grade" />
</resultMap>
<select id="getById" parameterType="int" resultMap="studentResultMap">
SELECT *
FROM
student WHERE id = #{id}
</select>
<insert id="addStudent" parameterType="Student"
useGeneratedKeys="true" keyProperty="id">
insert into student (name,gender,major,grade)
values
(#{name},#{gender},#{major},#{grade})
</insert>
<select id="getList" resultMap="studentResultMap">
SELECT *
FROM
student
</select>
<delete id="delStudent" parameterType="int">
delete
from
student
where id=#{id}
</delete>
</mapper>
java接口类 mapper.java
package com.demo.mybatis.mapper;
import java.util.ArrayList;
import com.demo.mybatis.dto.Student;
public interface StudentMapper {
//根据学生ID查询学生实体
public Student getById(int id);
//添加学生
public void addStudent(Student student);
public ArrayList<Student> getList();
//删除学生
public void delStudent(int id);
}
实体类 Student.java
package com.demo.mybatis.dto;
public class Student {
private int id;
private String name; //姓名
private String gender; //性别
private String major; //专业
private String grade; //年级
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 String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
}
测试调用类:
package com.demo.mybatis.test;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.demo.mybatis.dto.Student;
import com.demo.mybatis.mapper.StudentMapper;
public class TestMyBatis {
private static SqlSessionFactory sqlSessionFactory =null;
public static void main(String[] args) {
// 与configuration.xml中的mapper配置类似,告诉MyBatis
// 应读取的核心配置文件
String resource = "resources/configuration.xml";
Reader reader = null;
try {
reader = Resources.getResourceAsReader(resource);
} catch (IOException e) {
e.printStackTrace();
}
// 创建SqlSessionFactory实例。没有指定要用到的
// environment,则使用默认的environment
sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(reader);
// selectbyID();
// addStudent("Mack1","male","math","2");
// getlist();
delbyID(4);
}
/**
* 查询
*/
private static void getlist(){
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
//select
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
ArrayList<Student> students = mapper.getList();
if (students.size()>0) {
for(int i=0;i<students.size();i++){
System.out.println("姓名: " + students.get(i).getName() + " 专业: "
+ students.get(i).getMajor());
}
} else {
System.out.println("没有找到。");
}
} finally {
sqlSession.close();
}
}
/**
* 查询
*/
private static void selectbyID(){
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
//select
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
Student student = mapper.getById(2);
if (student != null) {
System.out.println("姓名: " + student.getName() + "\n专业: "
+ student.getMajor());
} else {
System.out.println("没有找到。");
}
} finally {
sqlSession.close();
}
}
/**
* 增加
*/
private static void addStudent(String name, String gender,String major,String grade){
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
//select
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
Student student = new Student();
student.setName(name);
student.setGender(gender);
student.setMajor(major);
student.setGrade(grade);
mapper.addStudent(student);
} finally {
sqlSession.close();
}
}
/**
* 删除
*/
private static void delbyID(int id){
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
//select
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
mapper.delStudent(id);
// if (student != null) {
// System.out.println("姓名: " + student.getName() + "\n专业: "
// + student.getMajor());
// } else {
// System.out.println("没有找到。");
// }
} finally {
sqlSession.close();
}
}
}
OK,保存以备用