簡體   English   中英

如何使用休眠和Web服務與兩個父母保持實體關系?

[英]How to persist entity with two parents using hibernate and web service?

我具有以下實體結構(A,B,C,D是實體):

A-> one-to-many B, 
A-> one-to-many C,
B-> one-to-many D, 
C-> one-to-many D.

我想使實體A與休眠保持一致,但我正在通過Web服務發送它(消除了循環引用)。 因此,在服務器上,我收到了“了解”孩子的父母,而孩子卻不了解父母,因此我需要再次將所有內容聯系起來。 問題是我需要將D與兩個父對象進行匹配-客戶端上的單個D實例在服務器上變成了兩個實例,這些實例必須合並並且D以前沒有持久化,因此它不包含唯一ID可以匹配的。 我正在考慮兩種解決方案:

1.  Call web service twice – in first call persist Ds and then call it to persist A
2.  XmlIDRef, and XmlID annotations so I don’t have to merge Ds (jaxb will do the job for me) but in that case client will have to generate unique ids for that fields and I wanted to avoid that.

我該怎么辦? 我在正確的軌道上嗎?

順便說一句,我正在使用休眠,cxf和jaxb。

兩種方法都是合理的:

兩次致電網絡服務

一些用戶將消息分成較小的塊,以便僅通過私有方式在一條消息中發送私有數據。 對非私有數據的引用表示為鏈接(這些鏈接指定如何從另一個JAX-RS服務獲取對象)。 然后,您可以使用XmlAdapters來解析鏈接(請參見下文):

import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.adapters.XmlAdapter;

import org.example.product.Product;

public class ProductAdapter  extends XmlAdapter<String, Product>{

    private JAXBContext jaxbContext;

    public ProductAdapter() {
        try {
            jaxbContext = JAXBContext.newInstance(Product.class);
        } catch(JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String marshal(Product v) throws Exception {
        if(null == v) {
            return null;
        }
        return "http://localhost:9999/products/" + v.getId();
    }

    @Override
    public Product unmarshal(String v) throws Exception {
        if(null == v) {
            return null;
        }

        URL url = new URL(v);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/xml");

        Product product = (Product) jaxbContext.createUnmarshaller().unmarshal(connection.getInputStream());
        connection.disconnect();
        return product;
    }

}

@ XmlID / @ XMLIDREF

如果要在一次調用中發送所有數據,並且B和C共享對D實例的引用,則將需要@ XmlID / @ XmlIDREF。 您將需要一個對象來嵌套D的實例。 在這種情況下,在A下比較合適。 以下是我與用戶有關自動執行此操作的線程:

循環引用

MOXy JAXB實現具有用於處理循環關系的擴展。 這是通過@XmlInverseReference批注完成的。 有關更多信息,請參見:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM