如何将结果集复制到对象? [英] How to copy resultset into object?

查看:124
本文介绍了如何将结果集复制到对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下方法将检索到的值添加到类中。所有的值将被添加到类的属性,但我使用compisition(在类中有一个类的对象),并且它不显示任何输出。

I am using the following to add retrieved values to the class. all values will be added to attributes of the class but I am using compisition ( have an object of class in the class) and it does not show anything on output.

class employee 
{
....
private Address address = new Address();
.....
}
 ...
Employee emp = new Employee();
        try {

            ps = con.prepareStatement("select * from employee,address "
                    + "WHERE employee.username = ? AND "
                    + "employee.ADD_ID = address.ID");

            ps.setString(1, username);
            ResultSet r = ps.executeQuery();
            if (r.next()) {

                BeanProcessor bp = new BeanProcessor();
                emp = bp.toBean(r,Employee.class);
                System.out.println("blockkkk:"+emp.getAddress().getBlock());  
                                            //output of above line is blockkkk:null
            }

            con.close();
            ps.close();
        } catch (SQLException e) {
            System.err.println(e.getMessage());

        }
       return emp;

地址类别如下:

  public class Address {
    .....
    private String block;
    ....
      public String getBlock() {
            return block;
        }

        public void setBlock(String block) {
            this.block = block;
        }
    ....
   }


推荐答案

BeanProcessor.toBean 的工作方式如下:

将ResultSet行转换为JavaBean 。此实现使用反射和BeanInfo类来将列名称匹配到bean属性名称。根据以下几个因素将属性与列匹配:

Convert a ResultSet row into a JavaBean. This implementation uses reflection and BeanInfo classes to match column names to bean property names. Properties are matched to columns based on several factors:


  • 类具有与列名称相同的writable属性。

  • 可以使用ResultSet.get *方法将列类型转换为属性的set方法参数类型。如果转换失败(即属性为int,列为Timestamp),则抛出SQLException。

当从ResultSet返回SQL NULL时,将其设置为其缺省值。数字字段设置为0,布尔值设置为false。返回SQL NULL时,对象bean属性设置为null。这与ResultSet get *方法的行为相同。

Primitive bean properties are set to their defaults when SQL NULL is returned from the ResultSet. Numeric fields are set to 0 and booleans are set to false. Object bean properties are set to null when SQL NULL is returned. This is the same behavior as the ResultSet get* methods.

可能是地址不是可写属性。请检查它。

May be the address is not a writable property. Pls do check it.

这篇关于如何将结果集复制到对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆