2017-12-10 8 views
1

BeanUtils.setProperty 메서드를 사용하는 데 문제가 있습니다. 나는이 JAR 사용하고 있습니다 :BeanUtils.setProperty 메서드가 null을 BigDecimal 필드로 설정합니다.

<dependency> 
    <groupId>commons-beanutils</groupId> 
    <artifactId>commons-beanutils</artifactId> 
    <version>1.9.3</version> 
</dependency> 

내가 하나 개의 레코드를 반환하고 내가이 만든 자바 빈즈에 대한 결과 집합을 매핑하고있어 MySQL의 쿼리를 실행합니다. 여기에 메인 클래스가 있습니다.

public class QueryTester { 

    public static void viewTable(Connection con) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException { 
     Statement stmt = null; 
     String query = "SELECT * FROM Books WHERE code = 'AA00'"; 
     try { 
      stmt = (Statement) con.createStatement(); 
      ResultSet rs = stmt.executeQuery(query);  
      ResultSetMapper<Books> rsMapper = new ResultSetMapper<Books>(); 
      List<Books> list = rsMapper.mapResultSetToObject(rs, Books.class); 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     } finally { 
      if (stmt != null) { 
       stmt.close(); 
      } 
     } 
    } 

    public static void main(String[] args) { 
     Connection conn = null; 
     String url = "jdbc:mysql://localhost/dbname"; 
     String driver = "com.mysql.jdbc.Driver"; 
     String userName = "root"; 
     String password = "root"; 
     try { 
      Class.forName(driver).newInstance(); 
      conn = (Connection) DriverManager.getConnection(url,userName,password); 
      viewTable(conn); 
      conn.close(); 
     } catch (Exception e) { 
      System.out.println("NO CONNECTION"); 
     } 
    } 
} 

그리고 이것은 BeanUtils.setProperty 메서드를 사용하는 메서드입니다.

public class ResultSetMapper<T> { 
    public List<T> mapResultSetToObject(ResultSet rs, Class<T> outputClass) throws InstantiationException, SQLException, IllegalAccessException, InvocationTargetException { 
     List<T> outputList = new ArrayList<T>(); 
     if (rs == null) { 
      return outputList; 
     } 
     if (!outputClass.isAnnotationPresent(Entity.class)) { 
      throw new InstantiationException("Entity notation not present."); 
     } 

     ResultSetMetaData rsmd = rs.getMetaData(); 
     // retrieve data fields from output class 
     Field[] fields = outputClass.getDeclaredFields(); 
     while (rs.next()) { 
      T bean = (T) outputClass.newInstance(); 
      for (int iterator = 0; iterator < rsmd.getColumnCount(); iterator++) { 
       String columnName = rsmd.getColumnName(iterator + 1); 
       Object columnValue = rs.getObject(iterator + 1); 
       for (Field field : fields) { 
        if (field.isAnnotationPresent(Column.class)) { 
         Column column = field.getAnnotation(Column.class); 
         if (column.name().equalsIgnoreCase(columnName) && columnValue != null) { 
          BeanUtils.setProperty(bean, field.getName(), columnValue); 
          break; 
         } 
        } 
       } 
      } 
      outputList.add(bean); 
     } 
     return outputList; 
    } 
} 

mapResultSetToObject 메서드는 올바른 요소 하나가 포함 된 List를 반환하지만 잘못된 방식으로 설정됩니다. 필드 코드와 bookDescription은 올바르게 설정되어 있지만 kPrice 필드는 데이터베이스의 값인 3.000 대신 null로 설정됩니다. 이 코드를 디버그 모드로 실행하고 "columnValue"변수의 값이 3.000이지만 setProperty 메서드가 올바른 값을 설정하지 않고 값이 null로 유지됩니다.

여기에 Java Bean이 있습니다.

@Entity 
public class Books { 

    @Column(name="code") 
    private String code; 
    @Column(name="book_description") 
    private String bookDescription; 
    @Column(name="kPrice") 
    private BigDecimal kPrice; 

    public Books() {} 

    public Books(String code, String bookDescription, BigDecimal kPrice){ 
     this.code = code; 
     this.bookDescription = bookDescription; 
     this.kPrice = kPrice; 
    } 

    /* Getters and setters */ 
    ... 
} 

그리고 이것은 MySQL 테이블과 레코드입니다.

CREATE TABLE `Books` (
    `code` varchar(4) NOT NULL, 
    `book_description` varchar(50) NOT NULL DEFAULT '', 
    `kPrice` decimal(10,4) NOT NULL DEFAULT '1.0000', 
    PRIMARY KEY (`code`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 

INSERT INTO dbname.Books (code, book_description, kPrice) VALUES('AA00', 'Description example', 3.0000); 

왜 이러한 동작이 발생합니까? 내가 뭘 놓치고 있니? 미리 감사드립니다.

답변

0

세터/게터의 이름은 속성과 동일합니까?

경우에 따라 문제가 있습니다.

@Entity 
public class Books { 

    @Column(name="code") 
    private String code; 
    @Column(name="book_description") 
    private String bookDescription; 
    @Column(name="kPrice") 
    private BigDecimal kPrice; 

    public Books() {} 

    public Books(String code, String bookDescription, BigDecimal kPrice){ 
     this.code = code; 
     this.bookDescription = bookDescription; 
     this.kPrice = kPrice; 
    } 

    public void setKPrice (Bigdecimal kPrice) // and not setkPrice or setPrice.. 
    { 
     this.kPrice = kPrice; 
    } 

    public BigDecimal getKPrice() // and not getkPrice or getPrice.. 
    { 
     return this.kPrice; 
    } 
} 
:

아래에있는 내 예를 참조하십시오

관련 문제