使用Hibernate将嵌套的JSON数据保存到MySQL数据库中

时间:2017-04-19 05:44:59

标签: java mysql json spring hibernate

我对这个问题很感兴趣。我为嵌套的JSON创建了一个POJO,我在MarketPrice对象中获取了数据marketPrices是一个ArrayList,它有两个元素。

这是MarketPrice POJO类,实际上我需要将它保存到MarketPrice表中。即,整个JSON对象。但我有两个实体。怎么可能呢?

MarketPrice.java

@Entity
@Table(name = "MarketPrice")

public class MarketPrice {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "itemId")
private Long itemId;

@Column(name = "analysisDate")
private Date analysisDate;

@Column(name = "marketName")
private String marketName;

@Column(name = "category")
private String category;

@Column(name = "marketPlace")
private String marketPlace;

@Column(name = "state")
private String state;

@Column(name = "district")
private String district;


public ArrayList<Items> marketPrices;

Items.java

public class Items implements Serializable {

    private static final long serialVersionUID = -2428562977284114465L;

    @Id
    @Column(name="id")
    private int id;

    @Column(name = "itemName")
    private String itemName;

    @Column(name = "unitofPrice")
    private String unitofPrice;

    @Column(name = "minimumPrice",columnDefinition = "Float(10,2)")
    private Float minimumPrice;

    @Column(name = "maximumPrice",columnDefinition = "Float(10,2)")
    private Float maximumPrice;

这是我在控制器中从服务器端获取的嵌套JSON数据:

marketPrices

中的JSON数据
{
    "marketPrices": [{
        "itemName": "Mango",
        "unitofPrice": "Kg",
        "minimumPrice": "10",
        "maximumPrice": "20"
    }, {
        "itemName": "Grapes",
        "unitofPrice": "Kg",
        "minimumPrice": "30",
        "maximumPrice": "40"
    }],
    "state": "xyz",
    "district": 4,
    "marketPlace": 5001,
    "marketName": "pmc",
    "category": "Fruits"
}

Controller.java

@RequestMapping(value = {"/saveAnalysis"} , method = RequestMethod.POST,consumes = "application/json")
@ResponseBody
public MarketPrice bulkSaveMarketAnalysis(@RequestBody 
        String marketPrices, HttpServletResponse response,
        HttpServletRequest request) throws JsonProcessingException, IOException, JSONException{

    MarketPrice marketPrice1 = new MarketPrice();
    System.out.println("Json Data"+marketPrices);//here am getting valid nested json from UI
    Gson gson = new Gson();
    MarketPrice marketPrice = gson.fromJson(marketPrices, MarketPrice.class);//converting it into Entity type all values are present in it.
    //Am strucked after this,How to save nested json into DB.

    String marketDataResponse =  analyserService.saveListOfMarketPrice(marketPrice);
    marketPrice1.setStatusMessage("success");
    return marketPrice1;
}

DAO.java

public String saveListOfMarketPrice(MarketPrice marketPrice) {
    System.out.println("In Analyser DAO fro bulk saving");
    final Session session = getSession();
    session.beginTransaction();
    marketPrice.setAnalysisDate(new Date());
    for (Items item : marketPrice.marketPrices) {
       marketPrice.currentItem = item;
       marketPrice.setItemName(marketPrice.currentItem.getItemName());
       marketPrice.setUnitofPrice(marketPrice.currentItem.getUnitofPrice());
       marketPrice.setMinimumPrice(marketPrice.currentItem.getMinimumPrice());
       marketPrice.setMaximumPrice(marketPrice.currentItem.getMaximumPrice());
        session.save(marketPrice);
    }
    session.getTransaction().commit();
    session.close();
    return "success";
}

对DAO进行这些更改后,最终保存了 谢谢。

2 个答案:

答案 0 :(得分:1)

你应该为整个Json ant创建一个更大的实体,它将拥有你的marketPrice对象列表@onetomany。阅读有关该注释的内容。并且还会立即解析您的整个传入对象,而不仅仅是内部的marketPrices列表。您可以在此处阅读如何解析整个对象:GSON parsing without a lot of classes

你需要这样的东西: JsonObject rootObj = parser.parse(json).getAsJsonObject();

然后你应该在实体中描述这个结构:

@Entity
@Data
@Table(name = "your_table")
public class YourEntity{
//you should describe your parameters here too
//of the parsed json. it has other data in it not only the list of `MarketPrices`...


    @OneToMany(mappedBy = "yourEntity",
            cascade = {CascadeType.PERSIST, CascadeType.MERGE},
            fetch = FetchType.LAZY, orphanRemoval = true)
    private List<MarketPrice> prices;

.....

答案 1 :(得分:1)

正如评论中所讨论的,您可以按照以下方式修改代码,使其按预期工作。

<强> MarketPrice.java

@Entity
@Table(name = "MarketPrice")

public class MarketPrice {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "itemId")
private Long itemId;

@Column(name = "analysisDate")
private Date analysisDate;

@Column(name = "marketName")
private String marketName;

@Column(name = "category")
private String category;

@Column(name = "marketPlace")
private String marketPlace;

@Column(name = "state")
private String state;

@Column(name = "district")
private String district;

 @Transient
 public Items currentItem;

@Column(name = "itemName")
public String getItemName() {
    return this.currentItem.itemName;
}

@Column(name = "unitofPrice")
public String getUnitofPrice() {
    return this.currentItem.unitofPrice;
}

@Column(name = "minimumPrice",columnDefinition = "Float(10,2)")
public Float getMinimumPrice() {
    return this.currentItem.minimumPrice;
}

@Column(name = "maximumPrice",columnDefinition = "Float(10,2)")
public Float getMaximumPrice() {
    return this.currentItem.maximumPrice;
}

@Transient
public ArrayList<Items> marketPrices;

<强> Items.java

public class Items implements Serializable {

    private static final long serialVersionUID = -2428562977284114465L;

    @Id
    @Column(name="id")
    private int id;

    public String itemName;

    public String unitofPrice;

    public Float minimumPrice;

    public Float maximumPrice;

<强> DAO.java

public String saveListOfMarketPrice(MarketPrice marketPrice) {
        System.out.println("In Analyser DAO fro bulk saving");
        final Session session = getSession();
        session.beginTransaction();
        for (Items item : marketPrice.marketPrices) {
           marketPrice.currentItem = item;
           session.save(marketPrice);
        }
        session.getTransaction().commit();
        session.close();
        return "success";
    }