Re: EJB3 Newbie & Persistence



Mat wrote:
... wrote:

hi,

i'm trying to get a parent/child relationship going. The parent & "child" is in 2 different entities.

When I add a parent with 2 children it writes to the db fine. The problem is when I write the parent and one child then try to add a second child straight after. The second one doesn't get written.

From what I can see JBoss/EJB3 is supposed to write/update the second child as soon as it leaves the function, but it appears that it doesn't. From what I can tell, JBoss (or the client) doesn't report an error.

Is there something else I need to do such as do a find on the parent before I add the 2nd child even though the parent still exists ?

tia
Frustrated newbie


It depends which one (parent or child) you update.
In the @OneToMany annotation, you have the "mappedBy" attribute that defines which entity will manage the persistence of the relationship.
Please post your code so it will be easier to find the problem.


Mat
hi Mat,

heres the source, theres some rubbish in there so just ignore that :-)

Andrew
package com.meerkat.jfr.par;

import java.io.Serializable;

import javax.persistence.CascadeType;
import javax.persistence.GeneratorType;
import javax.persistence.Id;
import javax.persistence.Entity;
import javax.persistence.Column;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import static javax.persistence.FetchType.*;

/*import javax.persistence.JoinColumn;*/


/**
 * @ejb.bean name="Store"
 *           display-name="Store"
 *           description="Store Class"
 *           jndi-name="ejb/Store"
 *           type="CMP"
 *           cmp-version="1.x"
 *           view-type="local"
 */
@NamedQueries({
	@NamedQuery(name="findAllStores", queryString="FROM StoreCMP s")	
	})

@Entity
@Table(name = "STORE")
public class StoreCMP implements Serializable 
{
	private Long id;
	private String name;
	private String code;
	private String street;
	private String city;
	private String state;
	private String country;
	private String postcode;
	private String phone;

	CustomerCMP customer;

	public StoreCMP()
	{
	}

	@Id(generate = GeneratorType.AUTO)
	@Column(name="StoreId", nullable=false)
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}

/*	@OneToOne(cascade = {CascadeType.ALL}, fetch=EAGER)
	@JoinColumn(name = "ADDRESSID")
	public AddressCMP getAddress() {
		return address;
	}
	public void setAddress(AddressCMP address) {
		this.address = address;
	}
*/	
	@Column(name="CODE")
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	@Column(name="NAME")
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getCountry() {
		return country;
	}
	public void setCountry(String country) {
		this.country = country;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getPostcode() {
		return postcode;
	}
	public void setPostcode(String postcode) {
		this.postcode = postcode;
	}
	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}
	public String getStreet() {
		return street;
	}
	public void setStreet(String street) {
		this.street = street;
	}
	
	@ManyToOne(cascade={CascadeType.ALL})
	@JoinColumn(name="customerId", nullable=false)
	public CustomerCMP getCustomer()
	{
		return customer;
	}
	public void setCustomer(CustomerCMP customer)
	{
		this.customer = customer;
}
}
package com.meerkat.jfr.par;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.*;


@NamedQueries
({
	@NamedQuery(name="findAllCustomers", queryString="from CustomerCMP c")
//	@NamedQuery(name="findCustomer", queryString="from CustomerCMP c where c.CName =:cname")
})

@Entity
@Table(name = "CUSTOMER")
public class CustomerCMP implements java.io.Serializable{

	private Long id;
	private String name;
	private String contact;
	private String street;
	private String city;
	private String state;
	private String country;
	private String postcode;
	private String phone;
	List<StoreCMP> StoreList;

	public CustomerCMP(){} 

	@Id(generate = GeneratorType.AUTO)
	@Column(name = "customerId", nullable = false)
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	
	@Column(name="NAME")
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	@Column(name="CONTACT")
	public String getContact() {
		return contact;
	}
	public void setContact(String contact) {
		this.contact = contact;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getPostcode() {
		return postcode;
	}

	public void setPostcode(String postcode) {
		this.postcode = postcode;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getStreet() {
		return street;
	}

	public void setStreet(String street) {
		this.street = street;
	}

	@OneToMany(targetEntity=StoreCMP.class, 
				cascade={CascadeType.ALL}, 
				fetch=FetchType.EAGER, 
				mappedBy="customer")	
	@OrderBy("code")
	public List<StoreCMP> getStoreList()
	{
		if (this.StoreList == null)
			this.StoreList = new ArrayList<StoreCMP>();
		return StoreList;
	}
	public void setStoreList(List<StoreCMP> StoreList)
	{
		this.StoreList = StoreList;
	}

	public StoreCMP addToStoreList(StoreCMP store)
	{
		if (this.StoreList == null)
			this.StoreList = new ArrayList<StoreCMP>();
		store.setCustomer(this);
		StoreList.add(store);
		return store;
	}
	public StoreCMP removeFromStoreList(StoreCMP store)
	{
		getStoreList().remove(store);
		store.setCustomer(null);
		return store;
	}
}
package com.meerkat.jfr.ejb;

import java.util.List;

import javax.ejb.Remote;

import com.meerkat.jfr.par.*;

@Remote
public interface Customer {

	public CustomerCMP addCustomer(String Name, String Contact);
	public CustomerCMP addCustomer(CustomerCMP cust);
	public CustomerCMP addCustomer(CustomerCMP cust, Address addrs);
	public List getCustomer(String Name);
	public CustomerCMP getCustomer(Long key);
	public List getCustomers();
 	public StoreCMP addStore(String Name, String Code);
	public StoreCMP addCustomerStore(CustomerCMP newcust, StoreCMP Store);

}
package com.meerkat.jfr.ejb;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.FlushMode;
import javax.persistence.FlushModeType;
import javax.persistence.PersistenceContext;
import javax.transaction.Transaction;

import org.jboss.aspects.Current;
import org.jboss.aspects.tx.Tx;

import com.meerkat.jfr.par.CustomerCMP;
import com.meerkat.jfr.par.StoreCMP;

@Stateless
public class CustomerBean implements Customer {

	@PersistenceContext(unitName = "cust")
	private EntityManager em;
	@Current Transaction tx;
	
	public CustomerCMP addCustomer(CustomerCMP cust)
	{
		if (cust.getStoreList() == null)
			;
		em.persist(cust);
		em.flush();
		return cust;
	}
	public CustomerCMP addCustomer(CustomerCMP cust, Address addrs)
	{
		// Set up address details
		cust.setCity(addrs.getCity());
		cust.setCountry(addrs.getCountry());
		cust.setPhone(addrs.getPhone());
		cust.setPostcode(addrs.getPostcode());
		cust.setState(addrs.getState());
		cust.setStreet(addrs.getStreet());
		
		return this.addCustomer(cust);
	}

	public CustomerCMP addCustomer(String Name, String Contact)
	{
		CustomerCMP Customer = new CustomerCMP();
		Customer.setName(Name);
		Customer.setContact(Contact);
		em.persist(Customer);
		return Customer;
	}
	public StoreCMP addCustomerStore(CustomerCMP newcust, StoreCMP Store)
	{
		newcust.addToStoreList(Store);
		em.flush();
		return Store;
	}
	public List getCustomer(String user)
	{
		return  em.createQuery("from CustomerCMP c where c.name = :user")
				.setParameter("user",user)
				.getResultList();
//		return (CustomerCMP) em.createNamedQuery("findCustomer").setParameter("cname", Name)
//						.getSingleResult();
	}
	public CustomerCMP getCustomer(Long key)
	{
		return em.find(CustomerCMP.class, key);
	}
	public List getCustomers()
	{
		return em.createNamedQuery("findAllCustomers").getResultList();
//		return em.createQuery("from CustomerCMP c").getResultList(); 	
	}
	public StoreCMP addStore(String Name, String Code) {
		StoreCMP store = null;
		store = new StoreCMP();
		store.setName(Name);
		store.setCode(Code);
		em.persist(store);
		return store;
	}
}
package client;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.naming.InitialContext;

import com.meerkat.jfr.ejb.Address;
import com.meerkat.jfr.ejb.Customer;
import com.meerkat.jfr.par.CustomerCMP;
import com.meerkat.jfr.par.StoreCMP;

/**
 * @ejb.bean name="Client"
 *           display-name="Name for Client"
 *           description="Description for Client"
 *           jndi-name="ejb/Client"
 *           type="Stateless"
 *           view-type="both"
 */
public class Client {
    protected static Customer cust;

    	   public static void main(String[] args) throws Exception
		   {
		      System.out.println("Start");
		      InitialContext ctx = new InitialContext();
		      System.out.println("Got Initial Context");
		      cust = (Customer) ctx.lookup(Customer.class.getName());

		      loadDataBase();
//		      getOneCust();
		      getOneCustList();
		      getCustList();
		   }
		  private static void loadDataBase() 
		  {
			  CustomerCMP newcust = null;
			  Address newAdd = null;
		      StoreCMP newstore = null;
		      StoreCMP newstore2 = null;
			  
		      System.out.println("Adding");
		      
		      newcust = new CustomerCMP();
		      newcust.setName("Andrew");
		      newcust.setContact("Angela");
		      
	    	  newAdd = new Address();
		      newAdd.setCity("Hoppers Crossing");
		      newAdd.setCountry("Australia");
		      newAdd.setPhone("555-3333");
		      newAdd.setPostcode("3333");
		      newAdd.setState("VIC");
		      newAdd.setStreet("My Street");
		      newcust = cust.addCustomer(newcust);
		      
		      System.out.println("Adding2");
		      cust.addCustomer("ANdrew1", "Angela1");
		      System.out.println("Adding3");
		      cust.addCustomer("ANdrew2", "Angela2");
		      System.out.println("Adding4");
		      cust.addCustomer("ANdrew3", "Angela3");
		      
		      System.out.println("Adding Store");
		      newAdd.setPhone("555-4444");
		      newAdd.setPostcode("4444");
		      
// Customer details
		      CustomerCMP stcust = new CustomerCMP();
		      stcust.setName("ANdrews");
		      stcust.setContact("Angelas");
//  			  stcust.setAddress(newAdd);
  	
//  		    Store details
		      newstore = new StoreCMP();
		      newstore.setName("Highpoint");
		      newstore.setCode("HIGH");
		      newstore.setCity(newAdd.getCity());
		      newstore.setCountry(newAdd.getCountry());
		      newstore.setPhone(newAdd.getPhone());
		      newstore.setPostcode(newAdd.getPostcode());
		      newstore.setState(newAdd.getState());
		      newstore.setStreet(newAdd.getStreet());
		      stcust.addToStoreList(newstore);
		      
//			  cust.addCustomerStore(stcust, newstore);
//		      stcust.addToStoreList(newstore);
			  stcust = cust.addCustomer(stcust);
		      
		      newstore2 = new StoreCMP();
		      newstore2.setName("Werribee");
		      newstore2.setCode("Werr");
		      newstore2.setCity(newAdd.getCity());
		      newstore2.setCountry(newAdd.getCountry());
		      newstore2.setPhone(newAdd.getPhone());
		      newstore2.setPostcode(newAdd.getPostcode());
		      newstore2.setState(newAdd.getState());
		      newstore2.setStreet(newAdd.getStreet());

//			  cust.addCustomerStore(stcust, newstore2);
		      stcust = cust.getCustomer(stcust.getId());
			  cust.addCustomerStore(stcust, newstore2);
//		      stcust.addToStoreList(newstore2);

		      System.out.println("Added");
		  }
/*		private static void getOneCust() 
		  {
			  CustomerCMP cust1 = null;
			  
			  System.out.println("Getting");
		      cust1 = cust.getCustomer("Andrew");
		      System.out.printf("%s %s\r\n", cust1.getName(), cust1.getContact());
		      System.out.println("done");
		  }
*/
		  private static void getOneCustList()
		  {
		      CustomerCMP custList = null;
		      StoreCMP storeme = null;

		      System.out.println("One Cust List");
		      List rc = cust.getCustomer("ANdrews");
		      for (Iterator iter = rc.iterator(); iter.hasNext();)
		      {
		    	  custList = (CustomerCMP)iter.next();	
		    	  System.out.printf("%s %s\r\n", custList.getName(), custList.getContact());
		    	  List <StoreCMP> storelist = custList.getStoreList(); 
			      for (Iterator iter2 = storelist.iterator(); iter2.hasNext();)
			      {
			    	   storeme = (StoreCMP)iter2.next();
			    	   System.out.printf("Store1 : %s %s\r\n", storeme.getName(), storeme.getCode()); 
			      }
		      }
		  }
		  private static void getCustList()
		  {
		      CustomerCMP custList = null;
		      StoreCMP storeme = null;

		      System.out.println("CustList");
		      List rc = cust.getCustomers();
		      for (Iterator iter = rc.iterator(); iter.hasNext();)
		      {
		    	   custList = (CustomerCMP)iter.next();
 		    	   System.out.printf("%s %s %s\r\n", custList.getName(), custList.getContact(), 
					    	  custList.getPostcode());
		    	  List <StoreCMP> storelist = custList.getStoreList(); 
			      for (Iterator iter2 = storelist.iterator(); iter2.hasNext();)
			      {
			    	   storeme = (StoreCMP)iter2.next();
			    	   System.out.printf("Store : %s %s %s\r\n", storeme.getName(), storeme.getCode(), storeme.getCity()); 
			      }
		      }
		  }
}


Relevant Pages

  • Trying to understand interfaces
    ... have a class that implements an interface and I need to add functionality to ... private string m_message; ... private string m_sharpenedMessage; ... public void OnSharpened() ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Trying to understand interfaces
    ... if I have a class that implements an interface and I need to add ... private string m_message; ... private string m_sharpenedMessage; ... public void OnSharpened() ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: BinaryFormatter.Deserialize
    ... >> While I haven't taken the time to run the code, I can see that there> is>> nothing in your class that requires custom serialization. ... >>> private string DNIS; ... >>> public void GetObjectData(SerializationInfo info, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Help compiling castor ibm java example
    ... private String artist = null; ... public void setArtist{ ...
    (comp.lang.java.programmer)
  • Re: Is there a limit to the size or complexity of JPanels paintComponent method?
    ... double actualnorthextent, actualsouthextent, actualwestextent, ... public void movemapdown() ... public double convertstringcoordinatetodouble(String coord) ... return screencoords; ...
    (comp.lang.java.gui)