程序运行条件:MySQL数据库
请自行配置数据库信息,在session.java中进行配置。
本例子使用的数据库语句。
create database hibernate;
create table _student(_id int primary key, _name varchar(20), _age int);
文件结构:
两个包:com.test.model Student.java
com.test.testSession.java Test.java
Student.java
package com.test.model;
public class Student {
<span style="white-space:pre"> </span>//简单的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;
}
}
Session.java
package com.test.test;
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.test.model.Student;
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 {
// TODO Auto-generated method stub
String sql = createSQL();
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hibernate","root","zhaohui");
PreparedStatement ps = conn.prepareStatement(sql);
for(int i =0 ;i<methodNames.length;i++) {
Method m = s.getClass().getMethod( methodNames[i] );<span style="white-space:pre"> </span>//利用反射机制调用student的getXXX方法取得其值,然后使用ps对数据库进行赋值
Class r = m.getReturnType();<span style="white-space:pre"> </span>//这里用到了反射,不了解请自行百度。
System.out.println(m.getName() + "|" + r.getName() );
if( r.getName().equals("java.lang.String")){<span style="white-space:pre"> </span>//根据插入值类型的不同调用不同的set方法,如setString setInt
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 );
}
}
ps.executeUpdate();
ps.close();
conn.close();
}
private String createSQL() {
// 生成插入语句"insert into _student (_id,_name ,_age) values (?,?,?)"
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;
System.out.println("methodNames["+index +"]:"+methodNames[index]);
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.test.test;
import com.test.model.Student;
public class Test {
public static void main(String[] args) throws Exception {
Student s = new Student();
s.setId(3);
s.setAge(21);
s.setName("tom");
Session session = new Session();
session.save(s);
//session.close();
}
}
注意运行程序时不要忘了往程序中导入JDBC 的jar包
本例子出自马士兵Java视频中hibernate框架的片段