开发者

RESTful using Jersey: method to POST multiple entities

I am trying to develop a method in my RESTful web service in Java to insert multiple entries into a MySQL DB using POST request. The generated RESTful Web Service has a method to insert a single entity, but not multiple ones. For example, it accepts:

<creature>
  <sort>Mouse</sort> 
  <n开发者_如何学Pythoname>Pinky</name>
</creature>

But not (what I would like):

<creature>
  <sort>Mouse</sort> 
  <name>Pinky</name>
</creature>
<creature>
  <sort>Elephant</sort> 
  <name>Dumbo</name>
</creature>

I'm guessing that you have to loop through the entities, but not sure how to implement it, being a shameful novice.


Just ran into this myself. I need transactional posts of multiple items, so iterating on the client is out of the question. The consensus seems to be that you need to use a separate path from your normal resources:

http://chasenlehara.com/blog/creating-restful-web-services/ (Multi-resources)

RESTful way to create multiple items in one request

I couldn't find much about how to do this with Jersey, though. As it turns out, it's pretty easy. You should already have multi-entity converter and resource classes for GET requests, you just need to specify a path where the server can assume it's going to receive them:

@Path("creatures")
@Stateless
public class CreaturesResource {

...

    @POST
    @Consumes({"application/xml", "application/json"})
    public Response post(CreatureConverter data) {
       Creature entity = data.resolveEntity(em);
        postCreature(entity);
    }

    @POST @Path("multi")
    @Consumes({"application/xml", "application/json"})
    public Response postMulti(CreaturesConverter data) {
       Collection<Creature> entities = data.getEntities();
       for (Creature c : entities) {
            postCreature(c);
       }
    }

Then instead of posting

<creature />

to

http://.../resources/creatures

You would post

<creatures>
    <creature />
    <creature />
</creatures>

to

http://.../resources/creatures/multi
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜