Entity with existing table spring data jpa.

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

Entity with existing table spring data jpa

问题

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

表格:

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
)

实体:

@Data
@Entity
@Table(name = "es_user_groups")
public class UserGroup {
    private Integer groupId;
    private String alias;
}
英文:

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

答案1

得分: 3

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

@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;
}
英文:

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

答案2

得分: 2

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

实体:

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

存储库:

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

    List<UserGroupDTO> findAll();

}
英文:

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&lt;UserGroup, Integer&gt; {

    List&lt;UserGroupDTO&gt; findAll();

}

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:

确定