Mybatis之自定义Mybatis(二)
一、添加依赖
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
<!-- 解析xml的dom4j -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<!-- dom4j的依赖包jaxen -->
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</dependency>
</dependencies>
二、自定义mybatis框架
依据Mybatis的基本使用,创建相应自定义类.
public static void main(String[] args)throws Exception {
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
SqlSession session = factory.openSession();
IUserDao userDao = session.getMapper(IUserDao.class);
List<User> users = userDao.findAll();
for(User user : users){
System.out.println(user);
}
session.close();
in.close();
}
1.定义SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<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>
<mappers>
<mapper resource="cn/ybzy/dao/IUserDao.xml"/>
</mappers>
</configuration>
2.定义mybatis核心配置类
public class Configuration {
private String driver;
private String url;
private String username;
private String password;
private Map<String,Mapper> mappers = new HashMap<String,Mapper>();
public Map<String, Mapper> getMappers() {
return mappers;
}
public void setMappers(Map<String, Mapper> mappers) {
this.mappers.putAll(mappers);
}
}
3.定义封装Mapper
public class Mapper {
private String queryString;
private String resultType;
}
4.定义实体类
public class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
}
5.定义解析配置文件逻辑
public class XMLConfigBuilder {
public static Configuration loadConfiguration(InputStream inputStream){
try{
Configuration cfg = new Configuration();
SAXReader reader = new SAXReader();
Document document = reader.read(inputStream);
Element root = document.getRootElement();
List<Element> propertyElements = root.selectNodes("//property");
for(Element propertyElement : propertyElements){
String name = propertyElement.attributeValue("name");
if("driver".equals(name)){
String driver = propertyElement.attributeValue("value");
cfg.setDriver(driver);
}
if("url".equals(name)){
String url = propertyElement.attributeValue("value");
cfg.setUrl(url);
}
if("username".equals(name)){
String username = propertyElement.attributeValue("value");
cfg.setUsername(username);
}
if("password".equals(name)){
String password = propertyElement.attributeValue("value");
cfg.setPassword(password);
}
}
List<Element> mapperElements = root.selectNodes("//mappers/mapper");
for(Element mapperElement : mapperElements){
Attribute attribute = mapperElement.attribute("resource");
if(attribute != null){
System.out.println("使用的是XML");
String mapperPath = attribute.getValue();
Map<String,Mapper> mappers = loadMapperConfiguration(mapperPath);
cfg.setMappers(mappers);
}else{
System.out.println("使用的是注解");
String classPath = mapperElement.attributeValue("class");
Map<String,Mapper> mappers = loadMapperAnnotation(classPath);
cfg.setMappers(mappers);
}
}
return cfg;
}catch(Exception e){
throw new RuntimeException(e);
}finally{
try {
inputStream.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
private static Map<String,Mapper> loadMapperConfiguration(String mapperPath)throws IOException {
InputStream in = null;
try{
Map<String,Mapper> mappers = new HashMap<String,Mapper>();
in = Resources.getResourceAsStream(mapperPath);
SAXReader reader = new SAXReader();
Document document = reader.read(in);
Element root = document.getRootElement();
String namespace = root.attributeValue("namespace");
List<Element> selectElements = root.selectNodes("//select");
for(Element selectElement : selectElements){
String id = selectElement.attributeValue("id");
String resultType = selectElement.attributeValue("resultType");
String queryString = selectElement.getText();
String key = namespace+"."+id;
Mapper mapper = new Mapper();
mapper.setQueryString(queryString);
mapper.setResultType(resultType);
mappers.put(key,mapper);
}
return mappers;
}catch(Exception e){
throw new RuntimeException(e);
}finally{
in.close();
}
}
private static Map<String,Mapper> loadMapperAnnotation(String classPath)throws Exception{
Map<String,Mapper> mappers = new HashMap<String, Mapper>();
Class daoClass = Class.forName(classPath);
Method[] methods = daoClass.getMethods();
for(Method method : methods){
boolean isAnnotated = method.isAnnotationPresent(Select.class);
if(isAnnotated){
Mapper mapper = new Mapper();
Select selectAnno = method.getAnnotation(Select.class);
String queryString = selectAnno.value();
mapper.setQueryString(queryString);
Type type = method.getGenericReturnType();
if(type instanceof ParameterizedType){
ParameterizedType ptype = (ParameterizedType)type;
Type[] types = ptype.getActualTypeArguments();
Class domainClass = (Class)types[0];
String resultType = domainClass.getName();
mapper.setResultType(resultType);
}
String methodName = method.getName();
String className = method.getDeclaringClass().getName();
String key = className+"."+methodName;
mappers.put(key,mapper);
}
}
return mappers;
}
}
6.定义读取配置文件类
public class Resources {
public static InputStream getResourceAsStream(String filePath){
return Resources.class.getClassLoader().getResourceAsStream(filePath);
}
}
7.定义SqlSessionFactoryBuilder构建者对象
public class SqlSessionFactoryBuilder {
public SqlSessionFactory build(InputStream inputStream){
Configuration cfg = XMLConfigBuilder.loadConfiguration(inputStream);
return new DefaultSqlSessionFactory(cfg);
}
}
8.定义SqlSessionFactory接口和实现类
public interface SqlSessionFactory {
SqlSession openSession();
}
public class DefaultSqlSessionFactory implements SqlSessionFactory{
private Configuration cfg;
public DefaultSqlSessionFactory(Configuration cfg){
this.cfg = cfg;
}
@Override
public SqlSession openSession() {
return new DefaultSqlSession(cfg);
}
}
9.定义SqlSession接口和实现类
public interface SqlSession {
<T> T getMapper(Class<T> daoInterfaceClass);
void close();
}
public class DefaultSqlSession implements SqlSession {
private Configuration cfg;
private Connection connection;
public DefaultSqlSession(Configuration cfg){
this.cfg = cfg;
connection = DataSourceUtil.getConnection(cfg);
}
@Override
public <T> T getMapper(Class<T> daoInterfaceClass) {
return (T) Proxy.newProxyInstance(daoInterfaceClass.getClassLoader(),
new Class[]{daoInterfaceClass},new MapperProxy(cfg.getMappers(),connection));
}
@Override
public void close() {
if(connection != null) {
try {
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
10.定义获取连接工具类
public class DataSourceUtil {
public static Connection getConnection(Configuration cfg){
try {
Class.forName(cfg.getDriver());
return DriverManager.getConnection(cfg.getUrl(), cfg.getUsername(), cfg.getPassword());
}catch(Exception e){
throw new RuntimeException(e);
}
}
}
11.定义创建Dao接口代理对象的类
public class MapperProxy implements InvocationHandler {
private Map<String,Mapper> mappers;
private Connection conn;
public MapperProxy(Map<String,Mapper> mappers,Connection conn){
this.mappers = mappers;
this.conn = conn;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
String className = method.getDeclaringClass().getName();
String key = className+"."+methodName;
Mapper mapper = mappers.get(key);
if(mapper == null){
throw new IllegalArgumentException("传入的参数有误,无法获取执行的必要条件");
}
return new Executor().selectList(mapper,conn);
}
}
12.定义执行对象
public class Executor {
public <E> List<E> selectList(Mapper mapper, Connection conn) {
PreparedStatement pstm = null;
ResultSet rs = null;
try {
String queryString = mapper.getQueryString();
String resultType = mapper.getResultType();
Class domainClass = Class.forName(resultType);
pstm = conn.prepareStatement(queryString);
rs = pstm.executeQuery();
List<E> list = new ArrayList<E>();
while(rs.next()) {
E obj = (E)domainClass.newInstance();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
String columnName = rsmd.getColumnName(i);
Object columnValue = rs.getObject(columnName);
PropertyDescriptor pd = new PropertyDescriptor(columnName,domainClass);
Method writeMethod = pd.getWriteMethod();
writeMethod.invoke(obj,columnValue);
}
list.add(obj);
}
return list;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
release(pstm,rs);
}
}
private void release(PreparedStatement pstm,ResultSet rs){
if(rs != null){
try {
rs.close();
}catch(Exception e){
e.printStackTrace();
}
}
if(pstm != null){
try {
pstm.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
三、基于 XML使用自定义Mybatis框架
1.编写持久层接口和IUserDao.xml
public interface IUserDao {
List<User> findAll();
}
<?xml version="1.0" encoding="UTF-8"?>
<mapper namespace="cn.ybzy.dao.IUserDao">
<!--查询所有-->
<select id="findAll" resultType="cn.ybzy.model.User">
select * from user
</select>
</mapper>
2.执行测试
public class MybatisTest {
public static void main(String[] args)throws Exception {
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
SqlSession session = factory.openSession();
IUserDao userDao = session.getMapper(IUserDao.class);
List<User> users = userDao.findAll();
for(User user : users){
System.out.println(user);
}
session.close();
in.close();
}
}
四、基于注解使用自定义Mybatis 框架
1.自定义@Select 注解
定义查询注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Select {
String value();
}
2.修改持久层接口
public interface IUserDao {
@Select("select * from user")
List<User> findAll();
}
3. 修改SqlMapConfig.xml
修改SqlMapConfig.xml配置文件中mappers节点标签中内容
<mappers>
<mapper class="cn.ybzy.dao.IUserDao"/>
</mappers>
4.执行测试
public class MybatisTest {
public static void main(String[] args)throws Exception {
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
SqlSession session = factory.openSession();
IUserDao userDao = session.getMapper(IUserDao.class);
List<User> users = userDao.findAll();
for(User user : users){
System.out.println(user);
}
session.close();
in.close();
}
}