hibernate 模拟器
域模型:Student
packagecom.eagle.hibernate.model;
publicclassStudent{
privateintid;
privateStringname;
privateintage;
publicintgetId(){
returnid;
}
publicvoidsetId(intid){
this.id=id;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicintgetAge(){
returnage;
}
publicvoidsetAge(intage){
this.age=age;
}
}
测试类:StudentTest
importcom.eagle.hibernate.model.Student;
publicclassStudentTest{
publicstaticvoidmain(Stringargs[]){
Students=newStudent();
s.setId(8);
s.setName("student2");
s.setAge(18);
Sessionsession=newSession();
session.save(s);
}
}
实现功能类:Session
importjava.lang.reflect.InvocationTargetException;
importjava.lang.reflect.Method;
importjava.sql.Connection;
importjava.sql.PreparedStatement;
importjava.sql.DriverManager;
importjava.sql.SQLException;
importjava.util.HashMap;
importjava.util.Map;
importcom.eagle.hibernate.model.Student;
publicclassSession{
Stringtablename="_Student";//数据库表名
Map<String,String>cfs=newHashMap<String,String>();
String[]methodNames;
publicSession(){
cfs.put("_id","id");//key表示数据库字段,id表示student属性
cfs.put("_name","name");
cfs.put("_age","age");
methodNames=newString[cfs.size()];//存储get方法的名字
}
publicvoidsave(Students){
Stringsql=createSQL();
Connectionconn=null;
PreparedStatementpsmt=null;
try{
Class.forName("com.mysql.jdbc.Driver");
Stringurl="jdbc:mysql://localhost/hibernate?user=root&password=root";
conn=DriverManager.getConnection(url);
psmt=conn.prepareStatement(sql);
for(inti=0;i<methodNames.length;i++){
Methodm=s.getClass().getMethod(methodNames[i]);//获得student的get方法
Classr=m.getReturnType();//取得返回值类型的类
System.out.println(m.getName()+"|"+r.getName());
if(r.getName().equals("java.lang.String")){
StringreturnValue=(String)m.invoke(s);//m.invoke()表示执行m方法,此方法返回值存入returnValue
psmt.setString(i+1,returnValue);
}
if(r.getName().equals("int")){
IntegerreturnValue=(Integer)m.invoke(s);
psmt.setInt(i+1,returnValue);
}
}
psmt.executeUpdate();
}catch(ClassNotFoundExceptione){
e.printStackTrace();
}catch(SQLExceptione){
e.printStackTrace();
}catch(SecurityExceptione){
e.printStackTrace();
}catch(NoSuchMethodExceptione){
e.printStackTrace();
}catch(IllegalArgumentExceptione){
e.printStackTrace();
}catch(IllegalAccessExceptione){
e.printStackTrace();
}catch(InvocationTargetExceptione){
e.printStackTrace();
}finally{
try{
psmt.close();
conn.close();
}catch(SQLExceptione){
e.printStackTrace();
}
}
}
privateStringcreateSQL(){
Stringstr1="";//数据库字段
intindex=0;
for(Strings:cfs.keySet()){
Stringv=cfs.get(s);
v=Character.toUpperCase(v.charAt(0))+v.substring(1);
methodNames[index]="get"+v;//取得student属性的get方法名
str1+=s+",";
index++;
}
str1=str1.substring(0,str1.length()-1);
Stringstr2="";//sql语句未知参数
for(inti=0;i<cfs.size();i++){
str2+="?,";
}
str2=str2.substring(0,str2.length()-1);
Stringsql="insertinto"+tableName+"("+str1+")"+"values("+str2+")";
System.out.println(sql);
returnsql;
}
}