我有 2 个 A 类和 C 类
@Entity
@Table(name = "A")
public class A
{
private int id;
private String b;
private C c;
// Getters & Setters with @Column annotation
}
public class C
{
private String d;
private String e;
// Getters & Setters ...
public String toString() {...}
public boolean fromString(String serializedC){ ... }
}
和这样的数据库表
CREATE TABLE A
{
INT id NOT NULL,
VARCHAR(64) b,
TEXT c
};
由于 toString() 方法,我想将整个 C 元素存储在 c 列中,并将其从数据库中读取到 fromString() 中。 有什么方法可以通过 hibernate 映射轻松实现吗?
最佳答案
最简单的方法是在类 A 中定义 getter/setter,它们将像这样调用 C.toString() 和 C.fromString():
@Entity
@Table(name = "A")
public class A {
private int id;
private String b;
private C c;
@Id
@Column
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
@Transient
public C getC() {
return c;
}
public void setC(C c) {
this.c = c;
}
@Column
protected String getCAsString() {
return c!=null? c.toString() : null;
}
protected void setCAsString(String c) {
this.c = new C();
this.c.fromString(c);
}
}
注意:使用@Transient 注释标记getC(),因为它不打算映射到任何列。
关于java - Hibernate:将 toString() 类方法映射到 String db 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25760765/