2012-11-20 5 views
9

Spring MVC를 처음 사용합니다. Spring, Spring MVC 및 JPA/Hibernate를 사용하는 응용 프로그램을 작성 중입니다. Spring MVC에서 모델 객체로 드롭 다운 값을 설정하는 방법을 모르겠습니다. Customer.javaSpring MVC의 Dropdown 값 바인딩

@Entity 
public class Customer { 
    @Id 
    @GeneratedValue 
    private Integer id; 

    private String name; 
    private String address; 
    private String phoneNumber; 

    //Getters and setters 
} 

invoice.jsp

<form:form method="post" action="add" commandName="invoice"> 
    <form:label path="amount">amount</form:label> 
    <form:input path="amount" /> 
    <form:label path="customer">Customer</form:label> 
    <form:select path="customer" items="${customers}" required="true" itemLabel="name" itemValue="id"/>     
    <input type="submit" value="Add Invoice"/> 
</form:form> 

Invoice.java

@Entity 
public class Invoice{  
    @Id 
    @GeneratedValue 
    private Integer id; 

    private double amount; 

    @ManyToOne(targetEntity=Customer.class, fetch=FetchType.EAGER) 
    private Customer customer; 

    //Getters and setters 
} 

:이 매우 일반적인 시나리오 여기

상상할 수있는 것은 코드

InvoiceCon troller.java InvoiceControler.addInvoice()가 호출 인보이스 인스턴스를 매개 변수로서 수신

@Controller 
public class InvoiceController { 

    @Autowired 
    private InvoiceService InvoiceService; 

    @RequestMapping(value = "/add", method = RequestMethod.POST) 
    public String addInvoice(@ModelAttribute("invoice") Invoice invoice, BindingResult result) { 
     invoiceService.addInvoice(invoice); 
     return "invoiceAdded"; 
    } 
} 

. 송장의 금액은 예상대로이지만 고객 인스턴스 속성은 null입니다. 이것은 http 포스트가 고객 ID를 제출하고 Invoice 클래스가 Customer 객체를 기대하기 때문입니다. 나는 그것을 변환하는 표준 방법이 무엇인지 모른다.

스프링 타입 변환 (http://static.springsource.org/spring/docs/current/spring-framework-reference/html/validation.html)에 대해 Controller.initBinder()에 대해 읽었지만이 문제에 대한 해결책인지 잘 모릅니다.

아이디어가 있으십니까?

+3

가 나는 그것이 <폼 교체 작업을했다 : 선택 경로 = "고객".. ./>

답변

7

이미 언급 한 트릭은 ID를 드롭 다운에서 사용자 지정 인스턴스로 변환하는 사용자 지정 변환기를 등록하는 것입니다.

사용자 지정 변환이 방법을 쓸 수 있습니다 :

public class IdToCustomerConverter implements Converter<String, Customer>{ 
    @Autowired CustomerRepository customerRepository; 
    public Customer convert(String id) { 
     return this.customerRepository.findOne(Long.valueOf(id)); 
    } 
} 

지금 스프링 MVC와 함께이 변환기를 등록 :

<mvc:annotation-driven conversion-service="conversionService"/> 

<bean id="conversionService" 
    class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> 
    <property name="converters"> 
     <list> 
      <bean class="IdToCustomerConverter"/> 
     </list> 
    </property> 
</bean> 
+2

내가 그런 접근법에 대해 싫어하는 것은 당신이 이미 데이터베이스에서 ID와 같은 데이터 객체를로드했다는 것입니다. 이제 다시 문자열에서 객체로 변환하면 db에서 다시 가져옵니다. –

+0

@Biju Kunjummen : Annotation 및 Controller 클래스 코드로 답변을 업데이트 해 주시겠습니까? –

관련 문제