java.sql.SQLException:键“PRIMARY”的重复条目“sd”

java.sql.SQLException:键“PRIMARY”的重复条目“sd”,java,servlets,jpa,persistence,google-cloud-sql,Java,Servlets,Jpa,Persistence,Google Cloud Sql,我正试图在Google cloud SQL中使用JPA持久化这个角色对象。但我不知道如何捕获主键冲突异常并向用户显示适当的消息 这部分代码中的try-and-catch格式化需要帮助吗 这是我的全部servlet代码 package com.example.rolessample; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.util.logg

我正试图在Google cloud SQL中使用JPA持久化这个角色对象。但我不知道如何捕获主键冲突异常并向用户显示适当的消息

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

这是我的全部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异常,并从中获取SQL状态

SQLSTATE 23000==>完整性约束冲突

尝试实现如下所示

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
}
方法访问内部异常日志


希望它能起作用:

因为你使用的是JPA,它会把你扔出去

org.eclipse.persistence.exceptions

但假设您捕获SQL异常,并从中获取SQL状态

SQLSTATE 23000==>完整性约束冲突

尝试实现如下所示

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
}
方法访问内部异常日志

希望这能奏效:

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