0

I have a existing table with 6 columns. Can I create entity with custom columns (only 2)? I want to use this entity in a read-only mode.

table:

create table ES_USER_GROUPS
(
  group_id NUMBER(9) not null,
  alias    VARCHAR2(200) not null,
  name_es  VARCHAR2(200 CHAR) not null,
  name_lat  VARCHAR2(200 CHAR),
  name_en  VARCHAR2(200 CHAR),
  state    VARCHAR2(1) not null
)

Entity:

@Data
@Entity
@Table(name = "es_user_groups")
public class UserGroup {
    private Integer groupId;
    private String alias;
}
Andronicus
  • 25,419
  • 17
  • 47
  • 88
qwerty
  • 87
  • 2
  • 8

2 Answers2

3

Yes you can. But you should set the columns read-only.

@Data
@Entity
@Table(name = "es_user_groups")
public class UserGroup {
    @Id @Column(insertable=false, updateable=false)
    private Integer groupId;
    @Column(insertable=false, updateable=false)
    private String alias;
}
Simon Martinelli
  • 34,053
  • 5
  • 48
  • 82
2

The cleanest way would be to use a projection, i.e. a class with fields you want to fetch and use it in your repository, no additional mapping is needed:

Entity:

@Data
public class UserGroupDTO {
    private Integer groupId;
    private String alias;
}

Repository:

@Repository 
public interface UserGroupRepository extends Repository<UserGroup, Integer> {

    List<UserGroupDTO> findAll();

}
Andronicus
  • 25,419
  • 17
  • 47
  • 88
  • Thanks. And can I use relationships as if I were working with a full table? – qwerty Jul 22 '20 at 09:14
  • @qwerty I'm not sure, if not, interface projections should do the trick. Here you can find more on that topic: https://stackoverflow.com/questions/55371737/how-to-handle-spring-boot-spring-data-projections-with-entity-relationships-ne – Andronicus Jul 22 '20 at 09:16
  • No you can't. If you need to load a graph use my solution – Simon Martinelli Jul 22 '20 at 10:04
  • What dou you mean by "graph"? Want to say, I can use the relationship without any restrictions? – qwerty Jul 22 '20 at 13:10