博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java反射生成ORM
阅读量:6281 次
发布时间:2019-06-22

本文共 4120 字,大约阅读时间需要 13 分钟。

package com.wzh.jdbc;

import java.lang.reflect.Field;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class JDBCTemplate<T> {

public boolean save(final T t) {

String simpleName = t.getClass().getSimpleName();
System.out.println("simpleName" + simpleName);
final StringBuffer sql = new StringBuffer();
final Field[] fields = t.getClass().getDeclaredFields();
sql.append("insert into tb_").append(simpleName).append("(")
.append(fields[0].getName());
for (int i = 1; i < fields.length; i++) {
sql.append(",").append(fields[i].getName());
}
sql.append(") values(?");
for (int i = 1; i < fields.length; i++) {
sql.append(",?");
}
sql.append(")");
System.out.println("SQL - >" + sql.toString());
return template(new Callback<Boolean>() {
@Override
public Boolean doInCallback(Connection conn,
PreparedStatement pstm, ResultSet rs) throws Throwable {
pstm = conn.prepareStatement(sql.toString());
int index = 1;
for (Field field : fields) {
if (!field.getName().equals("UserId")) {
if (!field.isAccessible())
field.setAccessible(true);

//取得字段的值

System.out.println("field get --> "+field.get(t));
pstm.setObject(index, field.get(t));
index++;
}
}
int row = pstm.executeUpdate();
return row != 0 ? true : false;
}
});
}

public boolean delete(Class clazz, final int id) {

String simpleName = clazz.getSimpleName();
System.out.println("simpleName" + simpleName);
final String sql = "delete from tb_" + simpleName + " where id=?";
System.out.println("SQL->" + sql);
return template(new Callback<Boolean>() {
@Override
public Boolean doInCallback(Connection conn,
PreparedStatement pstm, ResultSet rs) throws Throwable {
pstm = conn.prepareStatement(sql);
pstm.setObject(1, id);
int row = pstm.executeUpdate();
return row != 0 ? true : false;
}
});
}

public List<T> findAll(final Class clazz) {

String simpleName = clazz.getSimpleName();
System.out.println("simpleName->" + simpleName);
final StringBuffer sql = new StringBuffer();
// 构建SQL语句 select [所有字段] from tb_class.getName() where id=?
Field[] fields = clazz.getDeclaredFields();
sql.append("select ").append(fields[0].getName());
for (int i = 1; i < fields.length; i++) {
sql.append(",").append(fields[i].getName());
}
sql.append(" from tb_").append(simpleName);
System.out.println("SQL - >" + sql.toString());
return template(new Callback<List<T>>() {
@Override
public List<T> doInCallback(Connection conn,
PreparedStatement pstm, ResultSet rs) throws Throwable {
pstm = conn.prepareStatement(sql.toString());
rs = pstm.executeQuery();
// 返回集合对象
List list = new ArrayList();
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
while (rs.next()) {
Object object = clazz.newInstance();
// 要得到rs返回的所有字段和信息
for (int i = 1; i <= count; i++) {
// 循环拿到列名id
String column = rsmd.getColumnName(i);
Field f = clazz.getDeclaredField(column);
if (!f.isAccessible()) {
f.setAccessible(true);
}
f.set(object, rs.getObject(column));
}
list.add(object);
}
return list;
}
});
}

private Connection conn = null;

public JDBCTemplate() {

super();
conn = ConnectionFactory.GetConnection();
}

protected interface Callback<E> {

E doInCallback(Connection conn, PreparedStatement pstm, ResultSet rs)
throws Throwable;
}

protected <E> E template(Callback<E> callback) throws DataAccessException {

PreparedStatement pstm = null;
ResultSet rs = null;
try {
return callback.doInCallback(conn, pstm, rs);
} catch (Throwable e) {
throw new DataAccessException(e);
} finally {
ConnectionFactory.Close(pstm, rs);
}
}

/**

* 开启事务
* */
public void beginTransaction() {
try {
conn.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}

/**

* 提交事务
* */
public void commit() {
try {
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}

/**

* 回滚事务
* */
public void rollback() {
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}

/**

* 关闭连接
* */
public void close() {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

转载地址:http://iuxva.baihongyu.com/

你可能感兴趣的文章
spring batch中用到的表
查看>>
资源文件夹res/raw和assets的使用
查看>>
UINode扩展
查看>>
LINUX常用命令
查看>>
百度云盘demo
查看>>
概率论与数理统计习题
查看>>
初学structs2,简单配置
查看>>
Laravel5.0学习--01 入门
查看>>
时间戳解读
查看>>
sbin/hadoop-daemon.sh: line 165: /tmp/hadoop-hxsyl-journalnode.pid: Permission denied
查看>>
@RequestMapping 用法详解之地址映射
查看>>
254页PPT!这是一份写给NLP研究者的编程指南
查看>>
《Data Warehouse in Action》
查看>>
String 源码浅析(一)
查看>>
Spring Boot 最佳实践(三)模板引擎FreeMarker集成
查看>>
Fescar 发布 0.2.3 版本,支持 Redis 和 Apollo
查看>>
Google MapReduce到底解决什么问题?
查看>>
CCNP-6 OSPF试验2(BSCI)
查看>>
Excel 2013 全新的图表体验
查看>>
openstack 制作大于2TB根分区自动扩容的CENTOS镜像
查看>>