我在处理数据库中的重复条目时遇到问题。我遍历了Google和Stack,但没有找到有效的解决方案。
这是我的代码:
数据库:
DROP TABLE IF EXISTS `batch`;
CREATE TABLE `batch` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`batch_number` int(3) NOT NULL,
`batch_style` varchar(45) DEFAULT NULL,
`batch_name` varchar(45) DEFAULT NULL,
`batch_creation_date` DATE,
PRIMARY KEY (`id`),
UNIQUE KEY(`batch_number`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
LOCK TABLE `batch` WRITE;
POJO:
@Entity
@Table(name="batch")
public class Batch {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="batch_number")
private Integer batchNumber;
@Column(name="batch_style")
private String batchStyle;
@Column(name="batch_name")
private String batchName;
@Column(name="batch_creation_date")
private LocalDate batchCreationDate;
Setters / Getters / Constructors / toString...
控制器(部分):
@Controller
@RequestMapping("/batch")
public class BatchController {
@Autowired
private BatchService batchService;
@Autowired
private MaltService maltService;
@PostMapping("/saveBatch")
public String saveBatch(@Valid @ModelAttribute("batch") Batch theBatch, BindingResult theBindingResult) {
if (theBindingResult.hasErrors()) {
return "batch-form";
}
else {
try {
batchService.saveBatch(theBatch);
return "redirect:/batch/list";
} catch (ConstraintViolationException e) {
theBindingResult.rejectValue("batchNumber", "duplicate", "Invalid number");
return "batch-form";
}
}
}
@GetMapping("/showBatchUpdateForm")
public String showBatchUpdateForm(@RequestParam("batchId") int theId, Model theModel) {
// get batch form our service
Batch theBatch = batchService.getBatch(theId);
// set as a model to prepopulate the form
theModel.addAttribute("batch", theBatch);
return "batch-form";
}
}
接下来,我有DAO和服务。 DaoImpl(部分):
@Repository
public class BatchDAOImpl implements BatchDAO {
@Autowired
private SessionFactory sessionFactory;
@Override
public void saveBatch(Batch theBatch) {
Session currentSession = sessionFactory.getCurrentSession();
currentSession.saveOrUpdate(theBatch);
}
}
问题:
当我编辑记录(即batchNumber = 2
)并保存时,保留原始编号-可以,不会引发任何异常。
当我尝试将batchNumber=2
更改为batchNumber=1
(已取数字)时,出现异常:
java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '1' for key 'batch_number_UNIQUE'
我想补充一点,当我使用相同的方法来防止在另一个实体中重复时,它可以工作,因此在调试数小时后,我不知道这里发生了什么。我可以在github上发布整个代码。
有什么建议吗?
答案 0 :(得分:0)
您正在捕获错误的异常。在您的控制器中,您捕获了org.hibernate.exception.ConstraintViolationException
,但是保存操作抛出了java.sql.SQLIntegrityConstraintViolationException
。因此,基本上,您只需要在控制器中更改捕获的异常即可。