英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论