database - 在遗留数据库 (JPA) 中将空列映射为 0

标签 database jpa null legacy playframework

使用 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/

相关文章:

php - 如何在Mysql中实现Join来获取以下记录

java - 返回带有事件编号的 ID SELECT * 查询

database - 为什么在 Laravel 中表名必须是复数?

java - Spring data jpa未选择所有记录

Objective-C 如何检查字符串是否为空

c++ - 从 C++ 模板返回 NULL

java - 无法读取控制台值 Java

database - AWS EC2 - 从特定域到数据库的安全连接?

Java : Set result set from JPA Paginated Query to custom class

java - JPA 中回滚语句和事务的区别