Hi, new here hope i achieve a lot :) ... I have two objects [Basket,Product] ... i use ManyToMany annotation mapping.. My Basket class is as follows ...
Code:
@Entity
@Table(name = "BASKET")
@SequenceGenerator(name = "sq_basket",sequenceName = "BASKET_SEQ_ID", initialValue=1)
public class Basket implements java.io.Serializable {
// Fields
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="sq_basket")
@Column(name = "ID")
private Integer entityId;
@Column(name = "REFERENCE")
private String reference;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable( name="PRODUCT_BASKET",joinColumns={@JoinColumn(name="BASKET_ID", referencedColumnName="ID")},
inverseJoinColumns={@JoinColumn(name="PRODUCT_ID", referencedColumnName="ID")})
private Set<Product> products = new HashSet<Product>(0);
............
............
public Set<Product> getProducts() {
return Collections.unmodifiableSet(products);
}
The product class has no Mapping reference to basket class (relationship mapping done on Basket only). Here's how i persist Basket and then load it again to see the persistent data..
Code:
@Test
public void testAddRemoveBasketProducts() {
// Create new Basket
Basket basket = new Basket("201008SN01");
manager.addProduct(basket, "hard-drive", "SANL100HD01", "seagate SATAII", 899.00);
manager.addProduct(basket, "hard-drive", "SANL100HD02", "seagate SATAII", 899.00);
manager.save(basket);
Basket testBasket = manager.getBasket("201008SN01");
// test is data was persistet successfully
assertNotNull(testBasket);
assertEquals(testBasket.getReference(), "201008SN01");
// Lazy load the products
products = testBasket.getProducts();
for (Product product : products) {
assertEquals(product.getName(), "hard-drive");
}
}
And lastly, my DAO ...
Code:
// called by manager.save(basket);
public void save(Basket transientInstance) {
log.debug("saving Basket instance");
try {
getCurrentSession().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
// called by manager.getBasket("201008SN01");
public Basket findBasketByReference(String reference) {
log.debug("finding Basket instance by customer's refence number"
+ ", value: " + reference);
try {
String hql = "from Basket where reference = ?";
Query query = getCurrentSession().createQuery(hql);
query.setMaxResults(1).setString(0, reference);
return (Basket) query.uniqueResult();
} catch (RuntimeException re) {
log.error("find by reference number failed", re);
throw re;
}
}
The following returns null values :( ...
Code:
products = testBasket.getProducts();
Oh, i run this with spring context transaction management