2016-05-14 2 views
0

У меня есть ошибка для редактирования с hibernate + spring. Я уже ищу в этом. Но до сих пор не удается найти решение. Я пишу код C R U D, все работают нормально, как добавление/удаление, но я получаю ошибки при редактировании/обновлении базы данных.hibernate get id = 0 Пакетное обновление возвращает неожиданный счетчик строк из обновления [0]; фактическое количество строк: 0; ожидается: 1

Просьба помочь вам найти решение?
Спасибо.

Вот мой код:

модальный/организация EmployeStatus.java

@Entity 
@Table 
public class EmployeeStatus { 

    @Id 
    @Column 
    @GeneratedValue(strategy= GenerationType.AUTO) 
    private int id; 

    @Column 
    private String name; 

    public EmployeeStatus() { 
    } 

    public EmployeeStatus(int id, String name) { 
     super(); 
     this.id = id; 
     this.name = name; 
    } 

    public int getId() { 
     return id; 
    } 

    public void setId(int id) { 
     this.id = id; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    @Override 
    public String toString() { 
     return "EmployeeStatus [id=" + id + ", name=" + name + "]"; 
    } 

} 

Dao осущ EmployeeStatusDaoImpl.java

@Repository 
public class EmployeeStatusDaoImpl implements EmployeeStatusDao { 

private static final Logger logger = LoggerFactory.getLogger(EmployeeStatusDaoImpl.class); 

@Autowired 
private SessionFactory sessionFactory; 

public EmployeeStatus findById(int id) { 

    return (EmployeeStatus)sessionFactory.getCurrentSession().get(EmployeeStatus.class, id); 
} 

@SuppressWarnings("unchecked") 
public List<EmployeeStatus> findAll() { 
    Session session = this.sessionFactory.getCurrentSession(); 
    List<EmployeeStatus> employeeList = session.createQuery("from EmployeeStatus").list(); 
    return employeeList; 
} 


public void save(EmployeeStatus es) { 
    //sessionFactory.getCurrentSession().save(es); 
    Session session = this.sessionFactory.getCurrentSession(); 
    session.persist(es); 
} 


public void update(EmployeeStatus es) { 
    //Session session = this.sessionFactory.getCurrentSession(); 
    //session.update(es); 
    sessionFactory.getCurrentSession().update(es); 
    sessionFactory.getCurrentSession().flush(); 
    //sessions.getCurrentSession().update(es); 
    logger.info("Employee Status updated successfully, Employee Status Details="+es); 
} 


public void delete(int id) { 
    sessionFactory.getCurrentSession().delete(findById(id)); 

} 


} 

сервис осущ EmployeeStatusServiceImpl.java

@Service 
public class EmployeeStatusServiceImpl implements EmployeeStatusService{ 

@Autowired 
private EmployeeStatusDao employeeStatusDao; 

@Transactional 
public EmployeeStatus findById(int id) { 
    return employeeStatusDao.findById(id); 
} 

@Transactional 
public List<EmployeeStatus> findAll() { 
    return employeeStatusDao.findAll(); 
} 

@Transactional 
public void save(EmployeeStatus es) { 
    employeeStatusDao.save(es); 

} 

@Transactional 
public void update(EmployeeStatus es) { 
    employeeStatusDao.update(es); 

} 

@Transactional 
public void delete(int id) { 
    employeeStatusDao.delete(id); 

} 


} 

контроллер EmployeeStatusController.java

@Controller 
public class EmployeeStatusController { 

@Autowired 
private EmployeeStatusService employeeStatusService; 

@RequestMapping(value="employeeStatus", method = RequestMethod.GET) 
public String list(Model model) { 
    model.addAttribute("empStat", new EmployeeStatus()); 
    model.addAttribute("list", this.employeeStatusService.findAll()); 
    return "empStat"; 
} 



    //For add 
    @RequestMapping(value= "/add", method = RequestMethod.POST) 
    public String addEmployeeStatus(@ModelAttribute("empStat") EmployeeStatus es){ 
     //new employee status, call save 
     this.employeeStatusService.save(es); 
     return "redirect:/employeeStatus"; 

    } 

    //for edit 
    @RequestMapping(value= "/update", method = RequestMethod.POST) 
    public String updateEmployeeStatus(@ModelAttribute("empStat") EmployeeStatus es){ 

     //existing Employee status, call update function from service 

     employeeStatusService.update(es); 
     return "redirect:/employeeStatus"; 

    } 

    @RequestMapping("/remove/{id}") 
    public String removeEmployeeStatus(@PathVariable("id") int id){ 

     this.employeeStatusService.delete(id); 
     return "redirect:/employeeStatus"; 
    } 

    //for call edit in list 
     @RequestMapping("/edit/{id}") 
     public String editEmployeeStatus(@PathVariable("id") int id, Model model){ 

      model.addAttribute("list", this.employeeStatusService.findAll()); 
      model.addAttribute("empStat", this.employeeStatusService.findById(id)); 
     return "empStat"; 
    } 


} 

employeeStatus.jsp JSP

` <%@ page language="java" contentType="text/html; charset=UTF-8" 
    pageEncoding="UTF-8"%> 
    <%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%> 
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
    <%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%> 
    <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> 


    <div id="page-wrapper"> 
    <div class="container-fluid"> 

     <!-- Page Heading --> 
     <div class="row"> 
      <div class="col-lg-12"> 
       <h1 class="page-header">Data Master</h1> 
       <ol class="breadcrumb"> 
        <li><i class="fa fa-dashboard"></i> <a href="/">Dashboard</a> 
        </li> 
        <li class="active"><i class="fa fa-table"></i> Employee Status List</li> 
       </ol> 
      </div> 
     </div> 
     <!-- /.row --> 
     <div class="page-content"> 
      <div class="col-md-9"> 
       <div class="panel panel-green"> 
        <div class="panel-heading">Employee Status</div> 
        <div class="panel-body"> 
         <table class="table table-hover table-bordered"> 
          <thead> 
           <tr> 
            <th>ID</th> 
            <th>Name</th> 
            <th>Operation</th> 
           </tr> 
          </thead> 
          <tbody> 
           <c:forEach items="${list}" var="empStatlist"> 
            <tr> 
             <td><a><c:out value="${empStatlist.id}" /></a></td> 
             <td><a><c:out value="${empStatlist.name}" /></a></td> 
             <td align="center"> 
              <a href="<c:url value='/edit/${empStatlist.id}' />"> 
               <span class="glyphicon glyphicon-edit"></span> 
              </a> 
                   
              <a href="<c:url value='/remove/${empStatlist.id}' />"> 
    <span class="glyphicon glyphicon-trash"></span> 
              </a> 
             </td> 
            </tr> 
           </c:forEach> 
          </tbody> 
         </table> 
        </div> 
       </div> 

       <br> 
       <div class="panel panel-success"> 
          <div class="panel-heading"> 
           <h3 class="panel-title">Add Employee Status</h3> 
          </div> 
          <div class="panel-body"> 
           <c:url var="addAction" value="/add"></c:url> 

           <form:form action="${addAction}" commandName="empStat"> 
            <table> 
             <tr> 
              <td><form:label path="name"> 
                <spring:message text="Name" /> 
               </form:label> 
              </td> 
              <td> 
               <form:input path="name" /> 
              </td> 
             </tr> 
             <tr> 
              <td colspan="2"> 
               <input type="submit" value="<spring:message text="Add"/>" /> 
              </td> 
             </tr> 
            </table> 
           </form:form> 
          </div> 
         </div> 

         <br> 
         <div class="panel panel-success"> 
          <div class="panel-heading"> 
           <h3 class="panel-title">Edit Employee Status</h3> 
          </div> 
          <div class="panel-body"> 
           <c:url var="editAction" value="/update"></c:url> 

           <form:form action="${editAction}" commandName="empStat"> 
            <table> 

              <tr> 
               <td> 
                <form:label path="id" > 
                 <spring:message text="ID" /> 
                </form:label> 
               </td> 
               <td> 
                <!-- <form:input path="id" /> --> 
                <form:input path="id" readonly="true" size="8" disabled="true" /> 
               </td> 
              </tr> 

             <tr> 
              <td><form:label path="name"> 
                <spring:message text="Name" /> 
               </form:label> 
              </td> 
              <td> 
               <form:input path="name" /> 
              </td> 
             </tr> 
             <tr> 
              <td colspan="2"> 
                <input type="submit" value="<spring:message text="Update"/>" /> 
              </td> 
             </tr> 
            </table> 
           </form:form> 
          </div> 
         </div> 
      </div> 
     </div>     
    </div> 
    </div>

, когда я ударил кнопку Simbol редактировать, я получаю данные, такие как идентификатор и имя get id

но когда я ударил редактировать кнопка i получила эту ошибку

15:48:18,574 DEBUG AnnotationTransactionAttributeSource:108 - Adding  transactional method 'EmployeeStatusServiceImpl.update' with attribute:  PROPAGATION_REQUIRED,ISOLATION_DEFAULT; '' 
Sat May 14 15:48:18 WIB 2016 WARN: Establishing SSL connection without  server's identity verification is not recommended. According to MySQL  5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be  established by default if explicit option isn't set. For compliance with  existing applications not using SSL the verifyServerCertificate property  is set to 'false'. You need either to explicitly disable SSL by setting  useSSL=false, or set useSSL=true and provide truststore for server certificate verification. 
15:48:18,587 INFO EmployeeStatusDaoImpl:50 - Employee Status updated successfully, Employee Status Details=EmployeeStatus [id=0, name=Semi Permanent] 
Hibernate: 
    update 
     EmployeeStatus 
    set 
     name=? 
    where 
     id=? 
15:48:18,603 ERROR AbstractBatcher:73 - Exception executing batch: 
org.hibernate.StaleStateException: Batch update returned unexpected row</code> 

id = 0 почему?

Как я могу это исправить?

ответ

0

Если HTML, сгенерированный JSP включает отключил на входе ид, ваш ответ

элементы с атрибутом инвалидов не представлены или вы можете сказать их значения не размещены.

Подробнее here

+0

ой мой плохой. спасибо за ваше решение. поэтому мне просто нужно изменить отключенный атрибут на чтение. еще раз спасибо – adi

0

Пожалуйста, следующие вещи в EmployeeStatus.java

  1. Изменение private int id; до private Long Id

  2. Удалить способ установки для этого свойства id.

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

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