0

I have a table which is of kind Ledger which records all information with no unique values.

Name Date Statement
First row random data
Second row random data

I am trying to create an Entity which will only fetch name and statement

@Entity
public class MyTable {
  private String name;
  private String statement;

}

As I am not specifing @Id I am getting exception and We don't have any unique identifier in the table I can't mention @Id annotation.

Also, If we need to write any user defined method for getting these values please suggest how to do that as well.Any sources or samples will greatly help here.

Vineel Pellella
  • 332
  • 2
  • 4
  • 20
  • 1
    Not a direct answer, but your SQL table really should have some sort of primary key in it. Once you have it, just map it over to the Java entity and annotate it with `@Id`. – Tim Biegeleisen Mar 07 '22 at 04:31

1 Answers1

-1

As you don't have any unique identifier, you need to define that first. You can do it in two ways:

  1. Redesign the table and identify any column which is unique Or

  2. Declare a Long value as a unique identifier like this[works for mysql, for pg, you need to define a sequence for auto id generation]:

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;

Moreover, to get values, don't forget to add getters setters method for these fields.

user404
  • 1,934
  • 1
  • 16
  • 32
  • The table can't be altered and if I include id which won't be available in the table and might cause different errors. – Vineel Pellella Mar 08 '22 at 09:42
  • you can follow this whole thread or just this answer [JPA entity without id](https://stackoverflow.com/a/3823596/5332914) – user404 Mar 08 '22 at 11:05
  • I followed this but am not sure what should we mention in JpaRepository as we usually mention the Id Type here. Any sample working code can be of great help in understanding how to use it. – Vineel Pellella Mar 09 '22 at 07:40
  • I am not sure but if your `Name` column is unique, you can annotate it as `@Id` and then mention String in your `JpaRepository` like this. – user404 Mar 09 '22 at 07:51
  • As already mentioned nothing in the table are unique. – Vineel Pellella Mar 09 '22 at 08:27
  • May be you missed this: **If your table has no unique columns at all, you can use all of the columns as the Id.** – user404 Mar 09 '22 at 09:28
  • Yup I tried this, Doing this made even worse as every column is now being treated as PK. – Vineel Pellella Mar 09 '22 at 09:34