Entity with existing table spring data jpa.

huangapple go评论115阅读模式
英文:

Entity with existing table spring data jpa

问题

我有一个已存在的具有6列的表格。我可以创建一个具有自定义列(只有2列)的实体吗?我想要将此实体用于只读模式。

表格:

  1. create table ES_USER_GROUPS
  2. (
  3. group_id NUMBER(9) not null,
  4. alias VARCHAR2(200) not null,
  5. name_es VARCHAR2(200 CHAR) not null,
  6. name_lat VARCHAR2(200 CHAR),
  7. name_en VARCHAR2(200 CHAR),
  8. state VARCHAR2(1) not null
  9. )

实体:

  1. @Data
  2. @Entity
  3. @Table(name = "es_user_groups")
  4. public class UserGroup {
  5. private Integer groupId;
  6. private String alias;
  7. }
英文:

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:

  1. create table ES_USER_GROUPS
  2. (
  3. group_id NUMBER(9) not null,
  4. alias VARCHAR2(200) not null,
  5. name_es VARCHAR2(200 CHAR) not null,
  6. name_lat VARCHAR2(200 CHAR),
  7. name_en VARCHAR2(200 CHAR),
  8. state VARCHAR2(1) not null
  9. )

Entity:

  1. @Data
  2. @Entity
  3. @Table(name = "es_user_groups")
  4. public class UserGroup {
  5. private Integer groupId;
  6. private String alias;
  7. }

答案1

得分: 3

是的,你可以。但是你应该将列设置为只读。

  1. @Data
  2. @Entity
  3. @Table(name = "es_user_groups")
  4. public class UserGroup {
  5. @Id @Column(insertable=false, updateable=false)
  6. private Integer groupId;
  7. @Column(insertable=false, updateable=false)
  8. private String alias;
  9. }
英文:

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

  1. @Data
  2. @Entity
  3. @Table(name = "es_user_groups")
  4. public class UserGroup {
  5. @Id @Column(insertable=false, updateable=false)
  6. private Integer groupId;
  7. @Column(insertable=false, updateable=false)
  8. private String alias;
  9. }

答案2

得分: 2

最干净的方式是使用投影,即一个带有您想要获取和在存储库中使用的字段的类,无需额外的映射:

实体:

  1. @Data
  2. public class UserGroupDTO {
  3. private Integer groupId;
  4. private String alias;
  5. }

存储库:

  1. @Repository
  2. public interface UserGroupRepository extends Repository<UserGroup, Integer> {
  3. List<UserGroupDTO> findAll();
  4. }
英文:

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:

  1. @Data
  2. public class UserGroupDTO {
  3. private Integer groupId;
  4. private String alias;
  5. }

Repository:

  1. @Repository
  2. public interface UserGroupRepository extends Repository&lt;UserGroup, Integer&gt; {
  3. List&lt;UserGroupDTO&gt; findAll();
  4. }

huangapple
  • 本文由 发表于 2020年7月22日 16:59:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/63030544.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定