public class Session {
QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
//执行sql语句
String sql = null;
//参数值
Object[] values = null;
//保存方法
public void save(Object obj){
//获取sql和参数值
buildSqlAndParam(obj);
try {
qr.update(sql,values);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
//insert into student(id,name,gender,age) values(?,?,?,?)
//构建sql语句
private void buildSqlAndParam(Object obj){
try {
List<Object> params = new ArrayList<Object>();
InputStream is = Session.class.getResourceAsStream("/gz/itcast/entity/Student.hbm.xml");
SAXReader reader = new SAXReader();
Document doc = reader.read(is);
String sql1 = "insert into ";
String sql2 = " values(";
Class clazz = obj.getClass();
String className= clazz.getName();
List<Element> list = doc.getRootElement().elements("class");
for(Element elem:list){
if(elem.attributeValue("name").equals(className)){
//表名
String tableName = elem.attributeValue("table");
sql1 += "student(";
//System.out.println(tableName);
List<Element> propElems = elem.elements("property");
for(Element propElem:propElems){
String columnName = propElem.attributeValue("column");
sql1 += columnName+",";
sql2 += "?,";
//取对象的值
String name = propElem.attributeValue("name");
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
params.add(field.get(obj));
}
sql1 = sql1.substring(0,sql1.length()-1);
sql2 = sql2.substring(0,sql2.length()-1);
sql1 += ")";
sql2 += ")";
}
}
System.out.println(sql1+sql2);
System.out.println(params);
//赋值
sql = sql1+sql2;
values = params.toArray();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}