I’m creating a Restfull API Server using Spring 3.1 / Hibernate / Jackson.
I have a ‘Purchase‘ Controller/Model/Dao.
I now need to add the ability to ‘Tag‘ a purchase.
So a simple class with a ‘tagId’ and ‘tagName’ linked back to the ‘Purchase’.
A ‘Purchase’ can have many ‘Tags’, a ‘Tag’ can belong to only one ‘Purchase’.
What is the best way to represent this new ‘Tag’ class I must add? I.e.
- Should I add purchaseId attribute to ‘Tag’ model and annonate it somehow?
- Should I add a ‘Tags List’ attribuate to Purchase’ model?
- Would I create a ‘Tag’ controller that would be a subclass of ‘PurchaseController’?
- Etc…
Essentially, I’m looking for the best practice way to design this using Spring.
Additionally, any suggestions on design patterns I could employ would be welcome.
Maybe the Decorator pattern is applicable here?
All Purchases and Tags must persist to a database of course.
Thanks
Purchase Controller:
@Controller
public class PurchaseController
{
@Autowired
private IPurchaseService purchaseService;
@RequestMapping(value = "purchase", method = RequestMethod.GET)
@ResponseBody
public final List<Purchase> getAll()
{
return purchaseService.getAll();
}
@RequestMapping(value = "purchase/{id}", method = RequestMethod.GET)
@ResponseBody
public final Purchase get(@PathVariable("id") final Long id)
{
return RestPreconditions.checkNotNull(purchaseService.getById(id));
}
@RequestMapping(value = "purchase/tagged", method = RequestMethod.GET)
@ResponseBody
public final List<Purchase> getTagged()
{
return RestPreconditions.checkNotNull(purchaseService.getTagged());
}
@RequestMapping(value = "purchase/pending", method = RequestMethod.GET)
@ResponseBody
public final List<Purchase> getPending()
{
return RestPreconditions.checkNotNull(purchaseService.getPending());
}
@RequestMapping(value = "purchase", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void create(@RequestBody final Purchase entity)
{
RestPreconditions.checkRequestElementNotNull(entity);
purchaseService.addPurchase(entity);
}
}
Purchase Model:
@Entity
@XmlRootElement
public class Purchase implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 6603477834338392140L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Long pan;
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public Long getPan()
{
return pan;
}
public void setPan(Long pan)
{
this.pan = pan;
}
}
Purchase model needs to be modified like below.
and Tag model will look something like below.
You can implement tag specific methods in PurchaseService and PurchaseController, if Purchase owns the relationship(parent) or implement separate service and controller classes for Tag.