这个实现过程全部是跟着B站黑马学习 学习地址
具体操作的流程图
这里叙述一下执行的大概的过程:
- 首先加载主配置文件配置数据源、根据主配置文件中的mapper标签加载配置文件
- 创建一个SQLSessionFactoryBuilder对象
- 根据传入的流创建一个SQLSessionFactory工厂对象这里使用到了构建者模式
- 通过工厂openSession方法创建一个session使用了工厂模式
- 通过session调用getMapper方法通过代理获得接口对象然后在对其接口方法增强调用Executor执行查询的操作
- 遍历查询的结果集
根据以上的图去创建对应的类及其接口
Tip:一下的代码只能进行查询数据库、并不能对其增删改
这些代码是全部代码标题的主题等级就是包路径及其java文件
在运行一下的代码过程中需要修改主配置文件的自己数据库的信息
1.main方法
public class mybatisDemo {
public static void main( String[] args ) throws DocumentException {
//加载主配置文件
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
//创建构建者
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//创建工厂
SqlSessionFactory factory = sqlSessionFactoryBuilder.build(in);
//创建会话
SqlSession sqlSession = factory.openSession();
//获取接口对象
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<user> list = userDao.findAll();
for (user users : list){
System.out.println(users);
}
}
}
以上其中用到的设置模式:
构建者模式: 把对象的创建细节隐藏,是使用者直接调用方法即可拿到对象
SqlSessionFactory factory = sqlSessionFactoryBuilder.build(in);
工厂模式: 降低代码重复、降低类之间依赖性
SqlSession sqlSession = factory.openSession();
代理模式: 不修改源代码就可以对其方法进行增强
UserDao userDao = sqlSession.getMapper(UserDao.class);
bean包
user.java
映射数据库对应的字段
public class user {
private int id;
private String username;
private String sex;
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "user{" +
"id=" + id +
", username='" + username + '\'' +
", sex=" + sex +
", address='" + address + '\'' +
'}';
}
}
dao包
UserDao.java
dao层数据与数据库做交互
public interface UserDao {
List<user> findAll();
}
mybatis
annoation
Select.java配置注解
配置Select注解在运行时机以及和在哪块配置
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Select {
String value();
}
config
Configuration.java
主要的目的:存储mybatis-config.xml下property标签下的四个属性值
/**
* 自定义mybatis的配置类
*/
public class Configuration {
private String driver;
private String url;
private String username;
private String password;
private Map<String,Mapper> mappers = new HashMap<>();
public Map<String, Mapper> getMappers() {
return mappers;
}
public void setMappers(Map<String, Mapper> mappers) {
this.mappers.putAll(mappers);//此处需要使用追加的方式
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Mapper.java
用来封装映射文件(mapper)之中的SQL语句以及结果集的全限定类名
/**
* 用于封装执行的SQL语句和返回结果集的全限定类名
*/
public class Mapper {
//存储SQL语句
private String queryString;
//存储结果集的全限定类名
private String resultType;
public String getQueryString() {
return queryString;
}
public void setQueryString(String queryString) {
this.queryString = queryString;
}
public String getResultType() {
return resultType;
}
public void setResultType(String resultType) {
this.resultType = resultType;
}
}
IO
Resources.java
获取主配置文件的IO流信息返回流
public class Resources {
/**
* 根据参数获取一个字节输入流
*/
public static InputStream getResourceAsStream(String filePath) {
return Resources.class.getClassLoader().getResourceAsStream(filePath);
}
}
sqlSession
defaults
DefaultSqlSession.java
SQLSession的实现类 主要的用处是通过代理(getMapper)拿到接口的对象
public class DefaultSqlSession implements SqlSession {
private Configuration configuration;
private Connection connection;
public DefaultSqlSession(Configuration configuration) {
this.configuration = configuration;
connection = DataSourceUtil.getConnection(configuration);
}
/**
* 用于创建代理对象
* @param doInterfaceClass
* @param <T>
* @return
*/
@Override
public <T> T getMapper(Class<T> doInterfaceClass) {
return (T) Proxy.newProxyInstance(doInterfaceClass.getClassLoader(),
new Class[]{doInterfaceClass},new MapperProxy(configuration.getMappers(),connection));
}
/**
* 用于释放对象
*/
@Override
public void close() throws SQLException {
connection.close();
}
}
DefaultSqlSessionFactory.java
SQLSessionFactory的实现类主要目的是通过openSession方法创建一个session对象
/**
* SQLSessionFactory接口的实现类
*/
public class DefaultSqlSessionFactory implements SqlSessionFactory {
private Configuration configuration;
public DefaultSqlSessionFactory(Configuration cfg) {
this.configuration = cfg;
}
/**
* 用于创建一个新的操作数据库对象
* @return
*/
@Override
public SqlSession openSession() {
return new DefaultSqlSession(configuration);
}
}
proxy
MapperProxy.java
代理类对其findAll方法增强
增强的实质是调用selectList方法
public class MapperProxy implements InvocationHandler {
//map的key是全限定类名+方法名
private Map<String,Mapper> mappers;
private Connection connection;
public MapperProxy(Map<String, Mapper> mappers,Connection connection) {
this.mappers = mappers;
this.connection = connection;
}
/**
* 用于对方法的增强,增强其实就是调用selectList方法
* @param proxy 代理生成的代理对象
* @param method 调用的的方法这里指的是findAll
* @param args 表示该方法的参数
* @return
* @throws Throwable
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//获取方法名
String methodName = method.getName();
//获取方法所在类的全限定类名
String className = method.getDeclaringClass().getName();
//3.组合key
String key = className + "." + methodName;
//4.获取mappers中的Mapper对象
Mapper mapper = mappers.get(key);
//判断是否有mapper
if (mapper == null){
throw new IllegalArgumentException("传入参数有误");
}
return new Executor().selectList(mapper,connection);
}
}
SqlSession.java
SQLSession接口主要目的:创建dao接口的的代理对象
/**
* 自定义mybatis和数据库交互的核心类
* 里面可以创建dao接口的代理对象
*/
public interface SqlSession {
/**
* 根据参数创建一个代理对象
* @param doInterfaceClass
* @param <T>
* @return
*/
<T> T getMapper(Class<T> doInterfaceClass);
/**
* 关闭资源
*/
void close() throws SQLException;
}
SqlSessionFactory.java
创建一个session对象
Tip:这块用到了工厂模式
public interface SqlSessionFactory {
/**
* 用于打开一个session
* @return
*/
SqlSession openSession();
}
SqlSessionFactoryBuilder.java
创建一个sqlsessionFactory对象
/**
* 用于创造一个sqlSessionFactory实列
*/
public class SqlSessionFactoryBuilder {
/**
* 根据字节流构建一个工厂类
* @param config
* @return
*/
public SqlSessionFactory build(InputStream config) throws DocumentException {
Configuration configuration = XMLConfigBuilder.loadConfiguration(config);
return new DefaultSqlSessionFactory(configuration);
}
}
utils
XMLConfigBuilder.java
解析主配置文件
这块主要通过主配置文件下mappers标签下的mapper标签对应的class或者resource判断是否通过的是注解形式还是xml形式
/**
* 用于解析配置文件
*/
public class XMLConfigBuilder {
/**
* 解析主配置文件,把里面的内容填充到DefaultSqlSession所需要的地方
* 使用的技术:dom4j+xpath
*/
public static Configuration loadConfiguration(InputStream config){
try{
//定义封装连接信息的配置对象(mybatis的配置对象)
Configuration configuration = new Configuration();
//1.获取SAXReader对象
SAXReader reader = new SAXReader();
//2.根据字节输入流获取Document对象
Document document = reader.read(config);
//3.获取根节点
Element root = document.getRootElement();
//4.使用xpath中选择指定节点的方式,获取所有property节点
List<Element> propertyElements = root.selectNodes("//property");
//5.遍历节点
for(Element propertyElement : propertyElements){
//判断节点是连接数据库的哪部分信息
//取出name属性的值
String name = propertyElement.attributeValue("name");
if("driver".equals(name)){
//表示驱动
//获取property标签value属性的值
String driver = propertyElement.attributeValue("value");
configuration.setDriver(driver);
} else if("url".equals(name)){
//表示连接字符串
//获取property标签value属性的值
String url = propertyElement.attributeValue("value");
configuration.setUrl(url);
} else if("username".equals(name)){
//表示用户名
//获取property标签value属性的值
String username = propertyElement.attributeValue("value");
configuration.setUsername(username);
} else{
//表示密码
//获取property标签value属性的值
String password = propertyElement.attributeValue("value");
configuration.setPassword(password);
}
}
//加载映射文件
//取出mappers中的所有mapper标签,判断他们使用了resource还是class属性
List<Element> mapperElements = root.selectNodes("//mappers/mapper");
//遍历集合
for(Element mapperElement : mapperElements){
//判断mapperElement使用的是哪个属性
Attribute attribute = mapperElement.attribute("resource");
if(attribute != null){//使用的是xml文件
//表示有resource属性,用的是XML
//取出属性的值
String mapperPath = attribute.getValue();//获取属性的值"com/itheima/dao/IUserDao.xml"
//把映射配置文件的内容获取出来,封装成一个map
Map<String,Mapper> mappers = loadMapperConfiguration(mapperPath);
//给configuration中的mappers赋值
configuration.setMappers(mappers);
}else{
System.out.println("使用的是注解");
//表示没有resource属性,用的是注解
//获取class属性的值
String daoClassPath = mapperElement.attributeValue("class");
//根据daoClassPath获取封装的必要信息
Map<String,Mapper> mappers = loadMapperAnnotation(daoClassPath);
//给configuration中的mappers赋值
configuration.setMappers(mappers);
}
}
//返回Configuration
return configuration;
}catch(Exception e){
throw new RuntimeException(e);
}finally{
try {
config.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
/**
* 根据传入的参数,解析XML,并且封装到Map中
* @param mapperPath 映射配置文件的位置
* @return map中包含了获取的唯一标识(key是由dao的全限定类名和方法名组成)
* 以及执行所需的必要信息(value是一个Mapper对象,里面存放的是执行的SQL语句和要封装的实体类全限定类名)
*/
private static Map<String,Mapper> loadMapperConfiguration(String mapperPath)throws IOException {
InputStream in = null;
try{
//定义返回值对象
Map<String,Mapper> mappers = new HashMap<String,Mapper>();
//1.根据路径获取字节输入流
in = Resources.getResourceAsStream(mapperPath);
//2.根据字节输入流获取Document对象
SAXReader reader = new SAXReader();
Document document = reader.read(in);
//3.获取根节点
Element root = document.getRootElement();
//4.获取根节点的namespace属性取值
String namespace = root.attributeValue("namespace");//是组成map中key的部分
//5.获取所有的select节点
List<Element> selectElements = root.selectNodes("//select");
//6.遍历select节点集合
for(Element selectElement : selectElements){
//取出id属性的值 组成map中key的部分
String id = selectElement.attributeValue("id");
//取出resultType属性的值 组成map中value的部分
String resultType = selectElement.attributeValue("resultType");
//取出文本内容 组成map中value的部分
String queryString = selectElement.getText();
//创建Key
String key = namespace+"."+id;
//创建Value
Mapper mapper = new Mapper();
mapper.setQueryString(queryString);
mapper.setResultType(resultType);
//把key和value存入mappers中
mappers.put(key,mapper);
}
return mappers;
}catch(Exception e){
throw new RuntimeException(e);
}finally{
in.close();
}
}
/**
* 根据传入的参数,得到dao中所有被select注解标注的方法。
* 根据方法名称和类名,以及方法上注解value属性的值,组成Mapper的必要信息
* @param daoClassPath
* @return
*/
private static Map<String,Mapper> loadMapperAnnotation(String daoClassPath)throws Exception{
//定义返回值对象
Map<String,Mapper> mappers = new HashMap<>();
//1.得到dao接口的字节码对象
Class daoClass = Class.forName(daoClassPath);
//2.得到dao接口中的方法数组
Method[] methods = daoClass.getMethods();
//3.遍历Method数组
for(Method method : methods){
//取出每一个方法,判断是否有select注解
boolean isAnnotated = method.isAnnotationPresent(Select.class);
if(isAnnotated){
//创建Mapper对象
Mapper mapper = new Mapper();
//取出注解的value属性值
Select selectAnno = method.getAnnotation(Select.class);
String queryString = selectAnno.value();
mapper.setQueryString(queryString);
//获取当前方法的返回值,还要求必须带有泛型信息
Type type = method.getGenericReturnType();//List<User>
//判断type是不是参数化的类型
if(type instanceof ParameterizedType){
//强转
ParameterizedType ptype = (ParameterizedType)type;
//得到参数化类型中的实际类型参数
Type[] types = ptype.getActualTypeArguments();
//取出第一个
Class domainClass = (Class)types[0];
//获取domainClass的类名
String resultType = domainClass.getName();
//给Mapper赋值
mapper.setResultType(resultType);
}
//组装key的信息
//获取方法的名称
String methodName = method.getName();
String className = method.getDeclaringClass().getName();
String key = className+"."+methodName;
//给map赋值
mappers.put(key,mapper);
}
}
return mappers;
}
}
DataSourceUtil.java
加载驱动以及建立与之数据库建立连接
/**
* 用于创建数据源的工具类
*/
public class DataSourceUtil {
public static Connection getConnection(Configuration configuration){
Connection connection = null;
try {
//加载驱动
Class.forName(configuration.getDriver());
//建立连接
connection = DriverManager.getConnection(configuration.getUrl(), configuration.getUsername(), configuration.getPassword());
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
}
Executor.java
执行查询的操作
执行的时机:创建dao层实现类增强的时候调用Executor
/**
* 负责执行SQL语句,并且封装结果集
*/
public class Executor {
public <E> List<E> selectList(Mapper mapper, Connection connection){
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
ArrayList<E> list = null;
try {
//1.取出mapper中的数据
String queryString = mapper.getQueryString();
String resultType = mapper.getResultType();
Class domainClass = Class.forName(resultType);
//2.获取preparedStatement对象
preparedStatement = connection.prepareStatement(queryString);
//3.执行SQL语句,获取结果集
resultSet = preparedStatement.executeQuery();
//4.封装结果集
list = new ArrayList<>();//定义返回值
while(resultSet.next()){
//实例化要封装的实体类的对象
E e = (E) domainClass.newInstance();
//取出结果集的元信息,ResultSetMetaData
ResultSetMetaData metaData = resultSet.getMetaData();
//取出总列数
int columnCount = metaData.getColumnCount();
//遍历总列数
for (int i = 1; i <= columnCount; i++) {
//获取每列的名称,列名的序号是从1开始的
String columnName = metaData.getColumnName(i);
//根据列名获取每列的值
Object columnValue = resultSet.getObject(columnName);
//给e赋值,使用java内省机制(借助PropertyDescriptor实现属性的封装)
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, domainClass);
//获取他的写入方法
Method writeMethod = propertyDescriptor.getWriteMethod();
//把获取列的值给对象赋值
writeMethod.invoke(e,columnValue);
}
//把赋好值的对象加入到集合之中
list.add(e);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
resource
mybatis-config.xml
主配置文件主要的目的:加载数据源和连接数据库
配置映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!-- mybatis的主配置文件 -->
<configuration>
<!-- 配置环境 -->
<environments default="mysql">
<!-- 配置mysql的环境-->
<environment id="mysql">
<!-- 配置事务的类型-->
<transactionManager type="JDBC"></transactionManager>
<!-- 配置数据源(连接池) -->
<dataSource type="POOLED">
<!-- 配置连接数据库的4个基本信息 -->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件 -->
<mappers>
<!--<mapper resource="mapper/UserDao.xml"/>-->
<mapper class="com.dao.UserDao"/>
</mappers>
</configuration>
mapper
UserDao.xml
映射文件
主要是配置返回的结果集以及SQL语句
<?xml version="1.0" encoding="UTF-8" ?>
<mapper namespace="com.dao.UserDao">
<select id="findAll" resultType="com.bean.user">
select * from user
</select>
</mapper>
要引入的依赖
<!--mysql操作-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<!--log4j-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--测试依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--dom4j-->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.5.2</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.2.0</version>
</dependency>
注意这里不可以导入mybatis否则在加载包路径的时候容易造成错误