核心配置文件mybatis.cfg.xml
在里面配置
util MyBatisUtil.java
package com.yxxy.mybatis.util;
import java.io.InputStream;
public class MyBatisUtil{
private static SqlSessionFactory sqlSessionFactory=null;
private static SqlSession sqlSession=null;
private static String resource=null;
public static SqlSessionFactory getSqlSessionFactory {
resource="mybatis.cfg.xml";
InputStream inputStream=null;
try{
inputStream=Resources.getResourceAsStream(resource);
sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
}catch(Exception e){
e.printStackTrace();
}
return sqlSessionFactory;
}
mapper UserMapper.java
package com.yxxy.mybatis.mapper;
import com.yxxy.mybatis.entiey.User;
public interface UserMapper{
User selectUserById(Integer id);
}
使用mybatis框架时根本不需要自己创建实现类,只有接口
test Test.java
package com.yxxy.mybatis.test;
import org.apache.ibatis.session.SqlSession;
public class Test{
public static void main(String[] args){
SqlSession sqlsession=MyBatisUtil.getSession();//打一个断点,通过debug模式启动
UserMapper userMapper=sqlsession.getMapper(UserMapper.class);
User user=userMapper.selectUserById(1);
System.out.println(user);
MyBatisUtil.closeSession();
}
}
SqlSession sqlsession=MyBatisUtil.getSession();//打一个断点,通过debug模式启动
UserMapper userMapper=sqlsession.getMapper(UserMapper.class);//使用mybatis框架时根本不需要自己创建实现类,只有接口
首先要读取配置文件mybatis.cfg.xml和UserMapper.xml
一个加载了数据库连接信息,一个读取我们编写的SQL信息
分析完源码后,自己写一个这样的框架
1、解析配置文件–UserMapper.xml的解析工具类
硬编码:直接写死在那里
2、实现动态代理–MapperProxy
3、加载代理对象并执行SQL–SqlSession
4、封装JDBC–Executor接口和它的实现SimpleExecutor
5、mybatis的mapper接口–UserMapper类
6、映射数据库实体–User类
UserMapper.xml
namespace
map key-value
MapperProxy
实现的invokahandler
invoke方法method,args
SqlSession
T getMapper
T selectOne(String sql,)
Executor
query
总共八个类实现
新建项目Java Project mybatis_hello
->将mysql的jar包导入
->新建包com.yxxy.mybatis.entity
User.java
UserMapperXml.java
public class UserMapperXml{
//模拟UserMapper.xml的命名空间
public static final String namespace=“com.yxxy.mybatis.mapper.UserMapper”;
public static Map<String,String> map=new HashMap<>();
static{//模拟
->新建包com.yxxy.mybatis.executor
Excutor.java
public class Excutor{
SimpleExcutor.java
封装JDBC实现CURD
public query(String sql,Object parameter){
Connection connection=null;
PrepareStatement prepared
private Connection getConnection(){
String driver="";
String url="";
String username="";
String password="";
Class.forName(driver);
Connection connection
->新建包com.yxxy.mybatis.mapper
UserMapper.java
public interface UserMapper{
User selectUserById(Integer id);
MapperProxy.java
public class MapperProxy implements InvocationHandler{
private SqlSession sqlSession
public Objecy invoke(Object proxy,Method method,Ob){
if(){
String sql=UserMapperXml.map.get();
session SqlSession.java
加载代理对象执行SQL的类
public class SqlSession{
private Executor executor=new SimpleExecutor();
public T selectOne(String statement,Object patameter){
return executor.query(statement,parameter);
}
public T getMapper(Class clazz){
return Proxy.newIn