本文介绍了没有@Id 的休眠/持久性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据库视图,它生成的结果集没有真正的主键.我想使用 Hibernate/Persistence 将此结果集映射到 Java 对象.当然,因为没有PK,我不能用@Id来装饰任何字段.

I have a database view that 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.

在部署时,Hibernate 会抱怨缺少 @Id.我该如何解决这个问题?

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

推荐答案

如果存在使行唯一的列组合,请围绕列组合建模主键类.如果没有,那么您基本上是走运了——但您应该重新检查视图的设计,因为它可能没有意义.

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.

有几种不同的方法:

@Entity
public class RegionalArticle implements Serializable {

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

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

或者:

@Entity
public class RegionalArticle implements Serializable {

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

public class RegionalArticlePk implements Serializable { ... }

详情在这里:http://docs.jboss.org/ejb3/app-server/HibernateAnnotations/reference/en/html_single/index.html#d0e1517

这是一个描述类似问题的帖子:http://www.theserverside.com/discussions/thread.tss?thread_id=22638

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

这篇关于没有@Id 的休眠/持久性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 08:54