A tool class that accelerates the generation of Spring JDBC RowMapper

Source: Internet
Author: User

Writing RowMapper is a tiring job when using spring JdbcTemplate. So I wrote a factory class rowmapperfactory that generates RowMapper based on the entity class to avoid writing RowMapper directly. Enumeration is not supported for rowmapperfactory.

Here is rowmapperfactory:

Import Org.springframework.jdbc.core.rowmapper;import Java.lang.reflect.method;import Java.sql.ResultSet;import Java.sql.sqlexception;import Java.util.hashmap;import Java.util.map;public class Rowmapperfactory {public static <    K> rowmapper<k> getinstance (class<k> clazz) {return getrowmapper (clazz); } public static <K> rowmapper<k> getrowmapper (class<k> clazz) {return new rowmapper<k> (            ) {Private autorowmapper<k> rm = new Autorowmapper (clazz);                    @Override public K Maprow (ResultSet rs, int rowNum) throws SQLException {try {                Return Rm.maprow (RS, RowNum, clazz.newinstance ()); } catch (Instantiationexception |                    Illegalaccessexception e) {e.printstacktrace ();                return null;    }            }        };     }/** * This is a writing helper class for simplifying RowMapper. * <p/> * This class will automatically skip ENA column that exists in tity but does not exist in the query statement.  * * @param <T> entity type */private static class Autorowmapper<t> {private map<string, string> Colname2settermap = new hashmap<> ();         Mapping of data column names to setter names private map<string, method> settermap = new hashmap<> ();    Setter name to setter method mapping private map<string, string> setterparammap = new hashmap<> (); Setter name to setter parameter type mapping/** * Initialize * * @param class object of T entity class */protected &LT ;            T> Autorowmapper (class<t> T) {method[] ms = T.getmethods ();                for (int i = 0; i < ms.length; i++) {String name = Ms[i].getname ();                    if (Name.startswith ("set") && ms[i].getparametercount () = = 1) {settermap.put (name, ms[i]);                    Setterparammap.put (name, Ms[i].getgenericparametertypes () [0].gettypename ()); Colname2settermap.put (SetteRtocolname (name), name);         }}}/** * In subclasses, this method is used in the Rowmapper.maprow to be implemented. * * @param rs Result set * @param rowNum result set line number * @param t entity object for filling query result row data * @retur N Incoming Entity Object */Public T Maprow (ResultSet RS, int. RowNum, T T) {for (String col:colname2se                    Ttermap.keyset ()) {try {int index = rs.findcolumn (col);//If the column is not found, an exception is thrown                    String settername = Colname2settermap.get (col);                Inject (Settermap.get (settername), Setterparammap.get (Settername), RS, index, T);                } catch (SQLException ex) {continue;        }} return t; }/** * Converts the setter name to a column name. such as Setcreatedon--and created_on */private static string Settertocolname (String settername) {S Tring property = Settername.substring (3, Settername.length ());            StringBuilder sb = new StringBuilder (). Append (Property.charat (0));                for (int i = 1; i < property.length (); i++) {char c = property.charat (i);                if (Character.isuppercase (c)) {Sb.append ('_');            } sb.append (c);        } return Sb.tostring (). toLowerCase ();         }/** * Injects the specified column into entity by type.       * <p/> * Currently supported class field types are: * <pre> * Java.lang.Boolean Boolean * java.lang.Byte         BYTE * Java.lang.Long Long * Java.lang.Integer int * Java.lang.Short Short * Java.lang.Float Float * java.lang.Double Double * java.lang.Date * Java.lang.Strin G * Java.sql.Blob * java.math.BigDecimal * </pre> * * private void inject (Meth        Od getter, String FieldType, ResultSet rs, int index, T t) {try {        Switch (fieldtype) {case ' Java.lang.Boolean '://Boolean case ' Boolean ':                        Getter.invoke (t, Rs.getboolean (index));                    Break Case "Java.lang.Byte"://Bytes Case "byte": Getter.invoke (T, rs.getbyte (Index)                        );                    Break Case "Java.lang.Long"://A long case "long": Getter.invoke (T, Rs.getlong (Inde                        x));                    Break Case "Java.lang.Integer"://int case "int": Getter.invoke (T, Rs.getint (index))                        ;                    Break Case ' java.lang.Short '://Short case ' short ': Getter.invoke (t, Rs.getshort (i                        Ndex));                    Break Case "java.lang.Float"://Float case "float":                       Getter.invoke (t, rs.getfloat (index));                    Break Case "java.lang.Double"://Double case "double": Getter.invoke (T, Rs.getdoubl                        E (index));                    Break                        Case "Java.lang.Date": Getter.invoke (T, rs.getdate (index));                    Break                        Case "java.lang.String": Getter.invoke (T, rs.getstring (index));                    Break                        Case "Java.sql.Blob": Getter.invoke (T, Rs.getblob (index));                    Break                        Case "Java.math.BigDecimal": Getter.invoke (T, Rs.getbigdecimal (index));                    Break                        Default:getter.invoke (t, Rs.getobject (index));                Break }} catch (Exception ex) {               Ex.printstacktrace (); }        }    }}

Use the following methods:

rowmapper<user> userrowmapper = Rowmapperfactory.getrowmapper (User.class);

A tool class that accelerates the generation 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.