万能 dao 增删改查一个方法搞定

来源:互联网 发布:smtp服务端口 编辑:程序博客网 时间:2024/04/30 03:13
package heima.shawn.utils;import java.beans.Introspector;import java.beans.PropertyDescriptor;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.ArrayList;import java.util.List;public class BaseDao<T> {public Object opreatorObj(Class<T> tClazz, String sql, Object... params)throws Exception {Connection conn = null;PreparedStatement pst = null;ResultSet rs = null;try {List<T> list = new ArrayList<T>();conn = DBUtils.getInstance().getConnection();pst = conn.prepareStatement(sql);if (params != null) {for (int i = 1; i <= params.length; i++) {pst.setObject(i, params[i - 1]);}}if (pst.execute()) {rs = pst.getResultSet();while (rs.next()) {T t = resultSet2Bean(rs, tClazz);list.add(t);}return list;} else {int rows = pst.getUpdateCount();if (rows > 0)return true;return false;}} finally {DBUtils.getInstance().release(conn, pst, rs);}}public T resultSet2Bean(ResultSet rs, Class<T> clazz) throws Exception {T t = clazz.newInstance();PropertyDescriptor[] props = Introspector.getBeanInfo(clazz).getPropertyDescriptors();for (int i = 0; i < props.length; i++) {if (props[i].getName().equals("class"))continue;props[i].getWriteMethod().invoke(t,rs.getObject(props[i].getName()));}return t;}}


 

package heima.shawn.utils;import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Properties;import com.mysql.jdbc.Driver;public class DBUtils {private Properties prop = new Properties();private DBUtils() {try {prop.load(DBUtils.class.getClassLoader().getResourceAsStream("DB.properties"));} catch (IOException e) {throw new RuntimeException(e);}}private static DBUtils instance = new DBUtils();public static DBUtils getInstance() {return instance;}public Connection getConnection() {Connection conn = null;try {Class.forName(prop.getProperty("driver"));//Driver driver = new Driver();conn = DriverManager.getConnection(prop.getProperty("url"), prop.getProperty("user"), prop.getProperty("password"));} catch (Exception e) {throw new RuntimeException(e);}return conn;}public void release(Connection conn, Statement st, ResultSet rs) {if (rs != null)try {rs.close();} catch (SQLException e) {throw new RuntimeException(e);}if (st != null)try {st.close();} catch (SQLException e) {throw new RuntimeException(e);}if (conn != null)try {conn.close();} catch (SQLException e) {throw new RuntimeException(e);}}}


还能改进,,,但是已经觉得比hibernate好用了!!!你懂的·········

0
原创粉丝点击