KRISTIJAN TOMASINI
KRISTIJAN TOMASINI

Reputation: 459

How to represent table with nulls in Spring Data JPA?

What should I do to represent this table in Spring Data Java Persistence Application Programming Interface (JPA)?

The table is specific because it has no primary key and every column in the table can have nulls, and it is read only.

In entity class I can not simply annotate a single column with @id because there is no column with unique values. I can, of course, create composite virtual primary key in entity class by annotating every column with @id, and that works, but only if there are no nulls in the row. So if I select row(s) with all columns not null then this works. But if one or more columns contains null, Spring is not able to extract that row from table, and instead returns simply null for entire row rather than returning an entity object with only the appropriate field null.

Please do not say "just add id column to the table" because table is read only for us. My company was negotiating for more then a month just to get the read rights to the table! I can not simply add id field in the table.

What else can I do in this case? Other than manually executing a query and extracting the result. Can I somehow fake the id field to make Spring happy? id field is not important for our application, we will never filter the table by id, so it can be whatever makes Spring happy as far as I am concerned.

Upvotes: 2

Views: 1159

Answers (2)

Randy Casburn
Randy Casburn

Reputation: 14165

You can use @EmeddedId with an ID you create. Set the ID field either @Transient or static so it won't affect persistence.

In the below example I use the UUID static method .randomUUID() to generate the ID.

So put this into your @Entity and you will get every row regardless of nulls. Inserts will work just fine too (depending on how you disambiguate your rows).

    @EmbeddedId
    static UUID uuid = UUID.randomUUID();

Upvotes: 1

Jens Schauder
Jens Schauder

Reputation: 81932

I don't think there is a way to do that.

Just get a NamedParameterJdbcTemplate injected and query away.

A central premise of JPA is that you can load data from a bunch of tables, edit the resulting object structure and JPA will take note and mirror the changes to the data in the database. If you don't have anything to use as an id you wouldn't know which row to update. So this whole approach kinda fails to work.

Upvotes: 1

Related Questions