java - org.hibernate.id.IdentifierGenerationException : ids for this class must be manually assigned before calling save():

标签 java spring hibernate spring-mvc

我知道以前可能有人问过这个问题,但我没有找到解决我的问题的方法。我有一个 varchar(20) 的categoryID 主键列,实体类由 id 属性映射到该主键列。添加数据时,它采用通过 UI 输入的 id 值,但在编辑其他字段并通过 UI 保存时,会抛出异常“IdentifierGenerationException:必须在调用 save() 之前手动分配此类的 ids:”

请找到下面的代码:

          Category.java
          -------------
          package com.niit.cakecuisinebe.model;

          import java.util.UUID;

          import javax.persistence.Column;
          import javax.persistence.Entity;
          import javax.persistence.Id;
          import javax.persistence.PrePersist;
          import javax.persistence.Table;

          import org.springframework.stereotype.Component;

        @Entity
        @Table
        @Component
        public class Category {

            @Id
            @Column(name="CATEGORYID")
            private String id;


            public String getId() {
                return id;
            }
            public void setId(String id) {
                this.id = id;
            }
            public String getName() {
                return name;
            }
            public void setName(String name) {
                this.name = name;
            }
            public String getDescription() {
                return description;
            }
            public void setDescription(String description) {
                this.description = description;
            }
            @Column(name="CATEGORYNAME")
            private String name;
            @Column(name="CATEGORYDESCRIPTION")
            private String description;
        }
        CategoryDAOImpl
        ----------------
        package com.niit.cakecuisinebe.dao;

        import java.util.List;


        import javax.transaction.Transactional;

        import org.hibernate.Criteria;
        import org.hibernate.Query;
        import org.hibernate.SessionFactory;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.stereotype.Repository;

        import com.niit.cakecuisinebe.model.Category;
        @Repository("categoryDAO")
        public class CategoryDAOImpl implements CategoryDAO{

            @Autowired
            private SessionFactory sessionFactory;

            public CategoryDAOImpl(SessionFactory sessionFactory) {
                this.sessionFactory = sessionFactory;
            }

            @Transactional
            public List<Category> list()
            {
                //Logger.debug("calling list");

                @SuppressWarnings("unchecked")
                List<Category> listCategory = (List<Category>) 
                          sessionFactory.getCurrentSession()
                        .createCriteria(Category.class)
                        .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
            //  Logger.debug("calling list");
                return listCategory;
            }

            @Transactional
            public Category get(String id) {
                // TODO Auto-generated method stub
                String hql = "from Category where id=" + "'"+ id +"'";
                //  from category where id = '101'
                Query query =  sessionFactory.getCurrentSession().createQuery(hql);
                List<Category> listCategory = (List<Category>) query.list();

                if (listCategory != null && !listCategory.isEmpty()) {
                    return listCategory.get(0);
                }
                return null;
            }

            @Transactional
            public void saveOrUpdate(Category category) {
                // TODO Auto-generated method stub
                sessionFactory.getCurrentSession().saveOrUpdate(category);
            }
            @Transactional
            public void delete(String id) {
                // TODO Auto-generated method stub
                Category category = new Category();
                category.setId(id);
                sessionFactory.getCurrentSession().delete(category);
            }

            @Transactional
            public Category getByName(String name) {
                // TODO Auto-generated method stub
                String hql = "from Category where name=" + "'"+ name +"'";
                Query query = sessionFactory.getCurrentSession().createQuery(hql);

                @SuppressWarnings("unchecked")
                List<Category> listCategory = (List<Category>) query.list();

                if (listCategory != null && !listCategory.isEmpty()) {
                    return listCategory.get(0);
                }

                return null;

            }

        }
        CategoryController
        --------------------
        package com.niit;

        import java.util.List;
        import java.util.Map;

        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;

        import org.apache.log4j.Logger;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.stereotype.Controller;
        import org.springframework.ui.Model;
        import org.springframework.ui.ModelMap;
        import org.springframework.web.bind.annotation.ModelAttribute;
        import org.springframework.web.bind.annotation.PathVariable;
        import org.springframework.web.bind.annotation.RequestMapping;
        import org.springframework.web.bind.annotation.RequestMethod;

        import com.niit.cakecuisinebe.dao.CategoryDAO;
        import com.niit.cakecuisinebe.model.*;


        @Controller
        public class CategoryController {
            protected static Logger logger = Logger.getLogger("CategoryController");
            @Autowired
            private CategoryDAO categoryDao;

            @RequestMapping(value = "/ViewCategory", method = RequestMethod.GET)
            public String getCategory(Model model) {

                logger.info("entering showAllGreetings");
                model.addAttribute("category", new Category());

                List<Category> categories = categoryDao.list();
                if (!categories.isEmpty()) {

                    model.addAttribute("categorylist", categories);
                }

                return "Category";
            }

            @RequestMapping(value = "/addCategory", method = RequestMethod.POST)
            public String addCategory(@ModelAttribute("category") Category category) {
                logger.info("entering showAllGreetings");

                categoryDao.saveOrUpdate(category);

                return "redirect:/ViewCategory";

            }

            @RequestMapping(value = "edit/addCategory", method = RequestMethod.POST)
            public String editCategory(@ModelAttribute("category") Category category) {
                logger.info("entering showAllGreetings");

                String id=category.getId();
                category.setId(id);
                categoryDao.saveOrUpdate(category);

                return "redirect:/ViewCategory";

            }

            @RequestMapping(value = "delete/{id}", method = RequestMethod.GET)
            public String deleteCategory(@PathVariable("id") String id, ModelMap model) {
                logger.info("entering showAllGreetings");

                categoryDao.delete(id);
                model.addAttribute("{msg}", "Successfully Deleted");
                return "redirect:/ViewCategory";
            }

            @RequestMapping(value = "edit/{id}", method = RequestMethod.GET)
            public String showEditCategory(@PathVariable("id") String id, Model model) {
                logger.info("entering showAllGreetings");

                model.addAttribute("category", this.categoryDao.get(id));
                model.addAttribute("categorylist", categoryDao.list());

                return "Category";
            }
        }
        <div  >
        <spring:form method="POST"  action="addCategory" modelAttribute="category" align="center">
        <table cellpadding="5" cellspacing="5" style="height=45px; width=45px; background-color: pink; padding=10px">
            <tr>

                <c:choose>
                 <c:when test="${!empty category.id}">
                  <td><spring:label path="id"><springtags:message text="CategoryID"></springtags:message></spring:label></td>
                  <td><spring:input path="id" disabled="true" readonly="true" /></td>
                 </c:when>
                 <c:otherwise>
                    <td><spring:label path="id"><springtags:message text="CategoryID"></springtags:message></spring:label></td>
                    <td><spring:input path="id" /></td>
                 </c:otherwise>
                </c:choose>
            </tr>
            <tr>
                <td> Category Name:</td>
                <td><spring:input path="name" /></td>
            </tr>
             <tr>
                <td> Category Description:</td>
                <td><spring:input path="description" /></td>
            </tr>



            <tr>

               <c:if test="${!empty category.id}">
                            <td>    <input type="submit"
                                    value="<springtags:message text="Edit Category"/>" />
                            </c:if> 
                            </td>
                            <td><c:if test="${empty category.id}">
                                <input type="submit" value="<springtags:message text="Add Category"/>" />
                            </c:if>
                            </td>
            </tr>


        </table>
        </spring:form>
            </div>

            <div class="container">
            <table class="table table-striped table-bordered table-hover table-condensed">
            <caption><h2>Categories</h2></caption>
            <thead>
              <tr>
              <th>Category ID</th>
               <th>Category Name</th>
               <th>Category Description</th>
               <th>Edit</th>
               <th>Delete</th>
              </tr>
              </thead>
                 <c:if test="${not empty categorylist}" >
                 <tbody>
                    <c:forEach items="${categorylist}" var="category">      
                    <tr>
                    <td>${category.id}</td>
                    <td>${category.name}</td>
                    <td>${category.description} </td>
                    <td><a href="edit/${category.id}">Edit</a> </td>
                    <td><a href="delete/${category.id}">Delete</a> </td>
                    </tr>       
                    </c:forEach>
                </tbody>    
        </c:if>
        <c:if test="${empty categorylist}" >
            There are no category yet. 
        </c:if>
              </tr>


        </table>
        </div>
         <%@ include file="footer.jsp"%>
        </body>
        </html> 

请帮忙解决过去两天的问题

最佳答案

我不太喜欢字符串类型的 ids。你应该换一个长id。因此,您可以使用一些排序内容将 id 的生成委托(delegate)给数据库。

如果您希望实际列中的数据是唯一的,只需创建另一个具有唯一约束的字段即可。

关于java - org.hibernate.id.IdentifierGenerationException : ids for this class must be manually assigned before calling save():,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38620878/

相关文章:

java - 如何让下面的代码在alfresco中正常工作?

java - 元素类型 "result"的内容必须与 "(module-dependency|package-dependency|token- dependency)"匹配

java - 非类型化元素的 JAXB 自定义绑定(bind)?

java - Spring MVC 的标签库

java - 如何在 (OpenEntityManagerInView) Web 环境内部和外部使用相同的 DAO?

java - Propagation.REQUIRES_NEW 会对我的应用造成什么附带影响

java - Hibernate 级联删除未按预期工作

java - 使用 htmlunitdriver 捕获屏幕截图?

java - Spring 绑定(bind)结果错误

java - 错误 :/hibernate. 未找到 cfg.xml