2015-06-17 3 views
0

Я новичок в весне + спящий режим. Когда я добавляю клиента и его адресатов (от одного до многих отношений), все в порядке. Но когда я обновляю пункт назначения клиента, все предыдущие адресаты остаются в базе данных с нулевым внешним ключом клиента.Как удалить объект из списка автопопуляций весной

Предположим, что я вставляю 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); 
     } 
    } 
} 
+0

ваш вопрос не ясно, пожалуйста, объясните это правильно – Chaitanya

+0

на самом деле у меня есть отношения один ко многим 1 клиентов, имеющих несколько назначения. когда я сохраняю 1 клиента с 4-мя адресатами, все работают нормально. но когда tring обновляет объект клиента, а затем сохраняет приоритеты для изменения ключа назначения для нулевого и нового адресатов, сохранить в базе данных. – zoomba

+0

Решение состоит в том, чтобы получить адресаты для клиентов и сохранить их в наборе, а затем добавить новые адресаты в набор, а затем сделать обновление. Теперь Hibernate позаботится об отношениях. Если вы этого не делаете, тогда hibernate предполагает, что вы пытаетесь удалить старые адресаты и добавлять новые адресаты, поэтому причина заключается в том, что внешние ключи удаляются в таблице назначения для тех, кто уже устарел. – Chaitanya

ответ

0

Этот вопрос весна даст вам новый объект клиента, поэтому я предполагаю, что объекты Destination в этом Заказчик пуст изначально. Таким образом, в вашей операции обновления вы просто добавляете несколько новых объектов Destination, а затем добавляете их клиенту в соответствии с вашим кодом.

Таким образом, в этом случае объект-заказчик имеет только новые объекты-адресаты, где, поскольку уже существующие объекты-адресаты, которые были сопоставлены ранее, в вашем объекте Customer отсутствуют.

Чтобы устранить проблему, сначала получите объект Customer из базы данных, тогда этот объект будет иметь набор целевых объектов. Теперь этому клиенту вы можете добавить новые объекты Destination, а также обновить существующие объекты Destination, если это необходимо, и попросить Hibernate выполнить операцию обновления. В этом случае Hibernate может видеть ваши более ранние целевые объекты, а также новые целевые объекты и на основании этого он будет запускать запросы на вставку &.

код выглядит примерно так:

// First get the customer object from database: 
Customer customer = (Customer) this.sessionFactory.getCurrentSession().get(Customer.class, customerId); 

// Now add your destination objects, if you want you can update the existing destination entires here. 

for (int i = 0; i < destinationAddrs.length; i++) { 
        DestinationsEntity destination = new DestinationsEntity(); 
        destination.setDestination(destinationAddrs[i]); 
           customer.getDestinationEntity().add(destination); 


       } 

// Then do the update operation  
this.sessionFactory.getCurrentSession().update(customer); 
+0

@modelAttribute всегда дает мне новый объект клиента, как я могу реплицировать его с помощью объекта persist .. любое решение для него. или рабочий пример. – zoomba

+0

как я могу загрузить объект persist вместо нового объекта-клиента – zoomba

+0

@JavedShhaikh, данный пример кода, попробуйте его – Chaitanya

Смежные вопросы