I have a registration form:
<form action="${ pageContext.request.contextPath }/customer/add" method="post">
<div>
<label>Name: </label>
<input type="text" name="name">
</div>
<div>
<label>Address: </label>
<input type="text" name="address.address">
</div>
<input type="submit" value="Insert">
Here i want to insert value of this form into customer and address account having the following pojo:
Cusotmer.java
@Id
@GeneratedValue
@Column
private Long id;
@Column
private String name;
@OneToOne
@JoinColumn(name = "address_id")
private Address address;
Address.java
@Id
@GeneratedValue
@Column
private Long id;
@Column
private String address;
I have created a daoImpl method to add customer and their respective address:
CustomerDaoImpl
@Override
@Transactional
public void addCustomer(Customer c) {
session = sessionFactory.openSession();
session.beginTransaction();
session.save(c);
session.getTransaction().commit();
session.close();
}
AddressDaoImpl
@Override
@Transactional
public void addAddress(Address a) {
session = sessionFactory.openSession();
session.beginTransaction();
session.save(a);
session.getTransaction().commit();
session.close();
}
CustomerController
@Autowired
private CustomerDao customerDao;
@Autowired
private AddressDao addressDao;
@RequestMapping(value="/customer/add", method = RequestMethod.POST)
public String postCustomer(@ModelAttribute Customer c, @ModelAttribute Address a){
addressDao.addAddress(a);
c.setAddress(a);
customerDao.addCustomer(c);
return "redirect:/customer";
}
Insert operation not working for address value only. Customer is added along with the respective address_id but in address table itself, the address name is not inserted just id is created.
Change the name of the private vairable address in the Address pojo so that it wont contrast with the address object in the Customer pojo.
@Id
@GeneratedValue
@Column
private Long id;
@Column
private String aName; // change is here...
Similaly change the form address input name from address.address to aName only.
<form action="${ pageContext.request.contextPath }/customer/add" method="post">
<div>
<label>Name: </label>
<input type="text" name="name">
</div>
<div>
<label>Address: </label>
<input type="text" name="aName"> // see the change here...
</div>
<input type="submit" value="Insert">
And rest is same in controller.
@RequestMapping(value="/add", method = RequestMethod.POST)
public String postCustomer(@ModelAttribute Customer c, @ModelAttribute Address a){
addressDao.addAddress(a);
c.setAddress(a);
customerDao.addCustomer(c);
return "redirect:/customer";
}