实现自己的Hibernate框架之Session 方法实现
<hibernate-configuration><session-factory><property name="dialect">org.hibernate.dialect.MySQLDialect</property><property name="connection.url">jdbc:mysql://localhost:3306/dir</property><property name="connection.username">root</property><property name="connection.password">sa</property><property name="connection.driver_class">com.mysql.jdbc.Driver</property><property name="myeclipse.connection.profile">mysql</property><mapping resource="bean/Student.hbm.xml" /></session-factory></hibernate-configuration>
<hibernate-mapping><class name="com.wsx.hibernate.Student" table="student"><id name="id" column="id" /><property name="name" column="name" /><property name="age" column="age" /></class></hibernate-mapping>?
Student stu = new Student();stu.setAge(19);stu.setName("fdg");stu.setId(1);Configuration con = new Configuration();SessionFactory sf = con.configure("/hibernate.cfg.xml").buildSessionFactory();Session session = sf.openSession();session.beginTransaction(); Serializable se=session.save(stu);System.out.println(se);session.getTransaction().commit();session.close();
package com.wsx.hibernate;import java.lang.reflect.Method;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.util.HashMap;import java.util.Map;import java.util.Set;public class Session { private String tableName="student"; private Map<String,String> map=new HashMap<String,String>(); private String[] methods=null; //创建语句类型; private static int save=0; private static int update=1; private static int delete=2; public Session (){ //key 值是表名 ,value是类属性 map.put("id", "id"); map.put("name", "name"); map.put("age", "age"); methods=new String[map.size()]; } public Connection getConn(){ Connection conn=null; try {Class.forName("com.mysql.jdbc.Driver");conn=conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/dir","root","sa");} catch (Exception e) {System.out.println("异常:"+e.getLocalizedMessage());}return conn; } /** * 用来向数据库里面添加内容的 * @param s student对象; * @throws Exception */ public void save(Student s) throws Exception{ String sql=create(Session.save); Connection conn=getConn(); java.sql.PreparedStatement ps= conn.prepareStatement(sql); int len=methods.length; for(int i=0;i<len;i++){ //根据方法名获取对应的方法; Method mo= s.getClass().getMethod(methods[i]); //获取方法的返回类型 Class c=mo.getReturnType(); //判断返回类型 if(c.getName().equals("java.lang.String")){ //根据不同的返回类型获取返回值。如果是void类型的话,那么返回类型为void。返回值为null String value=(String)mo.invoke(s); ps.setString(i+1,value); } if(c.getName().equals("int")){ Integer value=(Integer)mo.invoke(s); ps.setInt(i+1,value); } } ps.executeUpdate(); ps.close(); conn.close(); System.out.println("添加成功"); } private String create(int type) {//有几个属性。String str1="";//有几个待插入的位置String str2="";Set<String> set=map.keySet();int index=0;for(String s:set){str1+=s+",";str2+="? ,";//get方法方法名是属性名的首字母大写然后加上getString value=map.get(s);value=Character.toUpperCase(value.charAt(0))+value.substring(1,value.length());value="get"+value;//将方法名放入到方法数组里面methods[index++]=value;}//拼成的字符串最后面多了一个逗号。所以截取除了最后一个字符之外的其他字符str1=str1.substring(0,str1.length()-1);str2=str2.substring(0,str2.length()-1);System.out.println(str1+" "+str2);String sql=null; if(type==0){ //save sql="insert into "+tableName +" ("+str1+") values ("+str2+")"; }else if(type==1){ //update // sql="update "+tableName+" set name=? ,age=? where id=?"; }else if(type==2){//delete //sql="delete from "+tableName+" where id =?"; }return sql;} }
?
?? 这里用到了用到了动态反射的相关东西。通过方法名,来判断该方法的返回类型和返回值。
?
? 下面是测试类;
?
?
package com.wsx.hibernate;public class HibernateSave { public static void main(String[] args) {Student stu=new Student();stu.setId(4);stu.setName("wsx");stu.setAge(21);Session session=new Session();try {session.save(stu);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}?然后将会在数据库对应的表里面看到插入的数据。这里就是save方法的实现。!
?
?