qwerty
qwerty

Reputation: 101

Entity with existing table spring data jpa

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;
}

Upvotes: 0

Views: 4607

Answers (2)

Andronicus
Andronicus

Reputation: 26026

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();

}

Upvotes: 2

Simon Martinelli
Simon Martinelli

Reputation: 36103

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;
}

Upvotes: 3

Related Questions