Constraint 1 « Map « JPA Q&A

1. specifying constraint name in hibernate mapping file

I am using Hibernate 3 with Oracle 10. Is there a way to specify in a Hibernate mapping file the constraint names (from foreign keys, unique constraints, etc) that will be created ...

2. If you have a db table with a unique column (like "name"), how would you go about switching the names of two rows? (Using Hibernate, but it sounds like a problem across the board)

Let's say you had a table like this /------------
| id | name |
| 1 | foo    |
| 2 | bar    |
----------- There is a ...

3. Hibernate - renaming objects with a unique constraint

Say you have a bunch of Article objects, with a "title" property. Then there's an ARTICLE table with a TITLE column. The TITLE column has a unique constraint. The UI shows all ...

4. How to retrieve data which caused unique constraint violation (via Hibernate)?

Is there a way to find out which record caused such a violation in Hibernate? Normally you add objects to session and at the end you persist them. If such an error ...

5. Deleting Objects with JPA with Foreign Key Constraints

I have a two classes, Service and Customer, with a many-to-one association from Service to Customer. I want to delete a Customer and any Service that references it. I'm using JPA ...

6. unique constraint check in JPA

I am enforcing a unique constraint check in JPA for userid column which is enforced for all records in the user table.

@Table(name = "user",
       uniqueConstraints ...

7. Any tools or techniques for validating constraints programmatically between databases?

If you had two databases, that had two tables between them that would normally implement a one to one (or many to many) constraint but cannot since they are separate databases, ...

8. JPA remove constraints at run time

I'm deleting entities from a table with a one to many relationship to the same entity (representing node hierarchy). If I make the xincoCoreNodeId relationship a cascade all it works but ...

9. unique constraint check based on a parameter in the parent table

Table User has (userId, scoreType, ...)

@Table(name = "User", uniqueConstraints =
   @UniqueConstraint(columnNames = userId))
-- scoreType could be either points or percentage Table UserScore (id, userId, points, percentage) I would like to ...

10. Hibernate - clearing a collection with all-delete-orphan and then adding to it causes ConstraintViolationException

I have these entities

class Foo{
    Set<Bar> bars;

class Bar{
    Foo parent;
    String localIdentifier;
With this mapping (sorry, no annotations, I'm old fasioned):
<class name="Foo">

11. Hibernate: constraintName is null in MySQL

I have a code using JPA with Hibernate 3.3.x. This Java code can be used with schemas stored either on Oracle 10g or MySQL 5.1.x. Tables are defined with constraints to define unique ...

12. checks for constraint violation before persisting an entity

What is the best mechanism for preventing constraint violation checks before creation | modification of an entity? Suppose if the 'User' entity has 'loginid' as the unique constraint, would it be wise ...

13. Constraint error in hibernate

I am new to hibernate. I am having 2 tables, assume table1 and table2 . table2 has composite key and id column of table2 is referencing id column of table1. I have created one ...

14. Error in hibernate constraint

In my project i m using using hibernate and oracle as DB. I am having two tables with foreign key relationship. In hibernate I m have one-to-many relationship. my one-to-many code set name="classname" cascade="all,all-delete-orphan one-to-many ...

15. Express not trivial constraints in JPA

What is the best way to express range constraint in JPA? I would like to express something like 'this column can only take values between 1..5'. Probably I could use @PrePersist ...

16. Unique Constraint Nhibernate

I have a object with a Nhibernate mapping that has a surrogate ID and a natual ID. Since of cource the natural ID is uniquely constrained a insert query will ...

17. hibernate column uniqueness question

I'm still in the process of learning hibernate/hql and I have a question that's half best practices question/half sanity check. Let's say I have a class A:

public class A

18. Elegantly handling constraint violations in EJB/JPA environment?

I'm working with EJB and JPA on a Glassfish v3 app server. I have an Entity class where I'm forcing one of the fields to be unique with a @Column ...

19. HSQLDB Constraint Violation & SQL Query Log for an HSQLDB in-memory setup

We have a setup where we are using an embedded HSQLDB for backing Hibernate/JPA unit tests in java, and we are using the in-memory database mode since we simply want the ...

20. Foreign Key constraint violation when persisting a many-to-one class

I'm getting an error when trying to persist a many to one entity:

Internal Exception: org.postgresql.util.PSQLException: ERROR: insert or update on table "concept" violates foreign key constraint "concept_concept_class_fk" ...

21. Cannot add or update a child row: a foreign key constraint fails

i am having a user table which has desname as FK referring to des table ,i am trying to add desname in user but i am gettng Cannot add or ...

22. How to properly test for constraint violation in hibernate?

I'm trying to test Hibernate mappings, specifically a unique constraint. My POJO is mapped as follows:

<property name="name" type="string" unique="true" not-null="true" />
What I want to do is to test that I can't ...

23. How to introduce multi-column constraint with JPA annotations?

I am trying to introduce a multi-key constraint on a JPA-mapped entity:

public class InventoryItem {
    private Long id;


24. How to find the entity with the greatest primary key?

I've an entity LearningUnit that has an int primary key. Actually, it has nothing more. Entity Concept has the following relationship with it: @ManyToOne @Size(min=1,max=7) private LearningUnit ...

25. Catching constraint violations in JPA 2.0

Consider the following entity class, used with, for example, EclipseLink 2.0.2 - where the link attribute is not the primary key, but unique nontheless.

public class Profile {  
  @Id ...

26. Hibernate constraint ConstraintViolationException. Is there an easy way to ignore duplicate entries?

Basically I've got the below schema and I'm inserting records if they don't exists. However when it comes to inserting a duplicate it throws and error as I would expect. My ...

27. Grails automatic constraint update

Does grails have an automatic constraint update. If we change the field in domain class to be nullable by adding constraint, it is not getting reflected in database without schema export. ...

28. Unique constraint not created in JPA

I have created the following entity bean, and specified two columns as being unique. Now my problem is that the table is created without the unique constraint, and no errors in ...

29. How to handle EntityExistsException properly?

I have two entities: Question and FavoritesCounter. FavoritesCounter should be created when the question is added to favorites for the first time. Consider a use case when two users tries ...

30. Hibernate triggering constraint violations using orphanRemoval

I'm having trouble with a JPA/Hibernate (3.5.3) setup, where I have an entity, an "Account" class, which has a list of child entities, "Contact" instances. I'm trying to be able to ...

31. Can I name my constraints with JPA?

When I use the maven-hibernate3-plugin (aka hbm2ddl) to generate my database schema, it creates many database constraints with terrifically hard-to-remember constraint names like FK7770538AEE7BC70 . Is there any way to provide a ...

32. Removal of foreign key constraints, Referential integrity and Hibernate

My colleague mentioned that our client DBA proposed the removal of all foreign key constraints in our project Oracle DB schema. Initially I did not agree with the decision. I am ...

33. How to adjust constraints / DB mapping for Map within grails domain class

Following grails domain class:

class MyClass {
  Map myMap
Now for myMap, grails automatically creates a new table for the elements in the map. However if I add elements which are too ...

34. How to choose DDL Primary Key constraint names with JPA/Hibernate

There exists a proprietary hibernate annotation to specify the Foreign Key constraint names that are used at DDL generation time: org.hibernate.annotations.ForeignKey. Is there also a way to specify the Primary Key constraint ...

35. JPA: Problem with persisting Foreign Key Constraint

I got two Entity: Customer Entity

public class Customer {

@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String name;

@OneToMany(mappedBy="customer", cascade=CascadeType.ALL)
private List<Facility> facilities;

//Setter and Getter for name and facilities

public void addFacility(Facility facility){

36. To catch the reason of the unique constraint on JPA

I am trying to learn JPA and I have a problem that I stucked in since 2 days. I have a table named "User" includes id,email,password,username and status. As you guess email ...

37. Multiple unique constraints in JPA

Is there a way to specify using JPA that there should be multiple unique constraints on different sets of columns?

       uniqueConstraints=@UniqueConstraint(columnNames={"code", "uid"}))
public class Person ...

38. How to handle JPA unique constraint violations?

When a unique constraint is violated, a javax.persistence.RollbackException is thrown. But there could be multiple reasons to throw a RollbackException. How can I find out that a unique constraint was violated?

try ...

39. How to specify that a combination of columns should be a unique constraint using annotations?

I want to make sure that all rows in my table have a unique combination of two fields, and I want to specify this using annotations in my entity class. ...

40. Hibernate throws unique constraint violation exception while updating field part of unique key

Below is the use case: I have a unique index defined on 3 columns say A,B,C. Assume the values in them are A1,B1,C1. My java code is adding a new record say A1,B1,C1 ...

41. Hibernate and NonUniqueObjectException

i have an entity that contains two other entities with @ManyToOne relationship.

public class A extends Serializable{

    private Long id;


42. java.sql.SQLException: Cannot add or update a child row: a foreign key constraint fails

Could someone help me understand that why am I getting the following error when I am trying to persist ServiceProvider entity?

java.sql.SQLException: Cannot add or update a child row: a foreign key ...

43. Adding a constraint to a JPA or Hibernate entity column using annotations

I want to have a column for an entity which only accepts one of an enumerated set of values. For example let's say I have a POJO/entity class "Pet" with ...

44. OnDeleteAction cascade fails with constraint violation error

Hibernate 3.3.x

public class User {

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @Cascade(value = DELETE_ORPHAN)

45. Deleting JPA object fails due to foreign key constraints?

Why would the following query fail due to a foreign key constraint? There is no other way for me to delete the associated data that I am aware of.

Query query=em.createQuery("DELETE FROM ...

46. Enforce FK Constraints when JPA inserts inherited objects

I have a multilevel inheritance model in JPA that is using the joined strategy

public class Party implements Serializable{

@DiscriminatorValue(value="PARTY_ORG") // value in party table's PARTY_TYPE column that dictates an Org.
//how children clients ...

47. JPA2 unique constraint: do I really need to flush?

I have a DAO where I need to catch an unique constraint exception. To do this, the only working solution is to flush my EntityManager after the persist. Only then I ...

48. Violation of Unique Key constraint

I am using grails, and I am getting the following when trying to create a new EducationType in my controller

2010-10-26 17:14:49,405 [http-8080-1] ERROR util.JDBCExceptionReporter  - Violation of UNIQUE KEY constraint ...

49. Hibernate - unique column constraint being ignored

I have a MySQL table to hold tags (i.e. like those used here on Stack Overflow). It simply has an id (pk) and a tag column to hold the tag itself. The ...

50. JPQL and date comparison (constraint in the query)

My Application model object contains a date field (time stamp):

@Table(name = "MYTABLE")
public class Application {

   private Date timeStamp;
I'm trying to construct a JPQL query that would ...

51. Foreign key constraint's by eclipselink auto generated name starts with number

I have a problem. My Table's NAME is A295SOMETHING. Eclipselink generates a name starting with a number: 295SMTHG. How can I specify Eclipselink to use an other constraint name?

52. JPA ManyToMany constraints

I am new to JPA, so apologies if this is a very basic problem. I have an application where a user can vote on a product (range 0 to 10), but can ...

53. Integrity constraint violation

Using the Play! Framework, i have the following two models:

public class User extends Model {
    public String firstName;
    public String lastName;
    public ...

54. Using unique constraint on Hibernate JPA2

How could I be able to implement my unique constraints on the hibernate POJO's? assuming the database doesn't contain any. I have seen the unique attribute in @column() annotation but I ...

55. How do I map Hibernate collections with Oracle's NOT NULL column constraint enforced?

I have 2 tables, ENQUIRY and ELEMENT with a One-to-Many relationship such that an Enquiry has many Elements. I would like to enforce Oracle's NOT NULL constraint on foreign key column ...

56. BatchUpdateException - MySQL Error 'Duplicate entry' - which key/constraint has been violated?

The combo mysql/hibernate is creating exception stack traces like

Caused by: java.sql.BatchUpdateException: Duplicate entry '7872551600-B1310955127' for key 2
at com.mysql.jdbc.ServerPreparedStatement.executeBatch( at org.jboss.resource.adapter.jdbc.WrappedStatement.executeBatch( at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch( at ...

57. Hibernate non-negative value constraint

I have the table, the snippet below.

    package test;

    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import ...

58. Reverse engineering check constraints & indexes w/ Hibernate?

I've been tasked with reverse engineering Hibernate mappings from a large, legacy, sql server database. The database makes extensive use of check constraints (several per table) and indexes, and while ...

59. Find or insert based on unique key with Hibernate

I'm trying to write a method that will return a Hibernate object based on a unique but non-primary key. If the entity already exists in the database I want to ...

60. Does JPA support annotations (or xml tags declarations) for declaring a constraint like ON DELETE (set null, cascade, ...)?

I've used JPA to create a database, more exactly the hibernate implementation of JPA. But anyway, at first, my question is related to JPA. Let's do a scenario. I have two ...

61. Hibernate and JPA: how to make a foreign key constraint on a String

I am using Hibernate and JPA. If I have two simple entities:

@Table(name = "container")
public class Container {
  private String guid;

public class Item {

62. Testing validation constraints

The Hibernate Validator documentation has a simple Getting Started guide which outlines testing validation rules. The relevant chunk is

public void manufacturerIsNull() {
    Car car = new Car(null, ...

63. "Not in" constraint using JPA criteria

I am trying to write a "NOT IN" constraint using JPA Criteria. Ive tried something like this -

though i know it will not work. In the above syntax, how can i add ...

64. Best way to prevent unique constraint violations with JPA

I have an Keyword and a KeywordType as entities. There are lots of keywords of few types.

When trying to persist the second keyword of a type, the unique constraint is ...

65. Foreign Key Constraint Issues Involving One-To-Many and Many-To-One Relationship in EcliplseLink2.1.2

I'm encountering a 1452 error on MySQL 5.5.9 while running some JPA tutorial code that I pulled off the EclipseLink website (, and I'm hoping someone has some insight. I'm using ...

66. Do i need to make sql tables using constraint to work with hibernate

I am using hibernate annotations with spring MVC. Now i always create table using GUI editor like SQLYOG or phpmyadmin. So i just create table with columns and even if i have some ...

67. Force Hibernate to issue DELETEs prior to INSERTs to avoid unique constraint violations?

Background: Our table is:

There is a Primary key constraint on BOND_PAYMENT_ID, and a Unique constraint on (BOND_NUMBER, PAYMENT_ID). The application uses Hibernate, and allows a user to ...

68. Best practices for handling unique constraint violation at UI level

While working in my application i came across a situation in which there are likely chances to Unque Constraints Violation.I have following options

  1. Catch the exception and throw it back to UI
  2. At ...

69. How to ensure unique constraint is applied on multiple columns (mm_book_id and mm_author_id )?

I would like to know if anyone has ideas on how to ensure if in the join table mm_author_books, how to make sure the columns (mm_book_id and mm_author_id) are unique? For instance, ...

70. groovy + jpa + maven = loader constraint violation for javax/xml/transform/Source

if I create a JPA EntityManager from a groovy script I get these error:

java.lang.LinkageError: loader constraint violation: loader (instance of <bootloader>) previously initiated loading for a different type with name ...

71. Suppressing a constraint annotation

Suppose, I have a domain object that contains a field with an UNIQUE constraint annotation defined by me. Now, I added a new entity of this object by a form to ...

72. Hibernate date field with a unique constraint on the day

I'm currently implementing a historical report store where users will store only 1 report per day. We're trying to apply unique contraints but we're struggling as the created date goes down ...

73. Controlling DDL generation in Toplink Essentials

I am having some trouble with the DDL generation of Toplink Essentials. I am developing a Glassfish 2.1 based application and use JPA for persistence. I have an object graph where ...

74. A foreign key constraint violation in postgres that shouldn't be happening, as far as I can tell. (w/ hibernate)

So I have two tables:

table A
-other stuff

table B
-a_id, a fk column to id in A
in hibernate, I've mapped B.a_id as a simple property (I don't want a many-to-one and get an ...

75. Need assistance with uncanny, reproducible MySQL ERROR 1452 (23000) Foreign Key Constraint

MySQL select version() is 5.5.9 on Mac OS/X 10.6 Question When I execute the sql script below, I encounter a very perplexing foreign key constraint error. It seems as though it should not ...

76. Hibernate:Cannot add or update a child row: a foreign key constraint fails

this error gives me when i try to insert (save) an user using hibernate:

DROP TABLE IF EXISTS `bytecodete`.`account_confirmation`;
CREATE TABLE  `bytecodete`.`account_confirmation` (
  `email` varchar(255) ...

77. Hibernate :Cannot add or update a child row: a foreign key constraint fails

i have this issue :

Cannot add or update a child row: a foreign key constraint fails (bytecodete.company_links, CONSTRAINT FK_company_links_1 FOREIGN KEY (id) REFERENCES company ...

78. one-to-one mapping using unique constraint not working as expected

I'm trying this simple uni-directional one-to-one relationship Person ----> Address using many-to-one mapping with unique constraint. This is how my mapping looks like in Person.hbm.xml:

<class name="Person" table="PERSON">
<many-to-one name="address" column="ADDRESS_ID" cascade="all" not-null="true" unique="true"/>
I think ...

79. hibernate 3.6.3 - ORA-00001: unique constraint with save and merge

public void saveBook(final Book book) {

    final User u = this.sessionFactory.getCurrentSession().merge(book.getUser());

    // .... some mroe code
I have spring webflow and spring ...

80. Hibernate + Oracle, strange null constraint violation with primitive type

I just add a new column on an entity and a strange thing is happening. The entity was previously:

int publishedDayNb;

public int getPublishedDayNb() {
    return publishedDayNb;

public void setPublishedDayNb(int publishedDayNb) {

81. JPA: constraints violation on delete

I have three entities -

public class ApplicationEntity extends ModelEntity implements Application {
    @ManyToOne(fetch = FetchType.LAZY, optional = false, cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    private CategoryEntity ...

82. JPA unique constraint validation

How to validate Multiple column unique constraint in JPA entity. Is there any Hibernate validator for this purpose. I have added @UniqueConstraint annotation. But it is not doing any validation.And I ...

83. hibernate unique constraint

I was faced with the below problem problem P:S Have a look at the commnets :) on the above link And while solving it, I now have a question about how the unique ...

84. Hibernate Natural ID duplicate issue

I'm new to Hibernate and DBs in general, so pardon the elementary question. I am working with the DIS protocol and specifically the Open-DIS implementation of DIS. In DIS, ...

85. em.merge doesn't generate update statement

I'm using JPA 2.0 and hibernate in the project and faced the problem: em.merge() doesn't generate the update statement. The detail situation is: I have an entity, which is successfully persisted. It has ...

86. How to write a custom constraint to check that atleast one boolean field in a class is true

I have a class called "Scheduler" which has 7 Boolean fields. I want to write a constraint in hibernate to check that at-least one boolean field is true. Here is the "Scheduler" ...

87. Hibernate: A foreign key constraint fails

The following are the SQL statements generated by Hibernate

Hibernate: insert into HOSPITAL_ADDRESS (DOOR_NO, STREET, REFERENCE_LANDMARK, HASH) values (?, ?, ?, ?)
Hibernate: insert into PHONE_NUMBER (AREA_CODE, NUMBER, HASH) values (?, ?, ?)
Hibernate: ...

88. Is it possible to configure the Play Framework's CRUD module to respect @Column(unique=true) annotations?

I'm using Play's CRUD module to create a simple set of admin screens. One of my models is User and I want to enforce a unique constraint on the email ...

89. Is it possible to define an XOR constraint using JPA?

I need to define an XOR constraint on an entity using JPA i.e. a constraint that specifies that you can have a value in either column A or column B but ...

90. Setting unique constraint on all referenced collection members in hibernate

imagine you have a Hibernate/JPA entity class Text which may be annotated with multiple members of class Tag - how would you ensure that Text entity exist only once for a ...

91. JPA/hibernate - Cannot add or update a child row: a foreign key constraint fails - BUT record exists

I'm having a strange problem. I have some records in the database: Company

  • id = 1, Name = Microsoft
  • id = 2, Name = Sun
Now I have another entity, Event which has a ...

92. hibernate support for deferred constraints?

In Hibernate 3.6, what is the support for deferred constraints? As I get it, in 3.2, "Hibernate does not have support for deferred constraints." (from

93. Setting a constraint for all properties of a domain object?

Is there a way to set a constraint for all properties of a grails domain object? I want to set nullable: true for a class, essentially.

94. JPA: Partial contraint

I need something like a partial contraint for one of my entities.

public class MyEntity 
  private String name;

  @ManyToOne @NotNull
  private Type type;
Only for a sinlge ...

95. Hibernate annotation Cascade problem

I have a Java class that contains a list of another class.

@Entity public class Country {

private Long id;
private List<Hotel> hotels;

public void setId(Long id) { = id;

@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="COUNTRY_SEQ")
@SequenceGenerator(name="COUNTRY_SEQ", sequenceName="COUNTRY_SEQ", allocationSize=1)
public Long ...

96. JPA - defining multi-column unique constraints

Is it possible using JPA to define multiple unique constraints.

class Foo {
    long id;

     String name;

     MyEnum type;

} should be ...

97. Duplicate key value violates unique constraint

i am using hibernate, Getting following exception.

ERROR: duplicate key value violates unique constraint "tablename"
  Detail: Key (pkey)=(11929) already exists.
2011-07-18 06:28:04,373 ERROR [org.hibernate.event.def.AbstractFlushingEventListener] (http- Could not synchronize database state with session: ...

98. Hibernate oracle integrity constraint violated

I got a problem mapping oracle by hibernate I got these classes


    import java.util.HashSet;
    import java.util.Set;
    import ...

99. Hibernate order of [update, delete] on collection is breaking a DB constraint. How to fix?

Hibernate is causing pain merging an object that contains an ordered collection when removing an element from the middle of the collection. Some background: I'm working on a tool that produces CSV ...

100. How do I express this constraint with JPA?

I have a class that looks like this:

public enum Scope {
  A, B, C...

public class User {


    Scope scope; // enum, see above