繁体   English   中英

从数据库中获取值作为密钥对

[英]Get values from Database as key pair

我有这个表,我想将不同的值存储为键和值:

@Entity
@Table(name = "wpf_payment_attributes")
public class WpfPaymentAttributes implements Serializable {

    private static final long serialVersionUID = -2629784870868584850L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, updatable = false, nullable = false)
    private int id;

    @Column(length = 255)
    private String name;

    @Column(length = 255)
    private String global_ley;

    @Column(name = "VALUE", columnDefinition = "TEXT", length = 65535)
    private String value;
    ....
}

WpfPaymentAttributes attibutes = new WpfPaymentAttributes();
attibutes.setName("usage");
attibutes.setValue("Test Usage");
attibutes.setGlobal_key(12333);

WpfPaymentAttributes attibutes = new WpfPaymentAttributes();
attibutes.setName("name");
attibutes.setValue("Peter");
attibutes.setGlobal_key(12333);

但是如何使用 JPA 通过一个 SQL 查询获取具有相同全局键的所有值? 问题是我事先不知道表列和值是什么。

我需要得到这个结构:

usage      | name
-------------------
Test Usage | Peter

这可以用 JPA 实现吗?

这是不可能的,因为有些问题 JPA 将无法帮助您:

  • 可能有多个WpfPaymentAttributes值具有相同的全局键和名称(但是,这可以通过使用数据库约束来解决);
  • name列中可能有任意值,因此您必须确保它们实际上映射到您的预期结果结构,没有未知的“名称”等。

如果你不需要一个超级通用的系统,我建议你写一个简单的映射器,它不应该很复杂。 只需通过特定的global_key获取所有WpfPaymentAttributes并应用映射。 例如,这是您需要的结构:

public class Result {
    private String usage;
    private String name;
    // ...
}

进而:

Result result = new Result();
List<WpfPaymentAttributes> attributes = entityManager.createQuery(
    // query should be parameterized
    "select a from WpfPaymentAttributes a where global_key = 12333" 
).getResultList();
for (WpfPaymentAttributes attribute : attributes) {
    String value = attribute.getValue();
    switch(attribute.getName()) {
        case "name":
            result.setName(value);
            break;
        case "usage":
            result.setUsage(value);
            break;
        default:
            throw new IllegalStateException();
    }
} 
return result;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM