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

Viewed 12201

I am using spring boot and jpa to create the table but I need to create table without @Id primary key column.It is not giving me to make the table without this @Id field. How to get this using spring data jpa?

LetterDoc.java

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
}

It ask me the @Id field need.So there is error like:

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

In this table i am avoided to make @Id field but it is not giving me.How to achieve this?

2 Answers

JPA Specification clearly narrates that an Entity class must have a unique, immutable ID. However there are some hacks you can give them a try.

1) Maintain UUID for this purpose.

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

2) Create a DTO/POJO representation of data fields in view layer, then execute a SQL Native query, then map the result set to your class

USE JPA PROJECTIONS In your case you dont have a primary key so use JpaProjections to get the fields you want first declare Entity as

@Entity
@Immutable

set your Repository

public interface AddressView {
    String getZipCode();
}

Then use it in a repository interface:

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

note ADDRESS entity in above is a placeholder just make it

Public class ADDRESS{
@Id
Long id;
Related