我有两张桌子:
area (
id int PK autoincrement
code varchar
)
products (
id int PK autoincrement
area_id int
)
对象的定义如下:
class Product {
...
@JoinColumn(name = "area_id", referencedColumnName = "id")
@ManyToOne
@Expose
private Area area;
...
}
这很好但我希望该区域是一个字符串,其中包含区域列代码表中使用的代码。
class Product {
...
???
private String area;
...
}
使这项工作的注释应该是什么?
谢谢!
答案 0 :(得分:2)
尝试使用@SecondaryTable和@Column注释的组合。像这样:
@Entity
@SecondaryTable(name="area", pkJoinColumns=@PrimaryKeyJoinColumn(name="id", referencedColumnName="area_id"))
class Product {
...
@Column(name="code", table = "area")
private String code;
...
}
答案 1 :(得分:0)
如果有一些可怜的灵魂有同样的问题,我就是这样做的:
使用变形金刚。因此,字段区域的定义如下:
@Transformation(fetch = FetchType.EAGER, optional = false)
@ReadTransformer(transformerClass = AreaAttributeTransformer.class)
@WriteTransformers({
@WriteTransformer(
transformerClass = AreaFieldTransformer.class,
column = @Column(name = "area_id", nullable = false))
})
@Expose
private String area;
然后这些作品就像这样:
<强> AreaAttributeTransformer 强>
public class AreaAttributeTransformer implements AttributeTransformer {
private AbstractTransformationMapping mapping;
@Override
public void initialize(AbstractTransformationMapping abstractTransformationMapping) {
this.mapping = abstractTransformationMapping;
}
@Override
public Object buildAttributeValue(Record record, Object o, Session session) {
for (DatabaseField field : mapping.getFields()) {
if (field.getName().contains("area_id")) {
EntityManager em = MyEntityManagerFactory.getENTITY_MANAGER_FACTORY().createEntityManager();
List results = em.createNamedQuery("Areas.findById")
.setParameter("id", record.get(field))
.getResultList();
if (results.size() > 0)
return ((Area) results.get(0)).getCode();
}
}
return null;
}
}
<强> AreaFieldTransformer 强>
public class AreaFieldTransformer implements FieldTransformer {
private AbstractTransformationMapping mapping;
@Override
public void initialize(AbstractTransformationMapping abstractTransformationMapping) {
this.mapping = abstractTransformationMapping;
}
@Override
public Object buildFieldValue(Object o, String s, Session session) {
if (o instanceof RouSub) {
EntityManager em = MyEntityManagerFactory.getENTITY_MANAGER_FACTORY().createEntityManager();
List results = em.createNamedQuery("Area.findByCode")
.setParameter("area", ((Area) o).getCode())
.getResultList();
if (results.size() > 0)
return ((Area)results.get(0)).getId();
}
return null;
}
}