java 没有主键的表的 JPA 实体

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3179105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:42:13  来源:igfitidea点击:

JPA entity for a table without primary key

javajpa

提问by tputkonen

I have a MySQL table without primary key, and I have to map it into a JPA entity. I cannot modify the table in any way.

我有一个没有主键的 MySQL 表,我必须将它映射到一个 JPA 实体中。我无法以任何方式修改表格。

Because entities must have a primary key, I have to specify one. If I'm certain that the field I use as a primary key in the entity (or the fields, should I opt for using composite primary key) will always be unique (and not null) in table, can the fact that the table doesn't have a primary key specified in CREATE TABLE cause any issues?

因为实体必须有一个主键,所以我必须指定一个。如果我确定我在实体中用作主键的字段(或字段,我是否应该选择使用复合主键)在表中将始终是唯一的(而不是 null),表中的事实是否可以在 CREATE TABLE 中没有指定主键会导致任何问题吗?

回答by skaffman

That's correct. JPA has no way of knowing if the column(s) it is using as a PK is actually a real PK in the database. If those column(s) are, in practice, a PK, then it should be fine.

没错。JPA 无法知道它用作 PK 的列是否实际上是数据库中的真实 PK。如果这些列实际上是 PK,那么应该没问题。

You may potentially get some performance problems if the pseudo-PK columns are not correctly indexed, though - JPA will execute queries against the PK on the assumption that it will perform well.

但是,如果伪 PK 列没有正确索引,您可能会遇到一些性能问题 - JPA 将在假设它会执行良好的情况下对 PK 执行查询。

回答by Dewfy

JPA itself doesn't analyze your database. Just don't use common methods using primary key (find/merge/...) instead use named queries, for example using jpql update syntax.

JPA 本身不会分析您的数据库。只是不要使用使用主键 (find/merge/...) 的常用方法,而是使用命名查询,例如使用 jpql 更新语法。

@Entity
@Table(name = "login")
@NamedQueries({
        @NamedQuery(name = "Login.updateLastOnline", 
        query = "UPDATE Login l SET l.lastOnline = :newDate WHERE l.loginId = :loginId")
        })
public class Login implements Serializable
{

It doesn't matter if loginId is primary key

loginId 是否为主键无关紧要