Transitive persistence + Hibernate

Imagine a one-to-many from Item to Bid (an item may have one or more bids during an auction).

Lets write down the entities (without the constructors and getter/setter methods):


@Entity
@Table(name = "ITEM")
public class Item implements Serializable
{
@Id @GeneratedValue
@Column(name = "ITEM_ID")
private Long id;

@Column(name = "NAME")
private String name;

@OneToMany(mappedBy="item", cascade={CascadeType.ALL})
@Cascade( org.hibernate.annotations.CascadeType.DELETE_ORPHAN )
private Set bids = new HashSet();

public void addBid(Bid bid)
{
if (bid == null)
throw new IllegalArgumentException("Null bid");

bid.setItem(this);
bids.add(bid);
}
}



@Entity
@Table(name = "BID")
public class Bid implements Serializable
{
@Id @GeneratedValue
@Column(name = "BID_ID")
private Long id;

@Column(name = "CREATED")
private Calendar created = Calendar.getInstance();

@ManyToOne(targetEntity = Item.class)
@JoinColumn(name = "ITEM_ID", nullable = false)
@org.hibernate.annotations.ForeignKey(name = "FK_ITEM_ID")
private Item item;
}


In the following code (using Spring DAO's and @Transactional annotation) whenever we save or delete an Item the children Bid entities are also saved or deleted.


public class Tester
{
public static void main(String[] args)
{
Item item = saveToDB();
deleteAl(item);
}

private static void deleteAl(Item item)
{
ClassPathXmlApplicationContext ctx
= new ClassPathXmlApplicationContext("applicationContext.xml");
ItemDAO itemDAO = (ItemDAO) ctx.getBean("ItemDAO");
itemDAO.attachDirty(item);
itemDAO.delete(item);
}

@Transactional
private static Item saveToDB()
{
ClassPathXmlApplicationContext ctx
= new ClassPathXmlApplicationContext("applicationContext.xml");
BidDAO bidDAO = (BidDAO) ctx.getBean("BidDAO");
ItemDAO itemDAO = (ItemDAO) ctx.getBean("ItemDAO");
Item item = new Item();
item.setName("iPod");

Bid aBid = new Bid();
aBid.setCreated(Calendar.getInstance());
item.addBid(aBid);

itemDAO.save(item);
return item;
}
}
0