java.sql.SQLException : Duplicate entry 'sd' for key 'PRIMARY' 异常

标签 java servlets jpa persistence google-cloud-sql

我正在尝试在 Google 云 SQL 中使用 JPA 保留此角色对象。但我不确定如何捕获主键违规异常并向用户显示适当的消息。

需要帮助格式化这部分代码中的 try 和 catch

EntityManager em = EMF.get().createEntityManager();
EntityTransaction tx = em.getTransaction();

            tx.begin();
            em.persist(r);
            tx.commit();

这是我的整个 servlet 代码。

package com.example.rolessample;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class persist_role_servlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        PrintWriter out = resp.getWriter();

        String role_id = req.getParameter("role_id");
        String role_name = req.getParameter("role_name");
        String role_desc = req.getParameter("role_desc");

        String comp_id = "";
        String parent_comp = "";
        String permission = "";

        role r = new role();

        r.setRole_id(role_id);
        r.setRole_name(role_name);
        r.setRole_desc(role_desc);


        //Persisting the role bean .

        EntityManager em = EMF.get().createEntityManager();
        EntityTransaction tx = em.getTransaction();

            tx.begin();
            em.persist(r);
            tx.commit();




        String[] checkboxNamesList = req.getParameterValues("component");

        for (int i = 0; i < checkboxNamesList.length; i++) {

            String[] myCheckBoxValue = req
                    .getParameterValues(checkboxNamesList[i]);

            //If null, it means checkbox is not in request, so unchecked
            if (myCheckBoxValue == null) {

                component comp = new component();


                //Logic for finding component's name,component parent and their permissions.
                String S1 = checkboxNamesList[i];
                int lastUnderscore = S1.lastIndexOf("_");
                permission = S1.substring(lastUnderscore + 1);
                comp_id = S1.substring(0, lastUnderscore);
                lastUnderscore = comp_id.lastIndexOf("_");
                parent_comp = comp_id.substring(0, lastUnderscore);



                comp.setComp_id(comp_id);
                comp.setParent_comp(parent_comp);
                comp.setRole_id(role_id);
                comp.setPermission(permission);

                //Persisting component bean .


                    tx.begin();
                    em.persist(comp);
                    tx.commit();

            }
            // if is there, it means checkbox checked
            else {
                out.println(checkboxNamesList[i] + "=checked");

            }

        }

        // resp.setHeader("Refresh", "0; url=/guestbook.jsp");
    }

}

提前致谢。

最佳答案

因为你使用的是 JPA,它会抛出你

org.eclipse.persistence.exceptions

但是你应该捕获SQL Exception 并且你可以从中得到SQL STATE

SQLSTATE 23000 ==> Integrity constraint violation

尝试如下图实现

EntityManager em = EMF.get().createEntityManager();
EntityTransaction tx = em.getTransaction();
try {
   tx.begin();
   em.persist(r);
   tx.commit();
} catch (PersistenceException ex) {
Throwable t = getLastThrowable(ex);  //fetching Internal Exception
SQLException exxx = (SQLException) t;  //casting Throwable object to SQL Exception
System.out.println(exxx.getSQLState());
if(exxx.getSQLState()==23000) // Integrity constraint violation
{
 //Custom Bussiness Logic
}

访问内部异常的方法礼貌 Rupesh Kumar Kushwaha博客

private Throwable getLastThrowable(Exception e) {
Throwable t = null;
for(t = e.getCause(); t.getCause() != null; t = t.getCause());
return t;
} 

希望这有效 :)

关于java.sql.SQLException : Duplicate entry 'sd' for key 'PRIMARY' 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16769819/

相关文章:

jpa - 如何在Spring JpaRepository中使用JPQL选择组中的最新记录?

java - 两个或多个参数的 setParameter 在 Jpa 中不起作用(Mysql 注入(inject))

Java : Load class based on user input

java - Servlet 全局化 NumberFormat.getCurrencyInstance(Locale.JAPAN) 无法正常工作

java - J2SE内置方法的限制

java - 我正在尝试基于 servlet 的应用程序来工作

javascript - CORS 错误 header 允许来源 * http 与 https

java - 使用 hibernate 的一对多和一对一关系

java - 在 onListItemClick() 中启动 Activity

java - 从 XPath 查询中获取空值