手写orm
what?
orm->object -relation -mapping。
?
why?
减少代码冗余,提高代码的可复用性。
?
?
数据库配置文件ORM-DriverConfig.xml
<?xml version="1.0" encoding="UTF-8"?><Driver nsme="Mysql" state="true"> <DriverName>com.mysql.jdbc.Driver</DriverName> <url>jdbc:mysql://localhost:3306/test</url> <userName>root</userName> <pwd>xuxie</pwd></Driver>
?
?
封装sql与映射
<?xml version="1.0" encoding="UTF-8"?><sql><resultMap id="UserResult" table="s_user"><result property="id" column="id" /><result property="name" column="name" /><result property="age" column="age" /></resultMap><SQL id="SELECT_ALL" resultMap = "UserResult">select age,name from s_user</SQL><SQL id="DELETE_ID">delete from s_user where id =?</SQL><SQL id="INSERT_OBJECT">insert into s_user values(?,?,?,'')</SQL><SQL id="SELECT_NAME">select * from s_user where name like "%"?"%"</SQL></sql>
?
pojo
package com.aptech.orm.pojo;import java.sql.Blob;public class User{private int id;private String name;private int age;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}
?
工具类
package com.aptech.orm.util;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.jdom.Document;import org.jdom.Element;import org.jdom.JDOMException;import org.jdom.input.SAXBuilder;public class ORMUtil {public static Document getDbDocument() {Document document = null;SAXBuilder builder = new SAXBuilder();FileInputStream fileInputStream = null;try {fileInputStream = new FileInputStream(new File("./src/ORM-DriverConfig.xml"));document = builder.build(fileInputStream);} catch (FileNotFoundException e) {e.printStackTrace();} catch (JDOMException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (null != fileInputStream) {fileInputStream.close();}} catch (IOException e) {e.printStackTrace();}}return document;}public static Document getSqlDocument() {Document document = null;SAXBuilder builder = new SAXBuilder();FileInputStream fileInputStream = null;try {fileInputStream = new FileInputStream(new File("./src/ORM-Sql.xml"));document = builder.build(fileInputStream);} catch (FileNotFoundException e) {e.printStackTrace();} catch (JDOMException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (null != fileInputStream) {fileInputStream.close();}} catch (IOException e) {e.printStackTrace();}}return document;}public static Connection getConnection() {Connection con = null;try {Document document = getDbDocument();Element rootElement = document.getRootElement();String DriverName = rootElement.getChildText("DriverName");String url = rootElement.getChildText("url");String userName = rootElement.getChildText("userName");String pwd = rootElement.getChildText("pwd");Class.forName(DriverName);con = DriverManager.getConnection(url, userName, pwd);} catch (Exception e) {e.printStackTrace();}return con;}public static List<Element> getSqlElement() {Document document = getSqlDocument();Element root = document.getRootElement();List<Element> children = root.getChildren("SQL");return children;}public static List<Element> getResultMapElement() {Document document = getSqlDocument();Element root = document.getRootElement();List<Element> children = root.getChildren("resultMap");return children;}public static List<Element> getResultElement(String id) {List resultElementList = null;List<Element> children = getResultMapElement();for (Element element : children) {if (id.equals(element.getAttributeValue("id"))) {resultElementList = element.getChildren();break;}}return resultElementList;}public static String getSQL(String id) {String sql = "";List<Element> sqlElement = getSqlElement();for (Element element : sqlElement) {if (id.equals(element.getAttributeValue("id"))) {sql = element.getText();break;}}return sql;}public static String getResultMap(String id) {String resultMap = "";List<Element> sqlElement = getSqlElement();for (Element element : sqlElement) {if (id.equals(element.getAttributeValue("id"))) {resultMap = element.getAttributeValue("resultMap");break;}}return resultMap;}public static void close(Connection con, Statement stmt, ResultSet rs) {if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}}if (stmt != null) {try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}if (con != null) {try {con.close();} catch (SQLException e) {e.printStackTrace();}}}public static Map getResultMap(ResultSet rs) {Map map = new HashMap();try {ResultSetMetaData meta = rs.getMetaData();int clos = meta.getColumnCount();while (rs.next()) {for (int i = 1; i <= clos; i++) {map.put(meta.getColumnName(i), rs.getObject(i));}}} catch (SQLException e) {e.printStackTrace();}return map;}/** * * 〈获取查询的数据字段〉 * @param [rs] [结果集] * @return [字段集合] * @Author YangZhuan */public static List getResultFields(ResultSet rs) {List list = new ArrayList();try {ResultSetMetaData meta = rs.getMetaData();int clos = meta.getColumnCount();for (int i = 1; i <= clos; i++) {list.add(meta.getColumnName(i));}} catch (SQLException e) {e.printStackTrace();}return list;}/** * * 〈关系型数据映射为对象〉 * @param [rs] [结果集] * @param [id] [对应的mapping] * @return [Object] * @Author YangZhuan */public static Object getObject(ResultSet rs,String id) {//获取类路径String classPath = getClass(id);Object object = null;try {//所有字段List fieldsList = getResultFields(rs);//类实例化object = Class.forName(classPath).newInstance();//当前类的方法数组Method[] methods = object.getClass().getMethods();//遍历方法数组for (int i = 0; i < methods.length; i++) {//方法名String methodName = methods[i].getName();//只处理以set开头的方法if(methodName.startsWith("set")){//字段名String field = methodName.substring(3).toLowerCase();//判断当前子段是否使用if(fieldsList.contains(field)) {//隐式的方法调用methods[i].invoke(object, rs.getObject(field));}}}} catch (SQLException e) {e.printStackTrace();} catch (InstantiationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InvocationTargetException e) {// TODO Auto-generated catch blocke.printStackTrace();}return object;}public static String getClass(String id) {String classPath = "";try {List<Element> children = getResultMapElement();for (Element element : children) {if (id.equals(element.getAttributeValue("id"))) {classPath = element.getAttributeValue("class");break;}}} catch (Exception e) {e.printStackTrace();}return classPath;}}
?
执行
package com.aptech.orm.manage;import java.io.File;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.sql.Blob;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import com.aptech.orm.pojo.User;import com.aptech.orm.util.ORMUtil;public class ORMProcess {public static List QueryForList(String str) {List list = new ArrayList();Connection con = null;PreparedStatement ps = null;ResultSet rs = null;try {String sql = ORMUtil.getSQL(str);con = ORMUtil.getConnection();ps = con.prepareStatement(sql);ps.execute();rs = ps.getResultSet();while(rs.next()){Object obj = ORMUtil.getObject(rs, ORMUtil.getResultMap(str));list.add(obj);}} catch (Exception e) {e.printStackTrace();} finally {ORMUtil.close(con, ps, rs);}return list;}public static void main(String[] args) {List<User> list = QueryForList("SELECT_ALL");for (User user : list) {System.out.println("id:"+user.getId()+"name:"+user.getName()+"age:"+user.getAge());}}}
?
?