Search code examples
javasqlspring-boothibernatespring-data-jpa

Entity object with only some of the fields in the database table


I have an SQL database table Employee. On this Employee table, there are 10+ columns.

We only need 2 (say employeeId and lastname) of those 10+ columns. The rest of them just don’t any interest us and they sure won’t anytime soon.

Is there a way to form the entity only with these 2 columns and go from there—only the relevant find..() methods in repository? ( We’ll only be needing the derived find..() methods in repository )

How to do this? I’m guessing this is possible. Setting it up just to blindly try. I could use info/suggestions/reference if possible. Couldn’t find a ref as of now. There’s Extract only certain fields using CrudRepository?, but it doesn’t answer the “partial entity class”—one w/some but not all the fields of the database table.

TIA.


Solution

  • Yes, you can use the entity class with some fields only. As long as you are not creating a schema from the entity. You can use it for reading from table. Of course you will get only fields defined in it.

    You can even write the entity to the database but in this case the other fields will not be changed.