简体   繁体   English

具有单向关系的REST API设计

[英]REST API Design with unidirectional relationships

I am trying to build a REST API and am kind of at a loss as how to represent a many to 1 unidirectional relationships. 我正在尝试构建REST API,并且对于如何表示多对1单向关系感到有些困惑。

I have a 4 components that represents the 4 parts of a car (Engine, transmission, wheels, body). 我有4个组件,分别代表汽车的4个部分(引擎,变速箱,车轮,车身)。

Now obviously the component entities don't require a car entity, only the car cares about the components. 现在很明显,零部件实体不需要汽车实体,只有汽车在乎零部件。

What i'm wondering is the best way to handle a REST input of the car resource. 我想知道的是处理汽车资源的REST输入的最佳方法。

1) Should I require a fully completed model to be submitted to the service (eg include a transmission with the full tranmission entity)? 1)我是否需要将完整完成的模型提交给服务(例如,包括具有完整传输实体的传输)?

2) Adjust the data coming in to only accept the ID of the required entity (eg engine_id, transmission_id)? 2)调整输入的数据以仅接受所需实体的ID(例如engine_id,transmission_id)?

I'm a little confused on this and can't really find a good example after googling around. 我对此有些困惑,并且在四处搜寻之后无法真正找到一个很好的例子。

public class Engine
{
    private Integer id;
    // Engine specific stuff
}

public class Transmission
{
    private Integer id;
    // Transmission specific stuff
}

public class Wheels
{
    private Integer id;
    // Wheels specific stuff
}

public class Body
{
    private Integer id;
    // Body specific stuff
}


public class Car
{
    @Id
    private Integer id;

    @ManyToOne
    @JoinColumn(name="engine_id")
    private Engine engine;

    @ManyToOne
    @JoinColumn(name="transmission_id")
    private Transmission transmission;

    @ManyToOne
    @JoinColumn(name="wheels_id")
    private Wheels wheels;

    @ManyToOne
    @JoinColumn(name="body_id")
    private Body body;
}

1) No. Cars obviously belong to your problem domain, and you should treat them as such and identify them. 1)不会。汽车显然属于您的问题领域,您应该这样对待它们并加以识别。 You should also have functionality allowing to retrieve all cars having certain engine_id and so on. 您还应该具有允许检索具有某些engine_id的所有汽车的功能,依此类推。 According to how you state the problem, it is ambiguous if all 4 ids define a car. 根据您陈述问题的方式,如果所有4个ID都定义了一辆汽车,则模棱两可。

2) If I understand your question correctly, yes, ids are a critical part of a REST design. 2)如果我正确理解您的问题,是的,id是REST设计的关键部分。 This doesn't mean that you can't have functionality to display lists of subordinate objects or even searches. 这并不意味着您无法显示下级对象甚至搜索的功能。

Make the user first construct a valid Transmission, Engine, Body, and Wheels. 首先让用户构造有效的变速箱,发动机,车身和车轮。 Then require them to pass in either IDs or URLs to those resources when constructing the Car. 然后要求他们在构造Car时将ID或URL传递给这些资源。

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

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