簡體   English   中英

JPA /休眠/春季-主鍵異常

[英]JPA/Hibernate/Spring - Primary key exception

Eclipse拋出一個異常-鍵'PRIMARY'的條目'201805091-1'復制了。 我理解該異常,但是我不理解為什么下面的代碼在我的數據庫中創建了一條新記錄。 我認為應該這樣:如果日期和醫生ID的組合不存在-則使其使用數據庫中當前的組合。 但是顯然一定有什么問題...

非常感謝你 :)

OperationsDate od = null; // these 6 lines of the code may be problematic

        if(em.find(OperationsDate.class, id) != null) {
            od = em.find(OperationsDate.class, id);
        } else {
            od = new OperationsDate(id);
        }

public void process(List<Integer> list, int doctorId, String pin, boolean inf) {
        Patient p = em.find(Patient.class, pin);
        Doctor d = em.find(Doctor.class, doctorId);

        p.addDoctor(d);
        d.addPatient(p);

        int id = countId(doctorId);

        OperationsDate od = null;

        if(em.find(OperationsDate.class, id) != null) {
            od = em.find(OperationsDate.class, id);
        } else {
            od = new OperationsDate(id);
        }

        if(inf) {
            for(int number : list) {
                Medicine m = em.find(Medicine.class, number);

                od.setDoctor(d);
                d.addOperationsDate(od);
                od.addMedicine(m);
                m.addOperationsDate(od);
            }
        } else {
            Operation o = em.find(Operation.class, list.get(0));

            od.setDoctor(d);
            d.addOperationsDate(od);
            od.addOperation(o);
            o.addOperationsDate(od);
        }

    }

public int countId(int doctorId) {
        long millis=System.currentTimeMillis();  
        java.sql.Date date=new java.sql.Date(millis);  

        String id = "";
        String date2 = date.toString();
        for(int i=0; i < date2.length();i++) {
            if(i == 4 || i == 7) {
                continue;
            }
            id += date2.charAt(i);
        }
        id += doctorId;
        int id2 = Integer.parseInt(id);

        return id2;
    }

就像我在評論中告訴您的那樣,然后以這種方式嘗試:

    OperationsDate od = em.find(OperationsDate.class, id);
    if( od == null) {
        od = new OperationsDate(id);
    }
    ...
    // potential persist or merge, depending on your frameworks configuration regarding autocommit and such
    em.persist(od);

如果仍然無法正常工作,請為您的實體添加代碼,以確保沒有任何問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM