A little improvement of spring JDBC RowMapper

Source: Internet
Author: User

"Note" Usually we use RowMapper (such as parameterizedrowmapper), we need to define the query fields, if you use aliases there is no way. Also want to join group, or union query, can not be used, unless you do not want a field outside the principal bean, you can only use map to receive the returned results, or directly implement RowMapper. Based on this, a slightly more general approach is proposed: all beans inherit a base class bean, with a map (that is, storing the fields that the bean does not specify, such as Sum, COUNT, avg ...). A variety of query fields or aliases), refer to Beanpropertyrowmapper, in the Maprow method to make minor adjustments, can not find the column placed in the map, this way, the bean has a field to use GetXXX (), not from the map to take, It seems to be a bit of a use.

#具体方法如下 #

publicabstractclass BaseEntity {    privatenew HashMap<String, Object>();    publicvoidsetAliasField(String field, Object value) {        aliasFields.put(field, value);    }    publicgetAliasFields(String field) {        return aliasFields.get(field);    }}  

The class only put a map, stored in the bean does not have the field, the rest is to transform the RowMapper implementation class, you can copy the Beanpropertyrowmapper, change the class name, directly modify the Maprow method, as follows (the amount of change is very small, see note):

 PublicTMaprow(ResultSet RS,intRowNumber)throwsSQLException {assert.state ( This. mappedclass! =NULL,"Mapped class is not specified"); T Mappedobject = Beanutils.instantiate ( This. Mappedclass);    Beanwrapper bw = propertyaccessorfactory.forbeanpropertyaccess (mappedobject);    Initbeanwrapper (BW); ResultSetMetaData RSMD = Rs.getmetadata ();intColumnCount = Rsmd.getcolumncount (); Set<string> populatedproperties = (ischeckfullypopulated ()?NewHashset<string> ():NULL); for(intindex =1; Index <= ColumnCount;        index++) {String column = Jdbcutils.lookupcolumnname (RSMD, index); PropertyDescriptor PD = This. Mappedfields.get (Column.replaceall (" ",""). toLowerCase ());if(PD! =NULL) {Try{Object value = GetColumnValue (RS, index, PD);if(logger.isdebugenabled () && RowNumber = =0) {Logger.debug ("Mapping column "+ column +" to the property"+ pd.getname () +"' of type"+ Pd.getpropertytype ()); }Try{Bw.setpropertyvalue (Pd.getname (), value); }Catch(Typemismatchexception e) {if(Value = =NULL&& primitivesdefaultedfornullvalue) {Logger.debug ("intercepted typemismatchexception for Row"+ RowNumber +"and column" "+ column +"' with value '+ Value +"When setting "+ pd.getname () +"' of type"+ pd.getpropertytype () +"on object:"+ Mappedobject); }Else{ThrowE }                }if(Populatedproperties! =NULL) {Populatedproperties.add (Pd.getname ()); }            }Catch(Notwritablepropertyexception ex) {Throw NewDataretrievalfailureexception ("Unable to map column"+ column +"to"+ Pd.getname (), ex); }        }Else{/// * * * * * Modify this place!!! Object value = Jdbcutils.getresultsetvalue (rs, index);        ((baseentity) mappedobject). Setaliasfield (column, value); }    }if(Populatedproperties! =NULL&&!populatedproperties.equals ( This. mappedproperties)) {Throw NewInvaliddataaccessapiusageexception ("Given ResultSet does not contain all fields"+"necessary to populate object of class ["+ This. Mappedclass +"]: "+ This. mappedproperties); }returnMappedobject;}

The rest is the specific bean that inherits the baseentity, such as:

 Public  class Demo extends baseentity implements Serializable {      Public Static Final LongSerialversionuid =2233912281609962999LPrivateInteger ID;PrivateString name;PrivateString password;PrivateDate Createtime;PrivateInteger type; Public Demo() {Super. QueryBuilder =NewQueryBuilder ( This); } Public void setId(Integer ID) { This. id = ID; } PublicIntegergetId() {return  This. ID; } Public void SetName(String name) { This. name = name; } PublicStringGetName() {return  This. Name; } Public void SetPassword(String password) { This. Password = password; } PublicStringGetPassword() {return  This. password; } Public void Setcreatetime(Date createtime) { This. createtime = Createtime; } PublicDateGetcreatetime() {return  This. createtime; } Public void SetType(Integer type) { This. type = type; } PublicIntegerGetType() {return  This. type; }}

When querying, you can use the demo bean to remove data from non-table fields through the Getaliasfields (String field) method. Personal feeling can improve a certain convenience, follow-up will join Sbrom, about Sbrom can see http://blog.csdn.net/yefeng_918/article/details/44747033, Welcome to spit Groove!

A little improvement of spring JDBC RowMapper

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.