您的位置:首页 > 其它

简单模拟hibernate的实现原理

2013-12-17 14:22 507 查看

1、文件目录(仅需导mysql的驱动包)

2、具体代码,以目录所示顺序

StudentTest 类:

import com.lw.hibernate_simulation.Session;

import com.lw.hibernate_simulation.Student;

public class StudentTest {

public static void main(String[] args) {

Student student = new Student();

student.setId(1);

student.setAge(23);

student.setName("simulation");

Session session = new Session();

session.save(student);

}

}

Session 类:

package com.lw.hibernate_simulation;

import java.lang.reflect.Method;

import java.sql.*;

import java.util.HashMap;

import java.util.Map;

public class Session {

String tblName = "_student";

Map<String,String> cfs = new HashMap<String, String>(); 

String methodNames[];

public Session(){

cfs.put("_id","id" );

cfs.put("_name", "name");

cfs.put("_age", "age");

methodNames = new String[cfs.size()];

}

public void save(Student s) {

String sql = createSQL();

System.out.println(sql);

try {

Class.forName("com.mysql.jdbc.Driver");

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hibernate", "root", "root");

PreparedStatement ps = conn.prepareStatement(sql);

for(int i=0; i<methodNames.length; i++){

Method m = s.getClass().getMethod(methodNames[i]);

Class r = m.getReturnType();

if(r.getName().equals("java.lang.String")){

String returnValue = (String)m.invoke(s);

ps.setString(i+1, returnValue);

}

if(r.getName().equals("int")){

Integer returnValue = (Integer)m.invoke(s);

ps.setInt(i+1, returnValue);

}

//System.out.println(m.getName()+"---"+m.getReturnType());

}

ps.executeUpdate();

ps.close();

conn.close();

} catch (Exception e) {

e.printStackTrace();

}

}

private String createSQL() {

String str1 = "";

int index =0;

for(String s: cfs.keySet()){

String name = cfs.get(s);

name = Character.toUpperCase(name.charAt(0))+name.substring(1);

methodNames[index] = "get"+name;

str1 += s+",";

index++;

}

str1 = str1.substring(0, str1.length()-1);

String str2 = "";

for(int i =0; i<cfs.size(); i++){

str2 = str2+ "?,";

}

str2 = str2.substring(0, str2.length()-1);

String sql = "";

sql = "insert into "+tblName+" ("+str1+") " +"values ("+str2+")";

return sql;

}

}

Student 类:

package com.lw.hibernate_simulation;

public class Student {

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;

}

}

OK,收工!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hibernate 简单模拟