ibatis源码学习(五)缓存设计和实现

   缓存不算是ibatis框架的一个亮点,但理解ibatis的缓存设计和实现对我们合理使用ibatis缓存是很有帮助的。本文将深入分析ibatis框架的缓存设计和实现。缓存的使用参见官方文档:Cache Models。本文使用的ibatis版本为2.3.4。 

问题 
在介绍ibatis缓存设计和实现之前,我们先思考几个问题。 
1. 缓存的目标是什么? 缓存中存放哪些数据? 
2. 缓存数据的生命周期是怎样? 何时创建? 何时更新? 何时清理? 
3. 缓存数据的作用域是怎样? Session? 应用范围? 
4. 有哪些缓存管理策略? 如何加载策略配置? 如何使用这些策略? 
5. 缓存key的生成由哪些因素决定?
 
如果你能轻松回答上面这些问题,恭喜,你没有继续看下去的必要了 ,本文将围绕这些问题分析ibatis缓存的设计和实现。 

核心类图 
缓存相关的核心如下: 

1. CacheModel 
ibatis缓存的核心类,代表一个缓存对象,内部包含该缓存的配置信息(刷新间隔、缓存管理策略等)。该类和配置文件中的<cacheModel>标签对应。每个CacheModel内部组合一个CacheController对象,用于维护缓存数据。 

2. CacheController 
该接口表示采用某种策略的缓存管理者,缓存数据实际维护在CacheController实现类中。ibatis框架默认提供了四种缓存管理策略:MemoryCacheController提供了基于reference类型的管理策略;FifoCacheController提供了"先进先出"方式的管理策略;LruCacheController提供了"近期最少使用"的管理策略;OSCacheController提供了基于OSCache2.0缓存的管理策略。每种策略的实现方式将在下文介绍。 

3. ExecuteListener 
该接口表示一个观察者,它的唯一实现类是CacheModel。将该观察者注册到某个MappedStatement对象中,目的是当MappedStatement执行时,通知ExecuteListener执行相应操作(清除缓存对象)。该接口用于实现<flushOnExecute>这个功能。 

4. MappedStatement 
该类表示sql语句信息和执行时相关上下文环境。其内部包含List属性executeListeners,表示在sql执行后需要通知的观察者列表。 

5. CachingStatement 
该类是MappedStatement的包装类,用于sql执行时增加缓存功能。在配置文件中指定cacheModel属性的sql statement初始化时都会被包装成该对象。 

示例 
下面以常见的ibaits缓存配置举例,说明缓存的实现过程。 

Java代码   收藏代码
  1. <cacheModel id="CATEGORY-CACHE" type="Memory" serialize="false" readOnly="true">  
  2.     <property name="reference-type" value="WEAK" />  
  3.     <flushInterval minutes="15" />  
  4.     <flushOnExecute statement="MS-UPDATE-CATEGORY" />  
  5. </cacheModel>  
  6.   
  7. <select id="MS-FIND-SUB-CATEGORY" resultMap="RM-PF-PIC-CATEGORY"  
  8.     parameterClass="java.lang.Integer"  cacheModel="CATEGORY-CACHE">  
  9.     select id,cat_name,parent_id,is_leaf,prohibit_flag   
  10.     from PF_PIC_CATEGORY  
  11.     where parent_id=#parentId#  
  12. </select>  
  13.   
  14. <update id="MS-UPDATE-CATEGORY" parameterClass="TA-PF-PIC-CATEGORY">  
  15.     update PF_PIC_CATEGORY   
  16.     set cat_name=#catName#,gmt_modified=now()  
  17.     where id=#id#  
  18. </update>  

上述配置文件作用如下: 为MS-FIND-SUB-CATEGORY这条语句定义了名为CATEGORY-CACHE的Cache对象,采用基于内存(reference类型为弱引用)的缓存管理策略,缓存默认刷新时间为15min; 当执行MS-UPDATE-CATEGORY语句时,清除CATEGORY-CACHE缓存对象。 

初始化过程  
缓存初始化的主要过程有以下三点: 
1. 解析cacheModel配置,生成cacheModel对象。 该功能由SqlMapParser完成(初始化和配置文件解析参见 该文 ),部分源码如下: 
Java代码   收藏代码
  1. public class SqlMapParser {  
  2.   private void addCacheModelNodelets() {  
  3.     parser.addNodelet("/sqlMap/cacheModel"new Nodelet() {  
  4.       public void process(Node node) throws Exception {  
  5.         Properties attributes = NodeletUtils.parseAttributes(node, state.getGlobalProps());  
  6.         //解析各属性值  
  7.         String id = state.applyNamespace(attributes.getProperty("id"));  
  8.         String type = attributes.getProperty("type");  
  9.         String readOnlyAttr = attributes.getProperty("readOnly");  
  10.         Boolean readOnly = readOnlyAttr == null || readOnlyAttr.length() <= 0 ? null : new Boolean("true".equals(readOnlyAttr));  
  11.         String serializeAttr = attributes.getProperty("serialize");  
  12.         ...  
  13.         // 生成CacheModelConfig对象  
  14.         CacheModelConfig cacheConfig = state.getConfig().newCacheModelConfig(id, (CacheController) Resources.instantiate(clazz), readOnly.booleanValue(), serialize.booleanValue());  
  15.         state.setCacheConfig(cacheConfig);  
  16.       }  
  17.     });  
  18.     ...   
  19.   }  
  20. }  

上面的addCacheModelNodelets()方法目标是解析缓存相关配置信息,生成CacheModelConfig对象,CacheModelConfig构造过程中会生成cacheModel对象,最终cacheModel对象统一维护在SqlMapExecutorDelegate.cacheModels这个map属性中。 

2. 为配置cacheModel属性的sql语句生成CachingStatement对象。 该过程在SqlStatementParser中完成,部分源码如下: 
Java代码   收藏代码
  1. public class SqlStatementParser {  
  2.   public void parseGeneralStatement(Node node, MappedStatement statement) {  
  3.     ...  
  4.     String cacheModelName = state.applyNamespace(attributes.getProperty("cacheModel"));  
  5.     ...  
  6.     //下面这段代码在MappedStatementConfig的构造方法中,这里为了方便说明  
  7.     if (cacheModelName != null && cacheModelName.length() > 0 && client.getDelegate().isCacheModelsEnabled()) {  
  8.       //获取上面生成的cacheModel对象  
  9.       CacheModel cacheModel = client.getDelegate().getCacheModel(cacheModelName);  
  10.       //生成包装者对象  
  11.       mappedStatement = new CachingStatement(statement, cacheModel);  
  12.     } else {  
  13.       mappedStatement = statement;  
  14.     }  
  15.     ...  
  16.   }  
  17. }  


3. 将cacheModel这个观察者注册到其flushOnExecute属性对应的statement中 ,目的是statement执行后可以通知cacheModel清除缓存。 该过程由SqlMapConfigParser.addSqlMapConfigNodelets()方法实现,最终调用SqlMapConfiguration.wireUpCacheModels()方法。部分源码如下: 
Java代码   收藏代码
  1. public class SqlMapConfiguration{  
  2.   private void wireUpCacheModels() {  
  3.     // 循环处理每一个cacheModel  
  4.     Iterator cacheNames = client.getDelegate().getCacheModelNames();  
  5.     while (cacheNames.hasNext()) {  
  6.       String cacheName = (String) cacheNames.next();  
  7.       CacheModel cacheModel = client.getDelegate().getCacheModel(cacheName);  
  8.       //获取cacheModel对应的flushTriggerStatement,由<flushOnExecute>配置  
  9.       Iterator statementNames = cacheModel.getFlushTriggerStatementNames();  
  10.       while (statementNames.hasNext()) {  
  11.         String statementName = (String) statementNames.next();  
  12.         MappedStatement statement = client.getDelegate().getMappedStatement(statementName);  
  13.         if (statement != null) {  
  14.           //注册观察者  
  15.           statement.addExecuteListener(cacheModel);  
  16.         } else {  
  17.           throw new RuntimeException("Could not find statement named '" + statementName + "' for use as a flush trigger for the cache model named '" + cacheName + "'.");  
  18.         }  
  19.       }  
  20.     ...  
  21.     }  
  22.   }  
  23. }  


SQL执行过程  
已配置缓存的sql语句执行时,统一交由CachingStatement处理(sql完整执行过程参见 该文 ),下面以单个对象查询为例,通过源码说明使用缓存后的SQL执行过程。 

1. CachingStatement.executeQueryForObject()方法用于处理单个对象的查询请求,部分源码如下: 
Java代码   收藏代码
  1. public Object executeQueryForObject(StatementScope statementScope, Transaction trans, Object parameterObject, Object resultObject)  
  2.     throws SQLException {  
  3.   //获取CacheKey  
  4.   CacheKey cacheKey = getCacheKey(statementScope, parameterObject);  
  5.   cacheKey.update("executeQueryForObject");  
  6.   //根据cacheKey查询缓存value  
  7.   Object object = cacheModel.getObject(cacheKey);  
  8.   if (object == CacheModel.NULL_OBJECT){  
  9.     //已缓存,值为null  
  10.     object = null;  
  11.   }else if (object == null) {  
  12.       //没有缓存,通过组合的statement查询  
  13.      object = statement.executeQueryForObject(statementScope, trans, parameterObject, resultObject);  
  14.      //将查询结果放入缓存中  
  15.      cacheModel.putObject(cacheKey, object);  
  16.   }  
  17.   return object;  
  18. }  

上面的查询过程中,核心逻辑如下: 
1. 根据参数对象生成cacheKey(该过程稍后再详细说明); 
2. 根据cacheKey从cacheModel中获取对应的缓存value。 
2.1 如果为null,则通过组合的statement查询,并将查询结果放入缓存中。 
2.2 如果不为null,则直接返回缓存value。 
可以看出,缓存的查询和更新都是交由cacheModel对象完成,下面看一下cacheModel的查询和更新实现。 

2. 通过cacheModel查询缓存的部分源码如下: 
Java代码   收藏代码
  1. public Object getObject(CacheKey key) {  
  2.     Object value = null;  
  3.   synchronized (this) {  
  4.     // 判断缓存对象有没有过期,如果过期则清除  
  5.     if (flushInterval != NO_FLUSH_INTERVAL  
  6.         && System.currentTimeMillis() - lastFlush > flushInterval) {  
  7.       flush();  
  8.     }  
  9.   
  10.     // 通过controller查询缓存value  
  11.     value = controller.getObject(this, key);  
  12.     // 如果设置readOnly=false, serialize=true,需要反序列化缓存value  
  13.     if (serialize && !readOnly &&  
  14.             (value != NULL_OBJECT && value != null)) {  
  15.       try {  
  16.         ByteArrayInputStream bis = new ByteArrayInputStream((byte[]) value);  
  17.         ObjectInputStream ois = new ObjectInputStream(bis);  
  18.         value = ois.readObject();  
  19.         ois.close();  
  20.       } catch (Exception e) {  
  21.         ...  
  22.       }  
  23.     }  
  24.     ...  
  25.   return value;  
  26. }  

首先根据配置的flushInterval值判断缓存value有没有过期,如果过期则清除缓存;接着从controller中获取缓存value;如果存储的value是经过序列化的,这里需要再反序列化。 

3. 通过cacheModel更新缓存的部分源码如下: 
Java代码   收藏代码
  1. public void putObject(CacheKey key, Object value) {  
  2.     if (null == value) value = NULL_OBJECT;  
  3.     synchronized ( this )  {  
  4.     // 如果设置readOnly=false, serialize=true,需要序列化缓存value  
  5.     if (serialize && !readOnly && value != NULL_OBJECT) {  
  6.       try {  
  7.         ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  8.         ObjectOutputStream oos = new ObjectOutputStream(bos);  
  9.         oos.writeObject(value);  
  10.         oos.flush();  
  11.         oos.close();  
  12.         value = bos.toByteArray();  
  13.       } catch (IOException e) {  
  14.         ...  
  15.       }  
  16.     }  
  17.     // 通过controller更新缓存  
  18.     controller.putObject(this, key, value);  
  19.     ...  
  20.   }  
  21. }   

cacheModel更新缓存时,先判断缓存value是否需要序列化,如果需要则执行序列化操作;最后通过controller更新缓存value。 

小结  
从上面的查询过程可以看出,ibatis缓存查询和更新都是交由cacheModel完成,cacheModel承担缓存管理者的角色,如判断缓存是否过期等;最终统一交由controller完成。 

缓存管理策略  
在上文的核心类图说明时,我们提到了ibatis默认有四种缓存管理策略,下面分别看一下这四个controller的实现。 
1. MemoryCacheController  
Java代码   收藏代码
  1. public class MemoryCacheController implements CacheController {  
  2.   private MemoryCacheLevel cacheLevel = MemoryCacheLevel.WEAK;  
  3.   private Map cache = Collections.synchronizedMap(new HashMap());  
  4.   
  5.   public void putObject(CacheModel cacheModel, Object key, Object value) {  
  6.     Object reference = null;  
  7.     //弱引用  
  8.     if (cacheLevel.equals(MemoryCacheLevel.WEAK)) {  
  9.       reference = new WeakReference(value);  
  10.     //软应用  
  11.     } else if (cacheLevel.equals(MemoryCacheLevel.SOFT)) {  
  12.       reference = new SoftReference(value);  
  13.     //强引用  
  14.     } else if (cacheLevel.equals(MemoryCacheLevel.STRONG)) {  
  15.       reference = new StrongReference(value);  
  16.     }  
  17.     cache.put(key, reference);  
  18.   }  
  19.   
  20.   public Object getObject(CacheModel cacheModel, Object key) {  
  21.     Object value = null;  
  22.     Object ref = cache.get(key);  
  23.     if (ref != null) {  
  24.       if (ref instanceof StrongReference) {  
  25.         value = ((StrongReference) ref).get();  
  26.       } else if (ref instanceof SoftReference) {  
  27.         value = ((SoftReference) ref).get();  
  28.       } else if (ref instanceof WeakReference) {  
  29.         value = ((WeakReference) ref).get();  
  30.       }  
  31.     }  
  32.     return value;  
  33.   }  
  34. }  

MemoryCacheController使用reference类型来管理cache行为,垃圾收集器可以通过配置的reference类型(强引用、弱应用、软应用)判断是否要回收cache中的数据。 

2. FifoCacheController  
Java代码   收藏代码
  1. public class FifoCacheController implements CacheController {  
  2.   private int cacheSize;  // 缓存大小  
  3.   private Map cache;   // 缓存实际存储对象  
  4.   private List keyList;  //链表,用于控制key顺序  
  5.   
  6.   public void putObject(CacheModel cacheModel, Object key, Object value) {  
  7.     cache.put(key, value);  
  8.     keyList.add(key);  
  9.     // 超过缓存最大值的处理策略  
  10.     if (keyList.size() > cacheSize) {  
  11.       try {  
  12.         //清除最先进来的key  
  13.         Object oldestKey = keyList.remove(0);  
  14.         cache.remove(oldestKey);  
  15.       } catch (IndexOutOfBoundsException e) {  
  16.         ...  
  17.       }  
  18.     }  
  19.   }  
  20.   
  21.   public Object getObject(CacheModel cacheModel, Object key) {  
  22.     return cache.get(key);  
  23.   }  
  24. }  

FifoCacheController使用先进先出的缓存管理策略,通过内部维护的链表控制key的先后顺序。当缓存超出预定大小后,清除链表头部元素对应的value。 

3. LruCacheController  
Java代码   收藏代码
  1. public class LruCacheController implements CacheController {  
  2.   private int cacheSize;  // 缓存大小  
  3.   private Map cache;   // 缓存实际存储对象  
  4.   private List keyList;  //链表,用于控制key顺序  
  5.   public void putObject(CacheModel cacheModel, Object key, Object value) {  
  6.     cache.put(key, value);  
  7.     keyList.add(key);  
  8.     if (keyList.size() > cacheSize) {  
  9.       try {  
  10.         Object oldestKey = keyList.remove(0);  
  11.         cache.remove(oldestKey);  
  12.       } catch (IndexOutOfBoundsException e) {  
  13.         //ignore  
  14.       }  
  15.     }  
  16.   }  
  17.   
  18.   public Object getObject(CacheModel cacheModel, Object key) {  
  19.     Object result = cache.get(key);  
  20.     // 每次查询后,将key移到List的尾部  
  21.     keyList.remove(key);  
  22.     if (result != null) {  
  23.       keyList.add(key);  
  24.     }  
  25.     return result;  
  26.   }  
  27. }  

LruCacheController采用近期最少使用的缓存管理策略,实现上和FifoCacheController类似,唯一的差别是查询时将当前key移到keyList的尾部,保证经常查询的key都在链表的尾部,最少使用的key都在链表的头部。 当缓存超出预定大小后,直接清除链表头部元素对应的value即可。 

4. OSCacheController  
Java代码   收藏代码
  1. public class OSCacheController implements CacheController {  
  2.   private static final GeneralCacheAdministrator CACHE = new GeneralCacheAdministrator();  
  3.   public Object getObject(CacheModel cacheModel, Object key) {  
  4.     String keyString = key.toString();  
  5.     try {  
  6.       int refreshPeriod = (int) (cacheModel.getFlushIntervalSeconds());  
  7.       return CACHE.getFromCache(keyString, refreshPeriod);  
  8.     } catch (NeedsRefreshException e) {  
  9.       CACHE.cancelUpdate(keyString);  
  10.       return null;  
  11.     }  
  12.   }  
  13.     
  14.   public void putObject(CacheModel cacheModel, Object key, Object object) {  
  15.     String keyString = key.toString();  
  16.     CACHE.putInCache(keyString, object, new String[]{cacheModel.getId()});  
  17.   }  
  18. }  

OSCacheController采用OSCache2.0管理缓存,这里只是OSCache2.0缓存引擎的一个Plugin。我们可以借鉴OSCacheController的实现方式,实现自定义缓存实现,实现方式可以参考:  ibatis-with-memcached 。 

cacheKey生成策略  
上文的SQL执行过程中,查询缓存时首先需要根据参数对象生成cacheKey,再根据cacheKey在缓存中查找。核心实现源码如下: 
Java代码   收藏代码
  1. public CacheKey getCacheKey(StatementScope statementScope, Object parameterObject) {  
  2.   //生成CacheKey  
  3.   CacheKey key = statement.getCacheKey(statementScope, parameterObject);  
  4.   if (!cacheModel.isReadOnly() && !cacheModel.isSerialize()) {  
  5.     //更新CacheKey  
  6.     key.update(statementScope.getSession());  
  7.   }  
  8.   return key;  
  9. }  

其中MappedStatement.getCacheKey()实现如下: 
Java代码   收藏代码
  1. public CacheKey getCacheKey(StatementScope statementScope, Object parameterObject) {  
  2.   Sql sql = statementScope.getSql();  
  3.   ParameterMap pmap = sql.getParameterMap(statementScope, parameterObject);  
  4.   CacheKey cacheKey = pmap.getCacheKey(statementScope, parameterObject);  
  5.   cacheKey.update(id);  
  6.   cacheKey.update(baseCacheKey);  
  7.   cacheKey.update(sql.getSql(statementScope, parameterObject));  
  8.   return cacheKey;  
  9. }  

从上面过程可以看出,cacheKey的生成由以下几个元素决定: 
1) 参与参数映射的参数值 
2) statement id 
3) baseCacheKey 
4) sql语句 
5) 执行方法名称 
当设置缓存类型为读写缓存且未序列化时,session值也参与cacheKey的生成。 
从cacheKey的生成策略可以看出,当缓存类型是只读时,缓存数据在应用范围内共享;当缓存类型为读写缓存且未序列化时,缓存数据的作用域下降到session范围,要尽量避免这种情况发生。 

总结  
从设计上看,ibatis缓存设计主要涉及以下三种模式: 
策略模式:  默认提供四种不同的缓存管理策略,可以通过配置文件指定使用的策略,查询缓存时由CacheModel调用对应策略的Controller。 
观察者模式:  该模式主要针对配置<flushOnExecute>的缓存清除。在初始化时向目标statement注册观察者;当statement执行完毕后,会通知观察者清除缓存。 
包装者模式:  CachingStatement通过包装MappedStatement对象,增加缓存实现,实现功能增强。 

从ibatis缓存设计上看,如果sql传入的参数变化很多,或结果集数据量非常庞大,不适合使用ibatis缓存,可以考虑使用其他分布式缓存替代;对于参数比较稳定,结果集比较小的场景,可以考虑使用ibatis缓存,配置和使用上简洁方便。 

http://learnworld.iteye.com/blog/1478203

File: Account.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd"> <sqlMap namespace="Account"> <typeAlias alias="Account" type="Account"/> <resultMap id="AccountResult" class="Account"> <result property="id" column="ACC_ID"/> <result property="firstName" column="ACC_FIRST_NAME"/> <result property="lastName" column="ACC_LAST_NAME"/> <result property="emailAddress" column="ACC_EMAIL"/> </resultMap> <cacheModel id="categoryCache" type="LRU"> <flushInterval hours="24"/> <property name="size" value="100"/> </cacheModel> <select id="getByLike" resultClass="Account" parameterClass="Account" cacheModel="categoryCache"> select ACC_ID as id, ACC_FIRST_NAME as firstName, ACC_LAST_NAME as lastName, ACC_EMAIL as emailAddress from ACCOUNT where ACC_EMAIL = #emailAddress# and ACC_LAST_NAME = #lastName# </select> <!-- Insert example, using the Account parameter class --> <insert id="insertAccount" parameterClass="Account"> insert into ACCOUNT ( ACC_ID, ACC_FIRST_NAME, ACC_LAST_NAME, ACC_EMAIL )values ( #id#, #firstName#, #lastName#, #emailAddress# ) </insert> </sqlMap> File: Main.java import java.util.List; import com.ibatis.sqlmap.client.SqlMapClient; public class Main { public static void main(String[] a) throws Exception { Util util = new Util(); util .executeSQLCommand("create table ACCOUNT(ACC_ID int, ACC_FIRST_NAME varchar,ACC_LAST_NAME varchar,ACC_EMAIL varchar);"); util.executeSQLCommand("create table Message(Message_ID int, content varchar);"); SqlMapClient sqlMapper = util.getSqlMapClient(); Account account = new Account(); account.setId(1); account.setEmailAddress("e"); account.setFirstName("first"); account.setLastName("last"); sqlMapper.insert("insertAccount", account); util.checkData("select * from account"); List list = sqlMapper.queryForList("getByLike", account); System.out.println(((Account)list.get(0)).getLastName()); } } File: SqlMapConfig.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-config-2.dtd"> <sqlMapConfig> <!-- Configure a built-in transaction manager. If you're using an app server, you probably want to use its transaction manager and a managed datasource --> <transactionManager type="JDBC" commitRequired="false"> <dataSource type="SIMPLE"> <property name="JDBC.Driver" value="org.hsqldb.jdbcDriver"/> <property name="JDBC.ConnectionURL" value="jdbc:hsqldb:data/tutorial"/> <property name="JDBC.Username" value="sa"/> <property name="JDBC.Password" value=""/> </dataSource> </transactionManager> <!-- List the SQL Map XML files. They can be loaded from the classpath, as they are here (com.domain.data...) --> <sqlMap resource="Account.xml"/> <!-- List more here... <sqlMap resource="com/mydomain/data/Order.xml"/> <sqlMap resource="com/mydomain/data/Documents.xml"/> --> </sqlMapConfig> File: Util.java import java.io.Reader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import com.ibatis.common.resources.Resources; import com.ibatis.sqlmap.client.SqlMapClient; import com.ibatis.sqlmap.client.SqlMapClientBuilder; public class Util { Statement st; public Util() throws Exception{ // Load the JDBC driver. Class.forName("org.hsqldb.jdbcDriver"); System.out.println("Driver Loaded."); // Establish the connection to the database. String url = "jdbc:hsqldb:data/tutorial"; Connection conn = DriverManager.getConnection(url, "sa", ""); System.out.println("Got Connection."); st = conn.createStatement(); } public SqlMapClient getSqlMapClient() throws Exception{ Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml"); SqlMapClient sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader); reader.close(); return sqlMapper; } public void executeSQLCommand(String sql) throws Exception { st.executeUpdate(sql); } public void checkData(String sql) throws Exception { ResultSet rs = st.executeQuery(sql); ResultSetMetaData metadata = rs.getMetaData(); for (int i = 0; i < metadata.getColumnCount(); i++) { System.out.print("\t"+ metadata.getColumnLabel(i + 1)); } System.out.println("\n----------------------------------"); while (rs.next()) { for (int i = 0; i < metadata.getColumnCount(); i++) { Object value = rs.getObject(i + 1); if (value == null) { System.out.print("\t "); } else { System.out.print("\t"+value.toString().trim()); } } System.out.println(""); } } } File: Account.java public class Account { private int id; private String firstName; private String lastName; private String emailAddress; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmailAddress() { return emailAddress; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值