代码路径:https://github.com/m2492565210/java_orm自行下载

框架的类结构如下,anno包下注解和MODEL类结合用于定义数据库结构。MyORM类是工具类,获取工厂SESSIONFACTORY,工厂资源采用单例模式,目前没有考虑线程安全。使用工厂获取SESSION,利用SESSION类是数据库直接执行者,通过传入MODEL完成数据库读写。时间有限,SESSION方法中只是完成写数据库语句,并没有真正进行数据库操作。

测试类中有SESSION的使用方法,如下。

    @Test
    public void test() throws ClassNotFoundException, SQLException, IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
    {
        Session ss = MyORM.getSessionFactory("db.properties").openConnection();//db.properties是数据库URL,密码等信息,
        
        ss.save(new Student(1001, "A", 27));
        ss.update(new Student(1001, "A", 27));
        ss.delete(new Student(1001, "A", 27));
        ss.query(new Student(1001, "A", 27));
        
        ss.close();
    }

MyORM:

package m.cnblogs.com.orm;

import m.cnblogs.com.orm.conn.Factory;
import m.cnblogs.com.orm.conn.Session;

public final class MyORM
{
    private static Factory sin = null;
    
    private static class SessionFactory implements Factory
    {
        private SessionFactory(String path) throws ClassNotFoundException
        {
            System.out.println("use the file path provided to init factory");
        }
        
        public Session openConnection()
        {
            return new Session();
        }

    }
    
    public static Factory getSessionFactory(String path) throws ClassNotFoundException
    {
        if (null == sin)
        {
            sin = new SessionFactory(path);
        }
        return sin;
    }
}

 

Student类对应数据表,定义如下:

@Table(name = "STUDENT")
public class Student
{
    @ID //框架中定义的注解
    @Property(name = "ID", type = "int")
    private int id;
    @Property(name = "NAME", type = "varchar")
    private String name;
    @Property(name = "AGE", type = "int")
    private int age;
    
    public Student(int id, String name, int age)
    {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }
    public Integer 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;
    }
}

session.java

package m.cnblogs.com.orm.conn;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import m.cnblogs.com.orm.anno.ID;
import m.cnblogs.com.orm.anno.Property;
import m.cnblogs.com.orm.anno.Table;

public class Session
{
    
    public Session()
    {
        System.out.println("SESSION INIT");
    }
    
    public <T> void save(T obj) throws NoSuchMethodException, SecurityException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException
    {
        Class<? extends Object> cls = obj.getClass();
        
        StringBuffer sql = new StringBuffer();
        
        sql.append("INSERT INTO ");
        
        Table tbl = (Table) cls.getAnnotation(Table.class);
        
        if (null != tbl)
        {
            sql.append(tbl.name());
        }
        else
        {
            sql.append(cls.getName().substring(cls.getName().lastIndexOf(".") + 1));
        }
        
        sql.append("( ");
        
        Field[] fields = cls.getDeclaredFields();
        StringBuffer valueSql = new StringBuffer();
        
        for (Field field : fields)
        {
            
            Property proper = field.getAnnotation(Property.class);
            
            // 获得字段第一个字母大写
            String methodFirstLetter = field.getName().substring(0, 1).toUpperCase();
            // 转换成字段的get方法
            String getterName = "get" + methodFirstLetter + field.getName().substring(1);
            
            Method getMethod = cls.getMethod(getterName, new Class[]
            {});
            // 这个对象字段get方法的值
            Object value = getMethod.invoke(obj, new Object[]
            {});
            
            if (field.getType().getName().equals(java.lang.String.class.getName()))
            {
                valueSql.append("'" + value + "'").append(",");
            }
            else
            {
                valueSql.append(value).append(",");
            }
            
            if (null != proper)
            {
                sql.append(proper.name()).append(",");
            }
            else
            {
                sql.append(field.getName()).append(",");
            }
        }
        
        valueSql.deleteCharAt(valueSql.length() - 1);
        sql.deleteCharAt(sql.length() - 1);
        sql.append(" ) VALUES( ");
        sql.append(valueSql);
        sql.append(" )");
        
        System.out.println(sql.toString());
    }
    
    public <T> void query(T obj) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
    {
        Class<? extends Object> cls = obj.getClass();
        
        StringBuffer sql = new StringBuffer();
          
        sql.append("SELETE FROM ");  
          
        Table tbl = (Table)cls.getAnnotation(Table.class);
        
        if (null != tbl) {  
            sql.append(tbl.name());  
        } else {  
            sql.append(cls.getName().substring(cls.getName().lastIndexOf(".")+1));  
        }  
          
        Field[] fields = cls.getDeclaredFields();  
        
        for (Field field : fields) {
            
            if (null != field.getAnnotation(ID.class))
            {
                //获得字段第一个字母大写   
                String methodFirstLetter = field.getName().substring(0,1).toUpperCase();   
                //转换成字段的get方法  
                String getterName = "get" + methodFirstLetter + field.getName().substring(1);    
                      
                Method getMethod = cls.getMethod(getterName, new Class[] {});  
                //这个对象字段get方法的值   
                Object value = getMethod.invoke(obj, new Object[] {});
                sql.append(" WHERE ").append(field.getName()).append("=");
                if (field.getType().getName().equals(java.lang.String.class.getName())) {  
                    sql.append("'" + value + "'");  
                } else {  
                    sql.append(value);  
                } 
            }
            
   
        }  
        
        System.out.println(sql.toString());
        
    }
    
    public <T> void update(T obj) throws NoSuchMethodException, SecurityException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException
    {
        Class<? extends Object> cls = obj.getClass();
        
        StringBuffer sql = new StringBuffer();
        StringBuffer condition = new StringBuffer();
        
        sql.append("UPDATE ");
        
        Table tbl = (Table) cls.getAnnotation(Table.class);
        
        if (null != tbl)
        {
            sql.append(tbl.name());
        }
        else
        {
            sql.append(cls.getName().substring(cls.getName().lastIndexOf(".") + 1));
        }
        
        sql.append(" SET ");
        
        Field[] fields = cls.getDeclaredFields();
        
        for (Field field : fields)
        {
            
            Property proper = field.getAnnotation(Property.class);
            
            // 获得字段第一个字母大写
            String methodFirstLetter = field.getName().substring(0, 1).toUpperCase();
            // 转换成字段的get方法
            String getterName = "get" + methodFirstLetter + field.getName().substring(1);
            
            Method getMethod = cls.getMethod(getterName, new Class[]
            {});
            // 这个对象字段get方法的值
            Object value = getMethod.invoke(obj, new Object[]
            {});
            
            if (null != field.getAnnotation(ID.class))
            {
                condition.append(" WHERE ").append(field.getName()).append("=");
                if (field.getType().getName().equals(java.lang.String.class.getName()))
                {
                    condition.append("'" + value + "'");
                }
                else
                {
                    condition.append(value);
                }
            }
            else
            {
                String tmp = "";
                
                if (field.getType().getName().equals(java.lang.String.class.getName()))
                {
                    tmp = "'" + value + "'";
                }
                else
                {
                    tmp = value + "";
                }
                
                if (null != proper)
                {
                    sql.append(proper.name()).append("=").append(tmp).append(",");
                }
                else
                {
                    sql.append(field.getName()).append("=").append(tmp).append(",");
                }
            }
            
        }
        
        sql.deleteCharAt(sql.length() - 1);
        
        sql.append(condition);
        
        System.out.println(sql.toString());
    }
    
    public <T> void delete(T obj) throws NoSuchMethodException, SecurityException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException
    {
        Class<? extends Object> cls = obj.getClass();
        
        StringBuffer sql = new StringBuffer();
        
        sql.append("DELETE FROM ");
        
        Table tbl = (Table) cls.getAnnotation(Table.class);
        
        if (null != tbl)
        {
            sql.append(tbl.name());
        }
        else
        {
            sql.append(cls.getName().substring(cls.getName().lastIndexOf(".") + 1));
        }
        
        Field[] fields = cls.getDeclaredFields();
        
        for (Field field : fields)
        {
            
            if (null != field.getAnnotation(ID.class))
            {
                // 获得字段第一个字母大写
                String methodFirstLetter = field.getName().substring(0, 1).toUpperCase();
                // 转换成字段的get方法
                String getterName = "get" + methodFirstLetter + field.getName().substring(1);
                
                Method getMethod = cls.getMethod(getterName, new Class[]
                {});
                // 这个对象字段get方法的值
                Object value = getMethod.invoke(obj, new Object[]
                {});
                sql.append(" WHERE ").append(field.getName()).append("=");
                if (field.getType().getName().equals(java.lang.String.class.getName()))
                {
                    sql.append("'" + value + "'");
                }
                else
                {
                    sql.append(value);
                }
            }
            
        }
        
        System.out.println(sql.toString());
    }
    
    public void close()
    {
        System.out.println("SESSION CLOSE");
    }
}

 

 

简易框架模仿hibernate,运算后的结果如下:

 

posted on 2017-07-06 22:46  啊哈咧  阅读(4267)  评论(0编辑  收藏  举报