很久以前在看java反射的相关内容,但是运行来运行去,一直不明白输出和得到那些方法究竟有什么用。网上百度都说跟hibernate那些框架会用到,但是没有具体的例子很难明白。直到最近在学hibernate看到马士兵老师说的用java代码模拟简单的hibernate中save功能,他一说到jdbc中prepareStatement中是setInt还是setString我就明白了原来在这里用到了反射。话说不太清,直接看例子吧。
1.新建一个java项目
项目结构如图,当然你可以随意定。因为我们要模拟hibernate,我们就不需要导入hibernate的相关jar包,只需要jdbc的驱动包就行
2.新建一个Student实体类
package com.lin.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;
}
}
3.在mysql中新建对应的表
create table student(id int primary key,name varchar(20),age int);
4.新建一个测试类
import com.lin.hibernate.model.Student;
public class StudentTest {
public static void main(String[] args) throws Exception {
Student s1 = new Student();
s1.setId(1);
s1.setName("linjian");
s1.setAge(21);
Student s2 = new Student();
s2.setId(2);
s2.setName("linxiaobai");
s2.setAge(22);
Student s3 = new Student();
s3.setId(3);
s3.setName("xiaobai");
s3.setAge(23);
Session session = new Session();
session.save(s1);
session.save(s2);
session.save(s3);
}
}
我们主要是写其中的Session类的实现以及里面的save方法
5.下面开始实现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;
public class Session {
private String tableName = "student";
private Map<String,String> cfs = new HashMap<String, String>();
private String[] methodNames ;
public Session() {
cfs.put("id", "id");
cfs.put("name", "name");
cfs.put("age", "age");
methodNames = new String[cfs.size()];
}
public void save(Object o) throws Exception {
String SQL = createSQL();
String URL ="jdbc:mysql://localhost:3256/hibernate";
String USERNAME = "root";
String PASSWORD = "110110";
Class.forName("com.mysql.jdbc.Driver");//反射机制
Connection conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);
PreparedStatement ps = conn.prepareStatement(SQL);
Class classType = o.getClass();//反射机制
for(int i=0; i<methodNames.length;i++){
Method m = classType.getDeclaredMethod(methodNames[i]);//反射机制
Class returnType = m.getReturnType();//反射获取返回值类型
String name = returnType.getName();//获取返回值类型名,主要是用来判断ps是setInt还是String
if("int".equals(name)){
Integer value = (Integer) m.invoke(o);//反射去执行方法m并且返回值赋值给value
ps.setInt(i+1, value);
}
if("java.lang.String".equals(name)){
String value = (String) m.invoke(o);
ps.setString(i+1, value);
}
}
int result = ps.executeUpdate();
if(result>0){
System.out.println("插入成功");
}else{
System.out.println("插入失败");
}
ps.close();
conn.close();
}
private String createSQL() {
int index = 0;
String str1 = "";
String str2 = "";
for (String s : cfs.keySet()) {
String value = cfs.get(s);
value = "get"+Character.toUpperCase(value.charAt(0))+value.substring(1);
methodNames[index]=value;
str1 = str1+s+",";
str2 +="?,";
index++;
}
str1 = str1.substring(0,str1.length()-1);
str2 = str2.substring(0,str2.length()-1);
// System.out.println(str1);
// System.out.println(str2);
String sql = "insert into "+tableName+"("+str1+")"+" values("+str2+")";
return sql;
}
}
结果
save成功,简单的hibernate save功能实现完毕。