简体   繁体   English

没有主键的表的JPA实体

[英]JPA entity for a table without primary key

I have a MySQL table without primary key, and I have to map it into a JPA entity. 我有一个没有主键的MySQL表,我必须将它映射到JPA实体。 I cannot modify the table in any way. 我无法以任何方式修改表格。

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中指定的主键导致任何问题?

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. JPA无法知道它作为PK使用的列是否实际上是数据库中的真实PK。 If those column(s) are, in practice, a PK, then it should be fine. 如果这些列在实践中是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执行查询。

JPA itself doesn't analyze your database. JPA本身不会分析您的数据库。 Just don't use common methods using primary key (find/merge/...) instead use named queries, for example using jpql update syntax. 只是不要使用使用主键的常用方法(find / merge / ...)而是使用命名查询,例如使用jpql update语法。

@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是否为主键无关紧要

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM