Java JPA/Hibernate/Spring-主键异常
Eclipse向我抛出一个异常-键“PRIMARY”的重复条目“201805091-1”。我理解这个异常,但我不理解为什么下面的代码会在我的数据库中创建一个新记录。我认为这应该是这样的:如果日期和医生id的组合不存在,则使用数据库中当前的组合。但肯定有什么不对劲 非常感谢:)Java JPA/Hibernate/Spring-主键异常,java,spring,hibernate,jpa,jakarta-ee,Java,Spring,Hibernate,Jpa,Jakarta Ee,Eclipse向我抛出一个异常-键“PRIMARY”的重复条目“201805091-1”。我理解这个异常,但我不理解为什么下面的代码会在我的数据库中创建一个新记录。我认为这应该是这样的:如果日期和医生id的组合不存在,则使用数据库中当前的组合。但肯定有什么不对劲 非常感谢:) 操作日期od=null;//这6行代码可能有问题 if(em.find(OperationsDate.class,id)!=null){ od=em.find(operationdate.class,id); }否则{ o
操作日期od=null;//这6行代码可能有问题
if(em.find(OperationsDate.class,id)!=null){
od=em.find(operationdate.class,id);
}否则{
od=新操作日期(id);
}
公共无效进程(列表、int doctorId、字符串pin、布尔inf){
患者p=em.find(患者等级,pin);
博士d=em.find(博士类,博士ID);
p、 助理医生(丁),;
d、 ADD患者(p);
int id=countId(doctorId);
操作日期od=null;
if(em.find(OperationsDate.class,id)!=null){
od=em.find(operationdate.class,id);
}否则{
od=新操作日期(id);
}
如果(inf){
用于(整数编号:列表){
Medicine m=em.find(Medicine.class,number);
医生(丁);;
d、 添加操作日期(od);
od.addMedicine(m);
m、 添加操作日期(od);
}
}否则{
操作o=em.find(Operation.class,list.get(0));
医生(丁);;
d、 添加操作日期(od);
od.ADD操作(o);
o、 添加操作日期(od);
}
}
公共整数countId(整数doctorId){
长毫秒=System.currentTimeMillis();
java.sql.Date日期=新的java.sql.Date(毫秒);
字符串id=“”;
字符串date2=date.toString();
对于(int i=0;i
那么就这样试试吧,正如我在评论中告诉你的:
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);
如果仍然不起作用,请为您的实体添加代码,以确保没有任何问题。好吧,您这样做是在创建一个新的operationdate
实体:od=newoperationdate(id)代码>是否要保留它是另一回事。您的流程
方法是否在事务中?您的问题对结果有点不清楚,是否要创建此实体?顺便说一句,不要调用两次find
方法来获取相同的对象,只需将其直接分配给变量并进行null检查。感谢您的回答:)是的,我的服务层中有@Transactional。我想将一条记录保存到数据库中,以防数据库不包含它。。。
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);