Friday 17 April 2015

Dropdown access nested child object of entity object in spring form:select box


If you want to access nested objects which is coming child object like if we have relationship of ManyToOne or OneToMany then when we fetch object of one entity then the dependent object's reference will also come inside that object
Lets take an Example.

We have to models as below 

Address

@Entity
@Table(name="Address")
public class Address implements Serializable {

    private static final long serialVersionUID = 1L;
   
    @Id
    @Column(name="id",unique=true)
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
   
    @Column(name="address1")
    private String address1;
   
    @Column(name="address2")
    private String address2;
   
    @Column(name="city")
    private String city;
   
    @Column(name="state")
    private String state;
   
    @Column(name="zip")
    private String zip;
 
@OneToMany(mappedBy="address",cascade=CascadeType.ALL)
    private List<Contact> contacts;
                                     //all setter and getter here
}


Contact

@Entity
@Table(name="CONTACTS")
public class Contact implements Serializable  {
    private static final long serialVersionUID = 1L;
   
    @Id
    @Column(name="ID")
    @GeneratedValue
    private Integer id;
   
    @Column(name="FIRSTNAME")
    private String firstname;

    @Column(name="LASTNAME")
    private String lastname;

    @Column(name="EMAIL")
    private String email;
   
    @Column(name="TELEPHONE")
    private String telephone;
   
    @ManyToOne
    private Address address;
                                    //all setter and getter here
}


Now here we have used ManyToOne and OneToMany dependency.
so we can have more then one contact for one address.

Now if i am inserting a new contact then i have to select the address to which contact belong.
and when i get contact then related address should also get selected.
now lets take one controller which will have method to add and get the contact.

ContactController 

@Controller
public class ContactController {

    @Autowired
    private ContactService contactService;    
  
    @Autowired
    private AddressService addressService;

    @RequestMapping("/index")
    public String listContacts(Map<String, Object> map) {

        if(contactService.listContact().size()>0){
            map.put("contact", contactService.listContact().get(0));
        }else
        {
            map.put("contact", new Contact());
        }
     

        map.put("addressList", addressService.listAddress());
        map.put("contactList", contactService.listContact());
      
        return "contact";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addContact(@ModelAttribute("contact")
    Contact contact, BindingResult result) {
          
            contact.setAddress(addressService.getAddressById(contact.getAddress().getId()));
      
        contactService.addContact(contact);

        return "redirect:/index";
    }

  @RequestMapping("/delete/{contactId}")
    public String deleteContact(@PathVariable("contactId")
    Integer contactId) {

        contactService.removeContact(contactId);

        return "redirect:/index";
    }
 }


Now lets create the contact.jsp page on which we will have a form to add the contact and display first contact filled in form if any.

contact.jsp 

 <%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Spring 3 MVC Series - Contact Manager</title>
</head>
<body>

    <h2>Contact Manager</h2>

    <form:form method="post" action="add.html" commandName="contact">

        <table>
            <tr>
                <td>First Name</td>
                <td><form:input path="firstname" /></td>
            </tr>
            <tr>
                <td>Last Name</td>
                <td><form:input path="lastname" /></td>
            </tr>
            <tr>
                <td>Email</td>
                <td><form:input path="email" /></td>
            </tr>
            <tr>
                <td>telephone</td>
                <td><form:input path="telephone" /></td>
            </tr>
            <tr>
                <td>Address</td>
                <td>
               <c:if test="${!empty addressList}">
                        <form:select path="address.id" itemValue="address.id">
                                <c:forEach items="${addressList}" var="address">

                                    <form:option value="${address.id}">${address.address1},${address.address2},${address.city}</form:option>

                                </c:forEach>
                            </form:select>
                    </c:if>
</td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit"
                    value="<spring:message code="label.addcontact"/>" /></td>
            </tr>
        </table>
    </form:form>

    <h3>Contacts</h3>
    <c:if test="${!empty contactList}">
        <table class="data">
            <tr>
                <th>Name</th>          <th>Email</th>           <th>Telephone</th>          <th>&nbsp;</th>
            </tr>
            <c:forEach items="${contactList}" var="contact">
                <tr>
                    <td>${contact.lastname}, ${contact.firstname}</td>
                    <td>${contact.email}</td>
                    <td>${contact.telephone}</td>
                    <td><a href="delete/${contact.id}">delete</a></td>
                </tr>
            </c:forEach>
        </table>
    </c:if>


</body>
</html>


This will diasplay the form which is allow to add the contact to selected address and display the contact with its related address seleted in <form:select> drop down. 

NOTE: Create required serveries and dao. 





No comments:

Post a Comment