2010-05-21 3 views
2

SimpleJdbcDaoSupport 클래스를 사용하여 중첩 된 콩을 삽입하는 방법 :봄 - 고객과 같이 정의 된 주소 클래스 - 나는 두 콩 (POJO들)이

public class Customer { 
    private String name = null; 
    private Address address = null; 

    public Customer() { 
    address = new Address(); 
    } 

    public String getName() { 
    return name; 
    } 

    public void setName(name) { 
    this.name = name; 
    } 
    //additional setters/getters for various properties 
} 

public class Address { 
    private String street = null; 

    public String getStreet() { 
    return street; 
    } 

    public void setStreet(street) { 
    this.street = street; 
    } 
    //additional setters/getters for various properties 
} 

나는 데이터베이스에이를 삽입하기 위해 노력하고있어를 다음과 같이 사용 :

public class CustomerDAO extends SimpleJdbcDaoSupport { 
    public int addOrganization(Customer customer) { 

    SimpleJdbcInsert insertCustomer = null; 
    BeanPropertySqlParameterSource params = null; 
    Number customerID = null; 

    insertTransaction = new SimpleJdbcInsert(getDataSource()).withTableName("customers") 
      .usingGeneratedKeyColumns("customerID"); 

    params = new BeanPropertySqlParameterSource(customer); 

    customerID = insertTransaction.executeAndReturnKey(params); 

    return customerID.intValue(); 
    } 
} 

문제 것은 내가 Invalid argument value: java.io.NotSerializableException을 얻을하고 고객을 삽입하지 않는 것입니다. 데이터베이스에서 주소를 제거 할 수 있으며 다른 고객 데이터를 삽입합니다.

MapSqlParameterSource params = new MapSqlParameterSource(); 
params.addValue("name", customer.getName()); 
params.addValue("street", customer.getAddress().getStreet()); 

을하지만 그건 BeanPropertySqlParameterSource 클래스의 용이성을 제거하고 난 어떤 속성을 추가하거나 제거하면, 나는 또 다른 라인을 추가 할 수 있습니다 또는, 나는 이런 식으로 뭔가를 할 수 있습니다.

각 값을 수동으로 추가 할 필요없이 중첩 된 주소 bean을 저장하는 쉬운 방법이 있습니까? 어떻게 데이터베이스 및/또는 빈을 정의해야이 일이 가능합니까?

답변

1

귀하의 솔루션은 가장 간단합니다.

중첩 된 객체의 데이터를 삽입해야하고 맵에 매개 변수를 추가하는 것을 원하지 않는 경우 대신 JPA 사용을 고려해야합니다.

1

MapSqlParameterSource 및 리플렉션에서이 작업을 수행하는 방법이 있습니다. 아래의 일부 코드. (단점은 리플렉션을 사용해야한다는 점이지만 장점은 필드 추가/제거에 대해 걱정할 필요가 없다는 것입니다).

Customer 클래스와 Address 클래스는 AbstractBean 또는 다른 클래스에서 확장해야합니다.

public static MapSqlParameterSource generate(Customer bean) { 
    try { 
     MapSqlParameterSource source = new MapSqlParameterSource(); 
     addAllFields(bean, source, bean.getClass().getDeclaredFields()); 
     return source; 
    } catch (IllegalAccessException e) { 
     throw new IllegalStateException("Unable to generate the parameter source", e); 
    } 
} 

private static void addAllFields(AbstractBean bean, MapSqlParameterSource source, Field[] fields) 
    throws IllegalAccessException { 
    for (Field field : fields) { 
     field.setAccessible(true); 
     if (field.getType().isAssignableFrom(Address.class)) { 
      Address address = (Address)field.get(bean); 
      addAllFields(address, source, address.getClass().getDeclaredFields()); 
     } else { 
      source.addValue(field.getName(), field.get(bean)); 
     } 
    } 
}