Hibernate: so, the identifier field *is* mandatory after all!

Is it obvious to everyone that an identifier is mandatory in Hibernate? I actually thought that Hibernate generated some kind of internal identifier for classes that do not specify one.

The documentation says:

saveOrUpdate() does the following: […] if the object has no identifier property, save() it

That strongly implies that you can have no identifier, right?

In the test that I have written recently, I wanted to keep things as simple as possible. Just a String column in a table.

So my mapping looked like that:

<hibernate-mapping>
  <class name="test.springhibernate.BasicData" table="TestData">
  <property name="name" type="java.lang.String"/>
  </class>
</hibernate-mapping>

Well, too bad. That will get you a “The content of element type “class” must match “(meta*,subselect?,…“. Putting back the identifier fixes this. In fact, it is (sort of) consistent with another comment in the documentation:

If the name attribute [of the <id> tag] is missing, it is assumed that the class has no identifier property.

So, basically, having an<id> tag can mean that there is no identifier! Ooh… now I get it… Well, at least, I am not the only one to find this strange.

Alright, so the mapping becomes (that’s the simplest I could make it)

<hibernate-mapping>
  <class name="test.springhibernate.BasicData" table="TestData">
  <id name="name" type="java.lang.String"/>
  </class>
  </hibernate-mapping>

Similarly, in Hibernate Annotations, you will have to make one of your attributes an identifier.

@Entity
@Table(name = "TestDataAnnotated")
public class AnnotatedBasicData {
  @Id
  private String name;
  public void setName(String name) {
    this.name = name;
  }
  public Object getName() {
    return name;
  }
}

About Eric Lefevre-Ardant

Independent technical consultant.
This entry was posted in hibernate, java. Bookmark the permalink.