使用 Play !框架和它的 JPASupport 类我遇到了遗留数据库的问题。
我有以下类(class):
@Entity
@Table(name="product_catalog")
public class ProductCatalog extends JPASupport {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer product_catalog;
@OneToOne
@JoinColumn(name="upper_catalog")
public ProductCatalog upper_catalog;
public String name;
}
一些产品目录没有上层目录,这在遗留数据库中被引用为 0。如果我将 upper_catalog 提供为 NULL,那么 JPA 会向该数据库列插入一个 NULL 值。 如何在写入数据库时将空值强制为 0,而在从数据库中读取时强制将空值设为 0?
最佳答案
我没有看到任何直接使用 JPA 实现您想要的东西的简单方法(并且很有可能即使您找到了一种适用于基本操作(如保存或加载)的方法,但它不适用于更复杂的操作用例,如复杂条件/hql、非标准获取模式等)
所以我会这样做:
@Entity
@Table(name="product_catalog")
public class ProductCatalog extends JPASupport {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer product_catalog;
@Column(name="upper_catalog")
public Long upper_catalog_id;
public String name;
public ProductCatalog getUpperCatalog() {
if (upper_catalog_id == 0)
return null;
return ProductCatalog.findById(upper_catalog_id);
}
public void setUpperCatalog(ProductCatalog pc) {
if (pc == null) {
upper_catalog_id = 0;
}
else {
if (pc.id == null) {
// option 1. a bit like a cascade
pc.save();
// option 2. if you consider passing a transient entity is not valid
throw new RuntimeException("transient entity " + pc.toString());
}
upper_catalog_id = pc.id;
}
}
}
关于database - 在遗留数据库 (JPA) 中将空列映射为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2987864/