如何在org.hibernate.annotations.Formula中使用子表列

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

How to use child table column in org.hibernate.annotations.Formula

问题

我需要使用 `@Formula` 来连接父表和子表的某些列
以下是实体类的示例代码

@Entity
@Table(name = "parent1")
public class Parent1 implements Serializable {

  @Id
  private BigInteger id;

  @Column(name = "childId")
  private BigInteger childId;

  @Column(name = "col1")
  private String col1;

  @Column(name = "col2")
  private String col2;

  @Formula("CONCAT_WS(' ', (SELECT p2.child_colm FROM parent2 p2 WHERE p2.childId = childId), col1, col2)")
  private String combinedName;

  @OneToOne
  @JoinColumn(name = "childId")
  private Parent2 parent2;

}

@Entity
@Table(name = "parent2")
public class Parent2 implements Serializable {

  @Id
  @Column(name = "childId")
  private BigInteger childId;

  @Column(name = "child_colm")
  private String child_colm;

}

在这样的情况下,会返回 Unknown column 'Parent2.child_colm' 的错误。

英文:

I need to concat some columns from both parent and child table using @Formula
Here is the Entities

@Entity
@Table(name = "parent1")
public class Parent1 implements Serializable {

  @Id
  private BigInteger id;

  @Column(name = "childId")
  private BigInteger childId;
  
  @Column(name = "col1")
  private String col1;
  
  @Column(name = "col2")
  private String col2;
  
  @Formula("CONCAT_WS(' ',Parent2.child_colm,col1,col2)")
  private String combinedName;
  
  @OneToOne
  @JoinColumn(name = "childId")
  private Parent2 parent2;

}

@Entity
@Table(name = "parent2")
public class Parent2 implements Serializable {

  @Id
  @Column(name = "childId")
  private BigInteger childId;
  
  @Column(name = "child_colm")
  private String child_colm;

}

While giving like this it returns Unknown column 'Parent2.child_colm'

答案1

得分: 1

我建议您不要在这里使用 @Formula,而只需编写以下方法:

import javax.persistence.Transient;

@Entity
@Table(name = "parent1")
public class Parent1 implements Serializable {

   @Transient
   public String getCombinedName() {
      return Stream.of(parent2.child_colm, col1, col2)
          .filter(s -> s != null && !s.isEmpty())
          .collect(Collectors.joining(" "));
   }
}

@Transient 注释 用于指定不应持久化给定的实体属性。

英文:

I would suggest you instead of using @Formula here just write the following method:

import javax.persistence.Transient;

@Entity
@Table(name = "parent1")
public class Parent1 implements Serializable {

   @Transient
   public String getCombinedName() {
      return Stream.of(parent2.child_colm, col1, col2)
          .filter(s -> s != null && !s.isEmpty())
          .collect(Collectors.joining(" "));
   }
}

The @Transient annotation is used to specify that a given entity attribute should not be persisted.

huangapple
  • 本文由 发表于 2020年10月15日 19:19:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64370438.html
匿名

发表评论

匿名网友

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

确定