hibernate模拟(转载)
package simulation; /** * * @author Administrator * */ public class User { private int id; private String username; private String pwd; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } }
package simulation; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.DriverManager; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import com.mysql.jdbc.PreparedStatement; public class Session { private String table="user"; private Map<String, String> params=new HashMap<String, String>(); //装入方法名的容器 String [] methodName; public Session() { //模拟配置文件 key为属性 value为数据列 params.put("id", "_id"); params.put("pwd", "_pwd"); params.put("username", "_username"); methodName=new String[params.size()]; } public void save(User user){ String sql = creatSQL(); System.out.println(sql); //数据库操作 try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hibernate","root","123456"); PreparedStatement state = (PreparedStatement) con.prepareStatement(sql); //为占位符设值 for (int i = 0; i < methodName.length; i++) { //反射取值 Method method = user.getClass().getMethod(methodName[i]); Class<?> clazz = method.getReturnType(); if (clazz.getName().equals("java.lang.String")) { state.setString(i+1, (String) method.invoke(user)); } if (clazz.getName().equals("int")) { state.setInt(i+1, (Integer) method.invoke(user)); } System.out.println(method.getName()+":"+method.getReturnType()); } state.executeUpdate(); state.close(); con.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String creatSQL() { String parameters=""; String values=""; int index=0; //拼接属性字符串和值字符串 for (String key: params.keySet()) { // System.out.println(key); parameters+=params.get(key)+","; String v="get"+Character.toUpperCase(key.charAt(0))+key.substring(1); // System.out.println(methodName.length); methodName[index]=v; index++; } parameters=parameters.substring(0,parameters.length()-1); System.out.println(Arrays.toString(methodName)); for (int i = 0; i < params.size(); i++) { values+="?,"; } values=values.substring(0,values.length()-1); String sql="insert into "+table+"("+parameters+") values ("+values+")"; return sql; } }
package simulation; public class HibernateTest { public static void main(String[] args) { User user=new User(); user.setId(1); user.setPwd("123456"); user.setUsername("a"); Session session=new Session(); session.save(user); } }
posted on 2018-07-21 00:54 Danial7777777 阅读(126) 评论(0) 编辑 收藏 举报