模拟hibernate(反射+sql拼接)

来源:互联网 发布:淘宝华佗大药房旗舰店 编辑:程序博客网 时间:2024/05/29 04:28


Session.java

package com.wxh;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;import java.util.HashMap;import java.util.Map;public class Session {String tableName="_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) throws Exception{String sql=createSQL();Class.forName("com.mysql.jdbc.Driver");Connection conn=DriverManager.getConnection("jdbc:mysql://localhost/db_test","root","111");PreparedStatement psta=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);psta.setString(i+1, returnValue);}if(r.getName().equals("int")){Integer returnValue=(Integer)m.invoke(s);psta.setInt(i+1, returnValue);}System.out.println(m);}psta.executeUpdate();psta.close();conn.close();}private String createSQL() {String str1="";int index=0;for(String s:cfs.keySet()){String v=cfs.get(s);v=Character.toUpperCase(v.charAt(0))+v.substring(1);methodNames[index]="get"+v;str1+=s+",";index++;}str1=str1.substring(0,str1.length()-1);System.out.println(str1);String str2="";for(int i=0;i<cfs.size();i++){str2+="?,";}str2=str2.substring(0,str2.length()-1);System.out.println(str2);String sql="insert into "+tableName+"("+str1+")"+"values("+str2+")";System.out.println(sql);return sql;}}

Test.java

package com.wxh;public class Test {public static void main(String[] args) throws Exception {Student s=new Student();s.setId(2);s.setName("s2");s.setAge(2);Session session=new Session();session.save(s);}}

Student.java

package com.wxh;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;}}


0 0
原创粉丝点击