繁体   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