开发者

Spring MVC + JPA - Binding/Updating Associated Entities

Some of this question is related to JPA, but it's more about approaches than technology so hopefully someone will be able to offer advice.

I'm using Spring MVC and Hibernate to power a website that allows users to create products, and product descriptions. I have a Product entity, which has a bidirectional one-to-many relationship with ProductDescription.

If when submitting a form that binds to an instance of Product, and specifies all of its ProductDescriptions, then a malicious use开发者_StackOverflow中文版r could enter bogus IDs for the ProductDescriptions and 'hijack' other users' data. One solution to this would be to always create the ProductDescriptions anew, so delete them when the form is submitted, and create new ones each time. This seems inefficient because of the extra delete and write operations that would be needed every time the Product is updated (even if the ProductDesciptions haven't changed).

Another alternative would be to check 'ownership' of the child entities before running an update.

How do other people get around this issue? Do most people do delete/insert, or selective update?

Here's an example of the sort of POST submission I'm talking about:

id=1
name=My Product
descriptions[0].id=123
descriptions[0].text=A lovely description of my product
descriptions[0].price=100
descriptions[1].id=123
descriptions[1].text=Another lovely description of my product in another language
descriptions[1].price=50

And an example of the kind of class I'm talking about:

public class Product
{
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private Integer id;
   @OneToMany(mappedBy = "product")
   private Set<ProductDescription> descriptions;
   private String name;
}


public class ProductDescription
{
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private Integer id;
   private Integer price;
   @ManyToOne
   private Product product;
   private String text;
}


If you are inclined to add security to your application I would advise using spring security and with that you could check in the servlet if the user is the owner of that product before updating it's values.

That's how we have done so far here. wastes a little bit of resources with that checking in server side but using post, only advanced users can try that by changing the response header, so I don't think it's happens a lot.

Without security you could try to use a session to validate the user, but the problem with that is that if the session is gone nobody can change the product.

Cheers


Have you considered using Data Transfer Objects (DTOs)? That way you could pass DTOs rather than entity objects to an intermediate layer and therein you will be able to execute several checks.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜