I’m using Hibernate 4.0.1.Final with a MySQL 5.5 database. I’m writing a Java console app. In a JUnit test, I’m having trouble getting a test to fail. Here’s my models under test …
@Entity
@Table(name = "ic_domain")
public class Domain {
@Id
@Column(name = "DOMAIN_ID")
private String domainId;
@OneToOne(fetch = FetchType.EAGER, targetEntity = Organization.class)
@JoinColumn(name = "ORGANIZATION_ID")
private Organization org;
and
@Entity
@Table(name = "ic_organization")
public class Organization {
@Id
@Column(name = "ORGANIZATION_ID")
private String organizationId;
My problem is, in my JUnit test, I’m trying to create a foreign key that doesn’t exist, expecting things to fail upon saving, but they never do. Here’s the JUnit test
@Test
public void testSaveDomainWithUnmathcedOrg() {
final Organization org = createDummyOrg();
// Create an org id that doesn't exist.
org.setOrganizationId("ZZZZ");
final Domain domain = new Domain();
final String id = UUID.randomUUID().toString().replace("-", "");
domain.setDomainId(id);
domain.setName(org.getName());
domain.setOrg(org);
m_domainDao.saveOrUpdate(domain);
} // testSaveDomainWithUnmatchedOrg
The code of the DAO is
public void saveOrUpdate(final Domain domain) {
final Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(obj);
} // saveOrUpdate
Shouldn’t things fail at “session.saveOrUpdate”? How do I make them? I don’t want to commit my data in the JUnit test because I don’t want to pollute the underlying database with dummy data, but if that is the only way, so be it.
You don’t have to commit, but you need to flush the session to trigger execution of SQL statements:
Then you can roll the transaction back if you don’t want to pollute the database.