Я новичок в весне + спящий режим. Когда я добавляю клиента и его адресатов (от одного до многих отношений), все в порядке. Но когда я обновляю пункт назначения клиента, все предыдущие адресаты остаются в базе данных с нулевым внешним ключом клиента.Как удалить объект из списка автопопуляций весной
Предположим, что я вставляю 4 адресата a, b, c, d. После обновления клиента я вставляю x, y. Затем он хранит всего 6 пунктов назначения: a, b, c, d с нулевыми ссылками и x, y с отзывами клиентов.
Вот мой код:
1). Организация-заказчик
Имеет отношение «один ко многим» с назначением и отношения однонаправлен.
@Entity
@Table(name="customers")
@Proxy(lazy=false)
public class CustomerEntity {
@Id
@Column(name="id")
@GeneratedValue
private Integer id;
private String description;
private String panNo;
private String cstNo;
private String vatNo;
@OneToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
@JoinColumn(name = "customer_id", referencedColumnName = "id")
public List<DestinationsEntity> destination = new AutoPopulatingList<DestinationsEntity>(DestinationsEntity.class);
//getter and setters
}
2). Назначение Entity
@Entity
@Table(name = "destinations")
@Proxy(lazy = false)
public class DestinationsEntity {
@Id
@Column(name = "id")
@GeneratedValue
private Integer id;
@Column(name="destination")
private String destination;
// getter and setter
}
1). AddCustomer.jsp
Этот код для добавления дополнительных адресатов в списке заполняются автоматически
<div id="destination_container">
<div><textarea row="3" col="5" class="destination_address" name= "destination[${0}].destination" placeholder="Please enter address"></textarea></div>
</div>
<script type="text/javascript">
$(document).ready(function(){
var index = 1;
/*
* Add more destination
*/
$('#add_more_destination').click(function(){
$('#destination_container').append('<div><textarea row="3" col="5" class="destination_address" name= "destination[${"'+index+'"}].destination" placeholder="Please enter address"></textarea><span class="remove_dest">*</span></div>');
index++;
});
});
</script>
2). updateCustomer.jsp
Всех направления, добавленные заказчика показать здесь, и он/она может быть направлением изменения (например, перед тем, вставленной Пуна, Мумбаи, Бангалор) в настоящее время обновления направление (дели, Пенджаб)
<c:set var="index" scope="page" value="${fn:length(destinationss)}"/>
<c:forEach items="${destinationss}" var="dest" varStatus="i">
<div>
<textarea class="destination_address" name= "destination[${i.index}].destination" placeholder="Please enter address">${dest.destination}</textarea><span class="remove_dest">*</span>
</div>
</c:forEach>
<button type ="button" id="add_more_destination">Add More Destinations</button>
<script type="text/javascript">
$(document).ready(function(){
/*
* Add a destination
*/
var index = ${index};
$('#add_more_destination').click(function(){
$('#destination_container').append('<div><textarea row="3" col="5" class="destination_address" name=destination["'+index+'"].destination placeholder="Please enter address"></textarea><span class="remove_dest">*</span></div>');
alert(index);
index++;
});
</script>
контроллер
@RequestMapping(value = "/addCustomerForm", method = RequestMethod.GET)
public String addCustomerForm(ModelMap map) {
return "master/addCustomer";
}
@RequestMapping(value = "/addCustomer", method = RequestMethod.POST)
public String addCustomer(@ModelAttribute(value = "customer") CustomerEntity customer,BindingResult result, HttpServletRequest request) {
customerService.addCustomer(customer);
return "redirect:/customer";
}
Обновление клиента
Это новая вещь, которую я пробовал прошлой ночью. Проблема решается частично.
@ModelAttribute
public void updateOperation(HttpServletRequest request, ModelMap map) {
if(null !=request.getParameter("id"))
map.addAttribute("customer1", customerService.findOne(Integer.parseInt(request.getParameter("id"))));
}
@RequestMapping(value = "/updateCustomerForm/{customerId}", method = RequestMethod.GET)
public String updateCustomerForm(@PathVariable("customerId") Integer customerId, ModelMap map, HttpServletRequest request) {
CustomerEntity customerEntity = customerService.findOne(customerId);
map.addAttribute("customer", customerEntity);
map.addAttribute("destinationss",customerEntity.getDestination());
}
@RequestMapping(value = "/updateCustomer", method = RequestMethod.POST)
public String updateCustomer(@ModelAttribute(value = "customer1")CustomerEntity customer1,BindingResult result, HttpServletRequest request,HttpServletResponse response) {
customerService.updateCustomer(customer1);
return "redirect:/customer";
}
}
1). CustomerServiceImpl
public class CustomerServiceImpl implements CustomerService{
@Autowired
private CustomerDao customerDao;
@Override
@Transactional
public void addCustomer(CustomerEntity customer) {
customerDao.addCustomer(customer);
}
@Override
@Transactional
public CustomerEntity findOne(Integer id){
return customerDao.findOne(id);
}
@Override
@Transactional
public void updateCustomer(CustomerEntity customerEntity){
if (null != customerEntity) {
customerDao.updateCustomer(customerEntity);
}
}
}
2) .CustomerDaoImpl
public class CustomerDaoImpl implements CustomerDao{
@Autowired
private SessionFactory sessionFactory;
@Override
@Transactional
public void addCustomer(CustomerEntity customer){
this.sessionFactory.getCurrentSession().save(customer);
}
@Override
public CustomerEntity findOne(Integer id){
return (CustomerEntity) sessionFactory.getCurrentSession().load(CustomerEntity.class, id);
}
@Override
@Transactional
public void updateCustomer(CustomerEntity customerEntity){
if (null != customerEntity) {
this.sessionFactory.getCurrentSession().update(customerEntity);
}
}
}
ваш вопрос не ясно, пожалуйста, объясните это правильно – Chaitanya
на самом деле у меня есть отношения один ко многим 1 клиентов, имеющих несколько назначения. когда я сохраняю 1 клиента с 4-мя адресатами, все работают нормально. но когда tring обновляет объект клиента, а затем сохраняет приоритеты для изменения ключа назначения для нулевого и нового адресатов, сохранить в базе данных. – zoomba
Решение состоит в том, чтобы получить адресаты для клиентов и сохранить их в наборе, а затем добавить новые адресаты в набор, а затем сделать обновление. Теперь Hibernate позаботится об отношениях. Если вы этого не делаете, тогда hibernate предполагает, что вы пытаетесь удалить старые адресаты и добавлять новые адресаты, поэтому причина заключается в том, что внешние ключи удаляются в таблице назначения для тех, кто уже устарел. – Chaitanya