我們?cè)谑褂胢ybatis做orm時(shí), 只需要告知框架我們的mapper映射和domian所在位置即可, 不需要實(shí)現(xiàn)類, mybatis是如何幫我們?cè)L問(wèn)數(shù)據(jù)庫(kù)的呢 ?
debug查看dao接口的mybatis的實(shí)現(xiàn)類
// 追蹤代碼每個(gè)接口的實(shí)現(xiàn)類是MapperProxy
// 該類實(shí)現(xiàn)了 `InvocationHandler` 使用的jdk的動(dòng)態(tài)代理
public class MapperProxy<T> implements InvocationHandler, Serializable {
}
我們自己來(lái)實(shí)現(xiàn)一個(gè)簡(jiǎn)單的mybatis
- 創(chuàng)建接口
- 創(chuàng)建代理類
- 向mvc中注入代理類
- 測(cè)試調(diào)用
創(chuàng)建接口類
public interface UserDao {
public User getById(String id);
}
創(chuàng)建代理類
public class IBatisProxy implements InvocationHandler
{
private HikariDataSource pool;
public IBatisProxy(HikariDataSource pool)
{
this.pool = pool;
}
@ Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
Connection connection = pool.getConnection();
PreparedStatement statement = connection.prepareStatement("select * from dem_user where id =?");
statement.setString(1, args[0].toString());
ResultSet resultSet = statement.executeQuery();
resultSet.next();
String id = resultSet.getString("id");
String name = resultSet.getString("name");
String account = resultSet.getString("account");
String password = resultSet.getString("password");
String auth = resultSet.getString("auth");
String organId = resultSet.getString("organ_id");
User user = new User(id, name, account, password, auth, organId);
connection.close();
return user;
}
}
向ApplicationContext中注入代理類
@ Configuration
public class UserDaoConfig
{
@ Autowired
private HikariDataSource hikariDataSource;
@ Bean
public UserDao userDao2()
{
Class<UserDao> clazz = UserDao.class;
UserDao userDao = (UserDao)Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[]{clazz},
new IBatisProxy(hikariDataSource));
return userDao;
}
}
測(cè)試調(diào)用
@ RestController
public class HelloWorldController
{
@ Autowired
@ Qualifier("userDao2")
private UserDao userDao;
@ RequestMapping("/user/{id}")
@ Transactional
public com.inus.domain.User getUser(@ PathVariable String id)
{
if (StringUtils.isNotEmpty(id))
{
return userDao.getById(id);
}
return null;
}
}