DBUtils fails to fill fields of a Java Bean

后端 未结 2 1856
我寻月下人不归
我寻月下人不归 2021-01-07 12:18

I have a mysql table like this:

CREATE TABLE `sezione_menu` (
 `id_sezione_menu` int(11) unsigned NOT NULL AUTO_INCREMENT,
 `nome` varchar(256) NOT NULL DEFA         


        
相关标签:
2条回答
  • 2021-01-07 13:14

    You can fix it in two ways:

    As per dbutils doc,

    1. Alias the column names in the SQL so they match the Java names: select social_sec# as socialSecurityNumber from person
    2. Subclass BeanProcessor and override the mapColumnsToProperties() method to strip out the offending characters.

    If you are keeping a class like this

    public class SezioneMenuBean implements Serializable {
    
        private int idSezioneMenu;
    
        private String nome;
    
        private int ordine;
    
        public SezioneMenuBean() {
        }
    
        // Getters and setters for bean values
    
    }
    

    As per first solution write your queries something like this SELECT id_sezione_menu AS idSezioneMenu, name, ordine FROM sezione_menu.

    Or

    Based on second solution you can use GenerousBeanProcessor which is a subclass of BeanProcessor it ignores underscore & case sensitivity from column name. You don't have to implement your own custom BeanProcessor

    GenerousBeanProcessor is available since version 1.6 of commons-dbutils.

    Usage:

    // TODO initialize
    QueryRunner queryRunner = null;
    
    ResultSetHandler<List<SezioneMenuBean>> resultSetHandler =
                    new BeanListHandler<SezioneMenuBean>(SezioneMenuBean.class, new BasicRowProcessor(new GenerousBeanProcessor()));
    
    // best practice is specifying only required columns in the query
    // SELECT id_sezione_menu, name, ordine FROM sezione_menu
    final List<SezioneMenuBean> sezioneMenuBeans = queryRunner.query("SELECT * FROM sezione_menu", resultSetHandler);
    
    for (SezioneMenuBean sezioneMenuBean : sezioneMenuBeans) {
        System.out.println(sezioneMenuBean.getIdSezioneMenu());
    }
    
    0 讨论(0)
  • 2021-01-07 13:14

    I faced the same issue of BeanHandler/BeanHandlerList returning null or 0 for database columns.

    As mentioned by @aelfric5578 in the comment, I have updated the Bean class with same names as Database, DBUtils returned values correctly.

    Having BeanClass defined like this will solve your problem.

    
        public class SezioneMenuBean{
    
        int id_sezione_menu;
        String nome;
        int ordine;
    
        public SezioneMenuBean(){
        }
    
        // Getters and setters for bean values
    
        }
    
    
    0 讨论(0)
提交回复
热议问题