JPA Entity Without Id

JPA entity without id

I guess your entity_property has a composite key (entity_id, name) where entity_id is a foreign key to entity. If so, you can map it as follows:

@Embeddable
public class EntityPropertyPK {
@Column(name = "name")
private String name;

@ManyToOne
@JoinColumn(name = "entity_id")
private Entity entity;

...
}

@Entity
@Table(name="entity_property")
public class EntityProperty {
@EmbeddedId
private EntityPropertyPK id;

@Column(name = "value")
private String value;

...
}

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

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

Java/Hibernate View Entity without Id

You are missing a field annotated with @Id. JPA requires primary key for each @Entity.

for e.g. define your Entity as below:

@Entity
@Immutable
public class ProductView {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false)
private Long id;

private String name;

@Column(name = "product_code")
private String code;
...
}

Notice the @Immutable annotation and @Column attribute updatable = false. You can also use @EmbeddedId annotation if your view has two or more columns which makes a row unique. See Java Persistence/Identity and Sequencing for more info.

How to use spring Repository without @Id?

JPA requires that every entity has an ID. So no, entity w/o an ID is not allowed.

Every JPA entity must have a primary key.

from JPA spec

You may want to read more about how JPA handles a case when there's no id on the DB side from here (see 'No Primary Key').

How to create a JPA entity for a table that doesn't have a Primary Key or Unique Key column

Let's assume you wanted to change those records with SQL. How would you know which row to update or delete if you don't have a unique column?

Unless you create a unique column, there's nothing you can do about it.

How to create Spring Entity and Repository without primary key

Please see the awnser in this post. This should help you.

PK Explained

Another Option is if this is a join table, than you could make Embeded PK

@Embeddable
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder(toBuilder = true)
public class PersonGroupPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;

@Column(insertable=false,unique = false, updatable=false, nullable=false)
private Long personId;

@Column(insertable=false, unique = false,updatable=false, nullable=false)
private Long groupId;

}


Related Topics



Leave a reply



Submit