📄 activerecord.java
字号:
package ActiveObject.core;import ActiveObject.common.Flag;import java.io.FileInputStream;import ActiveObject.exception.*;import ActiveObject.vo.Accesstor;import ActiveObject.vo.Command;import ActiveObject.vo.ObjectInfo;import ActiveObject.vo.TableType;import java.lang.reflect.InvocationTargetException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Properties;import java.util.logging.Level;import java.util.logging.Logger;/** * @author Administrator */public class ActiveRecord { /** * private static DataSource activeDataSource = null; */ static Map<String, ObjectInfo> objectInformationBase = new HashMap<String, ObjectInfo>(); private static String connectUrl = ""; private static String userName = ""; private static String password = ""; /** * 数据表中必须存在的关键字段 */ protected Object id = null; protected boolean isActive = false; /** * 保存一个持久化对象,无须指定id,若id已指定,则该方法等效于更新 * @throws java.sql.SQLException * @throws java.lang.Exception 此类异常可能是因为实现机制的问题而产生 */ public void save () throws SQLException, ObjectAnalysisException { ObjectInfo recordInfo = ActiveRecordHelper.analizeObjectInfo(this.getClass()); Accesstor[] accesstors = recordInfo.getAccesstor(); Accesstor[] ids = recordInfo.getIdentify(); Object[] params = new Object[accesstors.length+ids.length]; if(this.isActive == true) { String sql = recordInfo.getBasicSqlStatement().getUpdateStatement(); int index = 0; try { for(Accesstor accesstor : accesstors) { params[index++] = accesstor.invokeGetValue(this); } for(Accesstor accesstor : ids) { params[index++] = accesstor.invokeGetValue(this); } ActiveRecordHelper.excuteUpdate(sql, params); } catch(SQLException err) { throw err; } catch(Exception err) { throw new ObjectAnalysisException(err.toString(), err); } return; } String sql = recordInfo.getBasicSqlStatement().getInsertStatement(); int index = 0; try { for(Accesstor accesstor : ids) { params[index++] = accesstor.invokeGetValue(this); } for(Accesstor accesstor : accesstors) { params[index++] = accesstor.invokeGetValue(this); } } catch(Exception err) { throw new ObjectAnalysisException(err.toString(), err); } Connection connection = ActiveRecord.getConnection(); connection.setAutoCommit(false);//显式声明事物 PreparedStatement stmt = connection.prepareStatement(sql); index = 1; for(Object item : params) { stmt.setObject(index++, item); } index = stmt.executeUpdate(); Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("select last_insert_id() limit 0,1"); if(rs.next()) { try { ids[0].invokeSetValue(this, rs.getObject(1)); this.isActive = true; } catch(SQLException err){ throw err; } catch(Exception err) { new ObjectAnalysisException(err.toString(), err); } } else throw new SQLException("Failed to retrieve object's ID ."); connection.commit(); rs.close(); stmt.close(); connection.close(); } /** * 添加一个保存任务,加入批量链中。当批量操作执行后,该对象并不会成为持久化对象 * @param batch * @throws java.sql.SQLException * @throws activerecord.exception.ObjectAnalysisException */ public final void saveToTask(Task batch) throws SQLException, ObjectAnalysisException { try { batch.save(this); } catch(SQLException err) { throw err; } catch(Exception err) { if(err instanceof IllegalAccessException || err instanceof IllegalArgumentException) throw new ObjectAnalysisException(err.toString()); else if(err instanceof InvocationTargetException) throw new ObjectAnalysisException(err.toString(), err); } } /** * 添加一个更新任务,加入批量链中 * @param batch * @throws java.sql.SQLException * @throws activerecord.exception.ObjectAnalysisException */ public final void updateToTask(Task batch) throws SQLException, ObjectAnalysisException, ObjectNotActive { if(this.isActive == false) throw new ObjectNotActive(); try { batch.update(this); } catch(SQLException err) { throw err; } catch(Exception err) { throw new ObjectAnalysisException(err.toString(), err); } } /** * 读出一个持久化对象,必须指定id * @throws java.sql.SQLException * @throws activerecord.exception.ObjectNotExistException * @throws activerecord.exception.ObjectAnalysisException */ public void read () throws SQLException, ObjectNotExistException, ObjectAnalysisException { ObjectInfo recordInfo = ActiveRecordHelper.analizeObjectInfo(this.getClass()); Accesstor[] ids = recordInfo.getIdentify(); Object[] params = new Object[ids.length]; int index = 0; for(Accesstor item : ids) { try { params[index++] = item.invokeGetValue(this); } catch(Exception err) { throw new ObjectAnalysisException(err.toString(), err); } } ResultReader reader = ActiveRecordHelper.excuteQuery(recordInfo.getBasicSqlStatement().getSelectStatement(), params); if(reader.read()) { ActiveRecordHelper.setupObjectByResultSet(this, reader.getResultSet()); reader.close(); } else { reader.close(); throw new ObjectNotExistException(); } } /** * 当对象为持久性对象时,删除该对象;否则抛出异常 * @throws java.sql.SQLException * @throws activerecord.exception.LinkTypeNotFoundException * @throws activerecord.exception.ObjectAnalysisException */ public void delete () throws java.sql.SQLException, ObjectAnalysisException, ObjectNotActive { if(this.isActive == false) throw new ObjectNotActive(); ObjectInfo recordInfo = ActiveRecordHelper.analizeObjectInfo(this.getClass()); Accesstor[] ids = recordInfo.getIdentify(); Object[] params = new Object[ids.length]; int index = 0; for(Accesstor item : ids) { try { params[index++] = item.invokeGetValue(this); } catch(Exception err) { throw new ObjectAnalysisException(err.toString(), err); } } if(ActiveRecordHelper.excuteUpdate(recordInfo.getBasicSqlStatement().getDeleteStatement(), params) > 0) throw new SQLException("record of this id doesn't exist."); } /** * 添加一个删除任务,加入任务链中 * @param batch * @throws java.sql.SQLException * @throws activerecord.exception.ObjectAnalysisException * @throws activerecord.exception.ObjectNotActive */ public final void deleteToTask(Task batch) throws SQLException, ObjectAnalysisException, ObjectNotActive { try { batch.delete(this); } catch(ObjectNotActive err) { throw err; } catch(SQLException err) { throw err; } catch(Exception err) { throw new ObjectAnalysisException(err.toString(), err); } } /** * 更新方法,必须指定对象的id * @throws java.sql.SQLException, ObjectAnalysisException */ public void saveAsNew () throws java.sql.SQLException, ObjectAnalysisException { this.isActive = false; this.save(); } public static Batch createBatch() throws SQLException { return new Batch(ActiveRecord.getConnection()); } public static Transaction createTransaction() throws SQLException { return new Transaction(ActiveRecord.getConnection()); } public Query queryBy(String condition, Object... values) throws SQLException, ObjectAnalysisException, ArgumentFormatError { return ActiveRecord.query(new Object[]{this.getClass()}, condition, values); } public static final Query query(Object[] objectTypes, String condition, Object... values) throws SQLException, ObjectAnalysisException, ArgumentFormatError { return new Query(objectTypes, condition, values); } /** * 批量删除 * @param filter 过滤条件 * @throws java.sql.SQLException */ public Delete deleteBy (String condition, Object... values) throws java.sql.SQLException , ArgumentFormatError { return deleteAll(new Class[]{this.getClass()}, condition, values); } public static final Delete deleteAll(Class[] objectTypes, String condition, Object... values) throws java.sql.SQLException, ArgumentFormatError { return new Delete(objectTypes, condition, values); } public Update updateBy(String setting, String condition, Object... values) throws java.sql.SQLException, ArgumentFormatError { return update(new Class[]{this.getClass()}, setting, condition, values); } public static final Update update(Class[] objectTypes, String setting, String condition, Object... values) throws java.sql.SQLException, ArgumentFormatError { return new Update(objectTypes, setting, condition, values); } public static DataReader excuteReader (Filter filter) throws java.sql.SQLException { Command cmd = filter.createQueryCommand(); return excuteReader(filter.getTables(), cmd.getCommandSQL(), cmd.getCommandParams()); } public static DataReader excuteReader (List<TableType> tables, String sql, Object[] agrs) throws java.sql.SQLException { Connection connection = ActiveRecord.getConnection(); PreparedStatement stmt = connection.prepareStatement(sql);//System.err.println(sql); int index =1; for(Object value : agrs) { stmt.setObject(index++, value); } return new DataReader(connection, stmt, tables); } protected static Connection getConnection () throws java.sql.SQLException { return DriverManager.getConnection(ActiveRecord.connectUrl, ActiveRecord.userName, ActiveRecord.password); } public Object getId () { return this.id; } public void setId (Object id) { this.id = id; } static { java.util.Properties properties = new Properties(); try { properties.load(new FileInputStream("database.ini")); ActiveRecord.connectUrl = DataBaseProperty.getProperty(Flag.DataSource.ConnectUrlName);//properties.getProperty(Flag.DataSource.ConnectUrlName); ActiveRecord.userName = DataBaseProperty.getProperty(Flag.DataSource.UserName);//properties.getProperty(Flag.DataSource.UserName); ActiveRecord.password = DataBaseProperty.getProperty(Flag.DataSource.Password);//properties.getProperty(Flag.DataSource.Password); Class.forName("com.mysql.jdbc.Driver"); //Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(Exception err) { //找不到配置文件 Logger.getLogger(ActiveRecord.class.getName()).log(Level.SEVERE, err.toString(), err); } } public static void main(String... args) throws Exception { Class.forName("com.mysql.jdbc.Driver"); Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "root", "123"); PreparedStatement stmt = c.prepareStatement("select * from user where id = ? and name = ?");// stmt.setString(1, "1");// stmt.setString(2, "ruy"); ResultSet rs = stmt.executeQuery(); while(rs.next()) { System.out.println(rs.getString(1)+" "+rs.getString("name")); } long time = System.currentTimeMillis(); Connection conn = getConnection();// conn.setAutoCommit(false);// int rank = 1;// PreparedStatement stmt = conn.prepareStatement("insert into user values (rank,'name',?)");// for(int i=0;i<1000000;i++)// {// stmt.setObject(1,rank++);// stmt.addBatch();// }// stmt.executeBatch();// conn.commit();// System.out.println("time " +(System.currentTimeMillis()-time)); } /**// * 该方法已放弃// * @throws activerecord.exception.ObjectAnalysisException// * @throws java.sql.SQLException// */// public void update_deleted() throws ObjectAnalysisException, SQLException// {// String sql = ActiveRecordHelper.analizeObjectSqlStatement(this).getUpdateStatement();// Map<Field, Accesstor> fields = ActiveRecordHelper.analizeObjectFields(this);//// int index = 0;// Object[] params = new Object[fields.size()];// try// {// for(Field field : fields.keySet())// {// params[index++] = fields.get(field).invokeGetValue(this);//.getGetter().invoke(this);// }//// ActiveRecordHelper.excuteUpdate(sql, params);// }// catch(SQLException err)// {// throw err;// }// catch(Exception err)// {// if(err instanceof IllegalAccessException || err instanceof IllegalArgumentException)// throw new ObjectAnalysisException(err.toString());// else if(err instanceof InvocationTargetException)// throw new ObjectAnalysisException(err.toString(), err);// }// }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -