My table requires unique strings (
termname) for each foreign key (
instid). My JUnit test creates two items, then updates one with the
termname of another. I expect it to throw an exception but that only happens after I try to read the data. Only when calling
getListOfTermsByInstId(..) does the
PersistenceException - ConstraintViolationException get thrown. Is there a change I should make to make that happen in
updateTerm(..)?
I am using Java 1.8, Hibernate 4.1.9.Final, Spring 4.0.5.RELEASE.
SQL script:
Code:
CREATE TABLE terms (
Id INTEGER(16) NOT NULL PRIMARY KEY AUTO_INCREMENT,
termname VARCHAR(16) NOT NULL,
instid INTEGER(16),
// other fields
CONSTRAINT fk_terms_instid
FOREIGN KEY (instid) REFERENCES institutions (Id)
ON DELETE RESTRICT
ON UPDATE RESTRICT,
CONSTRAINT uc_terms UNIQUE (instid, termname)
);
repository.java:
Code:
public Integer updateTerm(TermModel termModelIn) {
// omitting exception handling
TermModel termModel = entityManager.find(EntityTermModel.class, termModelIn.getId());
termModel.setTermname(termModelIn.getTermname());
// omitting other fields
entityManager.persist(termModel);
}
JUnit Java code:
Code:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={RepositoryConfiguration.class})
@TransactionConfiguration
@Transactional
...
@Test(expected=EntityExistsException.class)
public void testUpdateTerm_Duplicate()
{
createFirstTerm(imFirstInst.getId());
termService.createTerm(tmFirstTerm);
assertTrue(tmFirstTerm.getId() > 0);
// Create another term with different settings
createFourthTerm(imFirstInst.getId());
termService.createTerm(tmFourthTerm);
assertTrue(tmFourthTerm.getId() > 0);
// Change name to that of another term
tmFirstTerm.setTermname(sFourthTermname);
@SuppressWarnings("unused")
int result = termService.updateTerm(tmFirstTerm);
// TODO Should not get here
@SuppressWarnings("unused")
List<EntityTermModel> altered = termService.getListOfTermsByInstId(imFirstInst.getId());
assertTrue(false);
}