Mybatis框架原理
1、Mybatis 是什么:
MyBatis 是一个可以自定义SQL、存储过程和高级映射的持久层框架。MyBatis 摒除了大部分的JDBC代码、手工设置参数和结果集重获。MyBatis 使用简单的 XML 或注解来配置和映射基本体,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
1、Mybatis-Config.xml (Mybatis的全局配置文件,名称不定)配置了数据源、事务等 Mybatis 运行环境
2、Student.xml 映射文件(配置 sql 语句)
3、SqlSessionFactory (会话工厂)根据配置文件配置工厂、创建 SqlSession
4、SqlSession (会话)面向用户的接口、操作数据库(发出 sql 增删改查)
5、Executor (执行器)是一个接口(基本执行器、缓存执行器)、SqlSession 内部通过执行器操作数据库
6、Mapped Statement (底层封装对象)对操作数据库存储封装,包括 sql 语句、输入参数、输出结果类型
配置
在pom.xml中加入所需要的jar包(mybatis、odjbc、junit等);
先添加要依赖的包,对应的dependency,可以下面在这个网站找,然后将那段代码复制到pom.xml中。
http://mvnrepository.com/
Mybatis-Config.xml
配置 Mybatis 的运行环境、数据源、事务等
<?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">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"/>
<property name="username" value="fafa"/>
<property name="password" value="oracle"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/StudentMapper.xml"/>
</mappers>
</configuration>
Mybatis自带Generator工具类
package com.fafa.test;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
public class GenerateMbgConfig {
/*
* Mybatis自带Generator工具生成相应东西
*/
public static void generate(File file){
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = null;
try {
config = cp.parseConfiguration(file);
} catch (Exception e) {
e.printStackTrace();
return;
}
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
try {
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
callback, warnings);
myBatisGenerator.generate(null);
} catch (Exception e) {
e.printStackTrace();
return;
}
System.out.println("生成Mybatis配置成功!");
}
public static void main(String[] args) {
GenerateMbgConfig.generate(new File("./src/main/java/com/fafa/test/mybatis-generator-config.xml"));
}
}
Mybatis生成文件配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<classPathEntry
location="C:/Users/fafa/.m2/repository/com/oracle/ojdbc6/11.2.0.3/ojdbc6-11.2.0.3.jar" />
<context id="mybatisDemoForMysql" targetRuntime="MyBatis3">
<!-- 控制注释 -->
<commentGenerator>
<!-- 是否去除所有自动生成的注释文件 -->
<property name="suppressAllComments" value="true" />
<!-- 是否去除所有自动生成的文件的时间戳,默认为false -->
<property name="suppressDate" value="false" />
</commentGenerator>
<!-- 控制数据库 -->
<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver"
connectionURL="jdbc:oracle:thin:@127.0.0.1:1521/ORCL"
userId="fafa" password="oracle" />
<javaTypeResolver>
<!-- 把jdbc中的decimal与numberic类型转化为integer类型 -->
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 数据库表对应的model -->
<javaModelGenerator targetPackage="com.fafa.test.model"
targetProject="src/main/java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 控制Model的xmlMapper文件 -->
<sqlMapGenerator targetPackage="mapper"
targetProject="src/main/resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 控制mapper接口 -->
<javaClientGenerator targetPackage="com.fafa.test.dao"
type="XMLMAPPER" targetProject="src/main/java">
<property name="enableSubPackages" value="true" />
<property name="methodNameCalculator" value="extended" />
</javaClientGenerator>
<table tableName="STUDENT" domainObjectName="Student"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
</context>
</generatorConfiguration>
测试
package com.fafa.test;
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.fafa.test.dao.StudentMapper;
import com.fafa.test.model.Student;
/**
* MyBaties测试
* @author fafa
* @data Jan 22, 2017
* @time 11:23:30 AM
*
*/
public class MyBatisTest
{
private StudentMapper studentMapper;
List<Student> info=studentMapper.selectAllInfo();
public static void main(String[] args)
{
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
try {
StudentMapper mapper = session.getMapper(StudentMapper.class);
List<Student> studentInfos = mapper.selectAllInfo();
if (studentInfos == null) {
System.out.println("The result is null.");
} else {
System.out.println("编号\t姓名\t性别\t出生日期\t\t班级");
for (Student student : studentInfos) {
System.out.println(student.getStudentId()+"\t"+student.getStudentName()+"\t" +student.getStudentSex()+"\t"+student.getStudentBirthday()+"\t"+student.getClassId());
}
}
} finally {
session.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
查询结果
编号 | 姓名 | 性别 | 出生日期 | 班级 |
---|---|---|---|---|
1 | 小红 | 女 | 1980-2-8 | 1 |
2 | 小明 | 男 | 1980-1-8 | 1 |
3 | 小白 | 未知 | 1980-3-8 | 1 |