如何在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(' ',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;

}

尽管这样会返回UnkNown column 'Parent2.child_colm'

解决方法

我建议您不要在这里使用@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 annotation用于指定不应保留给定的实体属性。