Hibernate的ORM功能,简而言之就是用户传一个任意对象进去,然后系统自动生成相应的SQL语句并执行
因此,实现一个简易的ORM模块并不难,关键就在于对JAVA反射机制的使用和SQL语句的拼凑
基本思路是:
· 根据传入的Object来得到数据库的表名
· 得到属性名和对应的值
· 将所得信息进行整合,拼凑一条SQL语句
代码:
1. 定义两个测试用的POJO类(省略get和set方法)
public class UserInfo {
private int id;
private String userName;
private String userPwd;
private int userAge;
}
public class Article {
private int id;
private String title;
private String author;
private String content;
}
2. 然后写个数据库的连接静态类
import java.sql.Connection;
import java.sql.DriverManager;
public class DBConnector {
public static Connection conn;
public static boolean buildConn(){
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test";
conn = DriverManager.getConnection(url,"root","password");
return true;
}catch(Exception e){
e.printStackTrace();
}
return false;
}
}
3. 接下来是主体部分了
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import cn.netjava.dao.DBConnector;
import cn.netjava.pojo.Article;
import cn.netjava.pojo.UserInfo;
public class ORMmodel {
/**
* 插入数据
* @param obj 需要保存的对象
* @return 保存是否成功
*/
public boolean insert(Object obj){
String sql = "insert into ";
//得到表名
String tableName = obj.getClass().getName();
sql = sql + tableName.substring(tableName.lastIndexOf(".")+1) + "(";
//得到properties和values
Method[] methods = obj.getClass().getMethods();
ArrayList<String> properties = getProperties(methods);
ArrayList<Object> values = getValues(methods,obj);
//拼接sql语句
String sql1 = "";
String sql2 = ") value (";
for(int i=0;i<properties.size();i++){
String property = properties.get(i);
Object value = values.get(i);
if(property.equals("Id")){//插入时id属性不需要处理,跳过
continue;
}
sql1 += property + ",";
sql2 += "'" + value + "',";
}
sql += sql1.substring(0,sql1.length()-1) + sql2.substring(0,sql2.length()-1) + ")";
try{
Statement state = DBConnector.conn.createStatement();
state.executeUpdate(sql);
return true;
}catch(Exception e){
e.printStackTrace();
}
return false;
}
/**
* 删除对象
* @param obj
* @return
*/
public boolean delete(Object obj){
String sql = "delete from ";
//得到表名
String tableName = obj.getClass().getName();
sql = sql + tableName.substring(tableName.lastIndexOf(".")+1) + " where ";
//得到properties和values
Method[] methods = obj.getClass().getMethods();
ArrayList<String> properties = getProperties(methods);
ArrayList<Object> values = getValues(methods,obj);
//拼接sql语句
for(int i=0;i<properties.size();i++){
String property = properties.get(i);
Object value = values.get(i);
if(property!=null&&value!=null){
if(value instanceof Integer){ //如果属性类型为int而且
int a = ((Integer) value).intValue(); //没被赋值时,默认是0,所以
if(a==0){ //此处对值为值为0的属性不做
continue; //处理,跳过
} //(此处理只适用于不会出现值
} //为0的属性的对象,仅供测试)
sql += property + "='" + value.toString() + "' and ";
}
}
sql = sql.substring(0, sql.length()-5);
try{
Statement state = DBConnector.conn.createStatement();
state.executeUpdate(sql);
return true;
}catch(Exception e){
e.printStackTrace();
}
return false;
}
/**
* 修改对象
* @param obj
* @return
*/
public boolean update(Object obj){
String sql = "update ";
//得到表名
String tableName = obj.getClass().getName();
sql += tableName.substring(tableName.lastIndexOf(".")+1) + " set ";
//得到properties和values
Method[] methods = obj.getClass().getMethods();
ArrayList<String> properties = getProperties(methods);
ArrayList<Object> values = getValues(methods,obj);
//拼接sql语句
String id = null;
for(int i=0;i<properties.size();i++){
String property = properties.get(i);
Object value = values.get(i);
if(property.equals("Id")){
id = value.toString();
continue;
}
if(value instanceof Integer){
int a = ((Integer) value).intValue();
if(a==0){
continue;
}
}
sql += property + "='" + value.toString() + "',";
}
sql = sql.substring(0,sql.length()-1) + " where id='" + id + "'";
try{
Statement state = DBConnector.conn.createStatement();
state.executeUpdate(sql);
return true;
}catch(Exception e){
e.printStackTrace();
}
return false;
}
/**
* 查找所有包含指定属性的Object
* @param obj
* @return
*/
public ArrayList<Object> search(Object obj){
ArrayList<Object> list = new ArrayList<Object>();
String sql = "select * from ";
//得到表名
String tableName = obj.getClass().getName();
sql += tableName.substring(tableName.lastIndexOf(".")+1) + " where ";
//得到properties和values
Method[] methods = obj.getClass().getMethods();
ArrayList<String> properties = getProperties(methods);
ArrayList<Object> values = getValues(methods,obj);
//拼接sql语句
for(int i=0;i<properties.size();i++){
String property = properties.get(i);
Object value = values.get(i);
if(property!=null&&value!=null){
if(value instanceof Integer){
int a = ((Integer) value).intValue();
if(a==0){
continue;
}
}
sql += property + "='" + value.toString() + "' and ";
}
}
sql = sql.substring(0,sql.length()-5);
try{
Statement state = DBConnector.conn.createStatement();
ResultSet set = state.executeQuery(sql);
while(set.next()){
if(tableName.substring(tableName.lastIndexOf(".")+1).equals("UserInfo")){
UserInfo user = new UserInfo();
user.setUserAge(set.getInt("userage"));
user.setId(set.getInt("id"));
user.setUserName(set.getString("username"));
user.setUserPwd(set.getString("userpwd"));
list.add(user);
}
if(tableName.substring(tableName.lastIndexOf(".")+1).equals("Article")){
Article article = new Article();
article.setAuthor(set.getString("author"));
article.setId(set.getInt("id"));
article.setContent(set.getString("content"));
article.setTitle(set.getString("title"));
list.add(article);
}
}
return list;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
/**
* 根据方法名得到属性名的List
* @param methods
* @return
*/
private ArrayList<String> getProperties(Method[] methods){
ArrayList<String> properties = new ArrayList<String>();
for(Method m : methods){
String methodName = m.getName();
if(methodName.startsWith("get")&&!methodName.equals("getClass")){
String property = methodName.substring(3);
properties.add(property);
}
}
return properties;
}
/**
* 得到属性对应的value
* @param methods
* @param obj
* @return
*/
private ArrayList<Object> getValues(Method[] methods,Object obj){
ArrayList<Object> values = new ArrayList<Object>();
for(Method m : methods){
String methodName = m.getName();
if(methodName.startsWith("get")&&!methodName.equals("getClass")){
try{
Object value = m.invoke(obj, null);
values.add(value);
}catch(Exception e){
e.printStackTrace();
}
}
}
return values;
}
}
4. 最后再自己写个main函数测试下
特别说明:
·以上代码测试前需要准备好一个数据库并预先定义好userinfo和article表
·修改数据时id属性不能为0(未定义的话id也会默认为0滴)