簡體   English   中英

如何使用jpa在spring中創建沒有@Id字段的表?

[英]How to create the table without @Id field in spring using jpa?

我正在使用 spring boot 和 jpa 來創建表,但我需要創建沒有@Id主鍵列的表。它沒有讓我在沒有這個 @Id 字段的情況下制作表。 如何使用 spring 數據 jpa 獲得這個?

信函文檔

package com.ashwin.springsecurityangular.model;

import java.io.Serializable;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonIgnore;

@Entity
@Table(name = "letter_doc")
public class LetterDoc implements Serializable {

    private static final long serialVersionUID = 1L;

    @ManyToOne(fetch = FetchType.EAGER, optional = false,cascade=CascadeType.PERSIST)
    @JoinColumn(name = "letterNo")
    @JsonIgnore
    private Letter letter;

    @ManyToOne(fetch = FetchType.EAGER, optional = false,cascade=CascadeType.PERSIST)
    @JoinColumn(name = "documentId")
    @JsonIgnore
    private Document document;

    private String docFile;

//i omitted getters and setters and both constructor
}

它問我 @Id 字段需要。所以有如下錯誤:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: com.ashwin.springsecurityangular.model.LetterDoc

在這張表中,我避免使用 @Id 字段,但它沒有給我。如何實現?

JPA規范清楚地說明了Entity類必須具有唯一的,不變的ID。 但是,您可以嘗試一些技巧。

1)為此維護UUID。

@Id
@Column(columnDefinition = "BINARY(16)")
private UUID uuid;

2)在視圖層中創建數據字段的DTO / POJO表示形式,然后執行SQL Native查詢,然后將結果集映射到您的類

使用 JPA PROJECTIONS在您的情況下,您沒有主鍵,因此請使用 JpaProjections 來獲取您想要的字段,首先將 Entity 聲明為

@Entity @Immutable

設置您的存儲庫

public interface AddressView {
    String getZipCode();
}

然后在存儲庫界面中使用它:

public interface AddressRepository extends Repository<Address, Long> {
      @Query("SELECT ADDRESS from TABLE WHERE address =  ?1")
    AddressView getAddressByState(String state);
}

注意上面的 ADDRESS 實體是一個占位符,只是讓它

Public class ADDRESS{
@Id
Long id;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM