【问题标题】:Checking whether entity contains primary key or not检查实体是否包含主键
【发布时间】:2021-05-09 13:39:58
【问题描述】:

我想检查我的实体是否包含主键或复合键。如果实体包含主键,则将 isPrimaryKey 设为 true 并在键字符串中输入主键的值,否则为 false,反之亦然。

这是我要返回的示例 JSON:

{
  "data": {
    "identifier": {
      "primaryKeys": {
        "isPrimary": false,
        "keys": ""
      },
      "compositeKeys": {
        "isComposite": true,
        "keys": "compositeKey"
      }
    },
    "rows": [],
    "columns": [
      {
        "createTimeStamp": "2020-09-30T19:00:00.000-05:00",
        "createUserId": "SHOKUMA",
        "lastUpdateTimeStamp": "2020-09-30T19:00:00.000-05:00",
        "lastUpdateUserId": "SHOKUMA",
        "key": {
          "xyz": "DLRHOLD",
          "abc": "010",
          "cde": "LSE",
          "date": "2020-01-01"
        },
        "dteExpn": "01/01/2025",
        "indActive": "Y"
      }
    ]
  }
}

我已经为此创建了一些 pojo:

public class PrimaryKeys{
    public boolean isPrimary;
    public String keys;
}

public class CompositeKeys{
    public boolean isComposite;
    public String keys;
}

public class Identifier{
    public PrimaryKeys primaryKeys;
    public CompositeKeys compositeKeys;
}

public class Key{
    public String xyz;
    public String abc;
    public String cde;
    public String date;
}

public class Column{
    public Date createTimeStamp;
    public String createUserId;
    public Date lastUpdateTimeStamp;
    public String lastUpdateUserId;
    public Key key;
    public String dteExpn;
    public String indActive;
}

public class Data{
    public Identifier identifier;
    public List<Object> rows;
    public List<Column> columns;
}

public class Root{
    public Data data;
}

【问题讨论】:

    标签: java json spring-boot hibernate jackson


    【解决方案1】:
    public boolean hasPrimary() {
        return Arrays.stream(this.getClass().getDeclaredFields())
                .anyMatch(field -> field.isAnnotationPresent(Id.class));
    }
    
    public boolean hasComposite() {
        return Arrays.stream(this.getClass().getDeclaredFields())
                .anyMatch(field -> field.isAnnotationPresent(EmbeddedId.class));
    }
    
    @JsonIgnore
    public String getKey() {
        return hasPrimary()
                ? Arrays.stream(this.getClass().getDeclaredFields())
                        .filter(field -> field.isAnnotationPresent(Id.class)).findFirst().get().getName()
                : Arrays.stream(this.getClass().getDeclaredFields())
                        .filter(field -> field.isAnnotationPresent(EmbeddedId.class)).findFirst().get().getName();
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-07
      • 1970-01-01
      • 1970-01-01
      • 2015-01-30
      • 2021-10-30
      相关资源
      最近更新 更多