标签:style blog http io color ar os sp java
Session:
import java.lang.reflect.Method; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.util.HashMap; import java.util.Map; import com.bjsxt.hibernate.model.Student; public class Session { String tableName = "_Student"; Map<String, String> cfs = new HashMap<String, String>(); String[] methodNames;// 用于存入实体类中的get方法数组 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();// 创建SQL串 Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection( "jdbc:mysql://xxx:3306/xxx?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull", "xxx", "xxx"); PreparedStatement ps = conn.prepareStatement(sql); for (int i = 0; i < methodNames.length; i++) { Method m = s.getClass().getMethod(methodNames[i]);// 返回一个 Method // 对象,它反映此 Class // 对象所表示的类或接口的指定公共成员方法 Class r = m.getReturnType();// 返回一个 Class 对象,该对象描述了此 Method // 对象所表示的方法的正式返回类型 if (r.getName().equals("java.lang.String")) { // 对带有指定参数的指定对象调用由此 Method 对象表示的底层方法。 // 个别参数被自动解包,以便与基本形参相匹配,基本参数和引用参数都随需服从方法调用转换 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); } if (r.getName().equals("java.lang.String")) { String returnValue = (String) m.invoke(s); ps.setString(i + 1, returnValue); } System.out.println(m.getName() + "|" + r.getName()); } ps.executeUpdate(); ps.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;// 拼实体类成员属性的getter方法 str1 += s + ",";// 根据表中字段名拼成字段串 index++; } str1 = str1.substring(0, str1.length() - 1); String str2 = ""; // 根据表中字段数,拼成?串 for (int i = 0; i < cfs.size(); i++) { str2 += "?,"; } str2 = str2.substring(0, str2.length() - 1); String sql = "insert into " + tableName + "(" + str1 + ")" + " values (" + str2 + ")"; System.out.println(sql); return sql; } }
Student:
package com.bjsxt.hibernate.model; 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; } }
StudentTest:
import com.bjsxt.hibernate.model.Student; public class StudentTest { public static void main(String[] args) throws Exception { Student s = new Student(); s.setName("xx"); s.setAge(2); s.setId(2); Session session = new Session(); session.save(s); } }
标签:style blog http io color ar os sp java
原文地址:http://www.cnblogs.com/super-d2/p/4102759.html