tags:

views:

1105

answers:

3

I have a database view thar yields a result set that has no true primary key. I want to use Hibernate/Persistence to map this result set onto Java objects. Of course, because there is no PK, I cannot decorate any field with @Id.

When deploying, Hibernate complains about the missing @Id. How can I work around this?

A: 

You could check if there is logic wise an id and provide mapping information accordingly. Hibernate will not check the database for existence of a defined primary key.

rudolfson
+4  A: 

For each entity, you must designate at least one of the following:

  • one @Id
  • multiple @Id and an @IdClass (for a composite primary key)
  • @EmbeddedId

so maybe you can create a composite primary key, containing multiple fields?

Fortega
+4  A: 

If there's a combination of columns that makes a row unique, model a primary key class around the combination of columns. If there isn't, you're basically out of luck -- but you should reexamine the design of the view since it probably doesn't make sense.

There are a couple different approaches:

@Entity
public class RegionalArticle implements Serializable {

    @Id
    public RegionalArticlePk getPk() { ... }
}

@Embeddable
public class RegionalArticlePk implements Serializable { ... }

Or:

@Entity
public class RegionalArticle implements Serializable {

    @EmbeddedId
    public RegionalArticlePk getPk() { ... }
}

public class RegionalArticlePk implements Serializable { ... }

The details are here: http://docs.jboss.org/ejb3/app-server/HibernateAnnotations/reference/en/html_single/index.html#d0e1517

Here's an posting that describes a similar issue: http://www.theserverside.com/discussions/thread.tss?thread_id=22638

eqbridges