I am using HQL 4.1.9 to access data in a MySQL 5.1.21 database. There is a table (terms) containing a field (termname) that allow duplicates but expects them to be unique for each foreign key (instid – institution ID). It works when I am creating (term) items but fails when I update one. Do I have to makes changes to my script to get the desired functionality or do I have to code my query to protect the data table?
Part of Create Database 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)
  );
Part of Repository.java
Code:
public Integer updateTerm(TermModel termModelIn) 
{
   int success = 0;
   // removed exception handling
   TermModel termModel = entityManager.find(EntityTermModel.class,termModelIn.getId());
   termModel.setTermname(termModelIn.getTermname());
   // other fields
   entityManager.persist(termModel);
   success = 1;
    return success;
 }
The Junit test creates two terms and the changes the name of one of them to match the other. I expect an exception to be thrown by updateTerm but it does not happen until I execute getListOfTermsByInstId.
Part of JUnit test.java
Quote:
@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);
}