Database 将旧数据库(JPA)中的空列映射为0
使用游戏!框架和它的JPASupport类,我遇到了遗留数据库的问题 我有以下课程:Database 将旧数据库(JPA)中的空列映射为0,database,jpa,null,legacy,playframework,Database,Jpa,Null,Legacy,Playframework,使用游戏!框架和它的JPASupport类,我遇到了遗留数据库的问题 我有以下课程: @Entity @Table(name="product_catalog") public class ProductCatalog extends JPASupport { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public Integer product_catalog; @OneToOne
@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。如果我将上面的目录作为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;
}
}
}
我看到两种选择:
- 将基本数据类型用作
(即Id
而不是int
)Integer
- 如果您使用Hibernate作为JPA提供程序,请使用
进行转换CustomType