【问题标题】:Java JPA. Select column from other table using where by other columnJava JPA。使用 where by other column 从其他表中选择列
【发布时间】:2020-08-26 13:33:28
【问题描述】:

我有两张桌子:

create table table_binding (id bigint not null, description varchar(255),primary key (id));

create table table2 (id bigint not null, value clob, type varchar(255));

例如,表格已被下一个值填充:

table_binding:

|---------------------|------------------|
|          ID         |    Description   |
|---------------------|------------------|
|          1          |     Some Desc    |
|---------------------|------------------|
|          2          |    Other Desc    |
|---------------------|------------------|

表2:

|---------------------|------------------|------------------|
|          ID         |       value      |       type       |
|---------------------|------------------|------------------|
|          1          |      VALUE_A     |       TYPE1      | 
|---------------------|------------------|------------------|
|          1          |      VALUE_B     |       TYPE2      | 
|---------------------|------------------|------------------|
|          2          |      VALUE_C     |       TYPE1      | 
|---------------------|------------------|------------------|
|          2          |      VALUE_D     |       TYPE2      | 
|---------------------|------------------|------------------|

我有一个像这样的实体

@Entity(name = "table_binding")
@Data
public class myBinding(){

    @Id
    @GeneratedValue(strategy= GenerationType.SEQUENCE)
    Long id; 
    private String description;
    @Clob
    private String value1;
    @Clob
    private String value2;

}

如何修改实体类代码以使 values1 和 value2 与下一个 sql 查询的返回值相同: 值1:

select value.t2 from table2 t2,table_binding t1 where t2.type="TYPE1" and t2.id=t1.id and t1.id=?

值2:

select value.t2 from table2 t2,table_binding t1 where t2.type="TYPE2" and t2.id=t1.id and t1.id=?

我的意思是 id=1 的 myBinding 实体将是: id =1 ;descripton ="Some Desc"; value1="VALUE_A" ;value2="VALUE_B"

我知道@SecondaryTable 和@Column 注解,但他们不让实现

where t2.type="TYPE1"

【问题讨论】:

    标签: java hibernate jpa entity where-clause


    【解决方案1】:

    实体必须是数据库的忠实表示。

    根据您选择的配置,应用程序不会启动,因为您在实体中指示 TABLE_BINDING 表具有列 VALUE1 和 VALUE2,但实际上它没有。

    您可以做的最好的事情是对两个实体进行建模,每个表都有一个对应的列,并实现一个返回所需数据的查询,或者在两者之间使用 fk,或者使用子查询,或者将两个表添加到从。以及 where 子句的必要条件,以避免笛卡尔积,不涉及实体。

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 2022-10-23
      • 1970-01-01
      • 2021-01-09
      • 2020-03-29
      • 1970-01-01
      • 2014-07-16
      • 1970-01-01
      • 2012-07-29
      相关资源
      最近更新 更多