【问题标题】:Accessing Table without primary Key -Spring data jpa访问没有主键的表 - Spring data jpa
【发布时间】:2017-03-30 09:27:33
【问题描述】:

我正在使用 spring data jpa,我必须将现有应用程序移植到 Spring boot。

我遇到了没有主键列的数据库表。没有@Id注解怎么写实体。

如果我尝试,我会收到错误:

Caused by: org.hibernate.AnnotationException: No identifier specified for entity: com.example.domain.Employee
    at org.hibernate.cfg.InheritanceState.getElementsToProcess(InheritanceState.java:243) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:775) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3845) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3799) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1412) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1846) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
    ... 29 common frames omitted

有什么方法可以在不修改现有数据库的情况下使用它?

【问题讨论】:

    标签: spring-boot spring-data-jpa


    【解决方案1】:

    是的,使用@IdClass 注释。

    @Entity
    @IdClass(EmployeeKey.class)
    public class Employee {
       @Id
       private int id;
       @Id
       private int departmendId;
    
    }
    
    
    public class EmployeeKey implements Serializable {
       private int id;
       private int departmendId;
    }
    
    
    public interface EmployeeRepository extends JpaRepository<Employee, EmployeeKey>,{}
    

    【讨论】:

      【解决方案2】:

      即使基础表没有明确指定主键,我确信至少有一个列被定义为唯一(或为其指定了唯一索引)。

      您可以将@Id 注释添加到与该列相关的实体字段,这对于持久性提供者来说已经足够了。当然,您可能不想指定任何生成器。

      如果您碰巧有几个唯一列可以形成一种自然键,那么您可以在您的实体中使用@EmbeddedId 策略或@IdClass 策略指定一个复合键。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-17
        • 2014-07-21
        • 2020-03-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多