Friday, June 4, 2010

JPA One to Many and Many to One easy example

Please follow two previous posting on JPA for basic start
1. JPA getting started, easy example of JPA, JPA annotation example, JPA with Hibernate
2. Configure JPA during run time, dynamic JPA Configuration using Spring context

Now OnetoMany and ManytoOne Example.


Suppose company has many employee. So during saving of company we can save employee also and during fetching company record we can fetch employee records also.

Create one Employee.java

package com.suman;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
* @author Binod Suman
*/

@Entity
@Table(name="blogemployee")
public class Employee {

@Id
private int id;
@Column(name="cid")
private int companyId;
private String name;
private String designation;

@ManyToOne
@JoinColumn(name="cid",nullable=false, insertable=false, updatable=false)
private Company company;
// cid column should be there in company table.
public Employee() { }
public Employee(int companyId, String name, String designation) {
super();
this.companyId = companyId;
this.name = name;
this.designation = designation;
}

public Employee(int id, int companyId, String name, String designation) {
super();
this.id = id;
this.companyId = companyId;
this.name = name;
this.designation = designation;
}

public int getId() {return id;}
public void setId(int id) {this.id = id;}
public int getCompanyId() {return companyId;}
public void setCompanyId(int companyId) {this.companyId = companyId;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public String getDesignation() {return designation;}
public void setDesignation(String designation) {this.designation = designation;}
public Company getCompany() {return company;}
public void setCompany(Company company) {this.company = company;}
}


Company.java

package com.suman;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.apache.log4j.Logger;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.hibernate.annotations.OptimisticLock;

/**
* @author Binod Suman
*/

@Entity
@Table(name="blogcompany")
public class Company {

@Id
private int id;
@Column(name="cname")
private String name;
private String city;

@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "company")
private List employees;
@Transient
Logger log = Logger.getLogger(Company.class);
// Use Transient if you dont want to mapping your java bean to database table column.
public Company(){};
public Company(String name, String city) {
super();
this.name = name;
this.city = city;
}

public Company(int id, String name, String city) {
super();
this.id = id;
this.name = name;
this.city = city;
}

public int getId() {return id;}
public void setId(int id) {this.id = id;}
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 List getEmployees() {return employees;}
public void setEmployees(List employees) {this.employees = employees;}
}


TestApplication.java


package com.suman;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import org.apache.log4j.Logger;

/**
* @author Binod Suman
*/

public class TestApplication {
Logger log = Logger.getLogger(TestApplication.class);
EntityManagerFactory emf;
EntityManager em;

public static void main(String[] args) {
TestApplication test = new TestApplication();
test.configureEntityManager();
// test.saveCompany();
// test.fetchCompanyData();
// test.saveCompanyAndEmployee();
test.fetchCompanyAndEmployee();
}

public void configureEntityManager(){
Map properties = new HashMap();
properties.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
properties.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/sumandb");
properties.put("hibernate.connection.username", "root");
properties.put("hibernate.connection.password", "mysql");
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.show-sql", "true");
properties.put("hibernate.format_sql", "true");
//emf = Persistence.createEntityManagerFactory("jpablogPUnit");
emf = Persistence.createEntityManagerFactory("jpablogPUnit",properties);
em = emf.createEntityManager();
}

public void saveCompany(){
log.info("Company data is going to save");
EntityManager entityManager = (EntityManager) emf.createEntityManager();
entityManager.getTransaction().begin();
Company company = new Company(120,"TecnoTree","Espoo, Finland");
entityManager.persist(company);
entityManager.getTransaction().commit();
log.info("Company data has been saved");
}

public void saveCompanyAndEmployee(){
log.info("Company and Employee data are going to save");
EntityManager entityManager = (EntityManager) emf.createEntityManager();
entityManager.getTransaction().begin();
Company company = new Company(145,"TecnoTree","Finland");
List employees = new ArrayList();
Employee employee = new Employee(10,145,"Binod","Project Manager");
// entityManager.persist(employee);
employees.add(employee);
employee = new Employee(11,145,"Binod Suman","Team Leader");
employees.add(employee);
company.setEmployees(employees);
entityManager.persist(company);
entityManager.getTransaction().commit();
log.info("Company and Employee data have been saved");
}

public void fetchCompanyData(){
Query query = em.createQuery("SELECT c FROM Company c");
List list = (List) query.getResultList();
log.info(list);
for (Company company : list) {
log.info("Company Name :: "+company.getName());
log.info("Company City :: "+company.getCity());
log.info("***************************");
}
}


public void fetchCompanyAndEmployee(){
Query query = em.createQuery("SELECT c FROM Company c");
List list = (List) query.getResultList();
log.info(list);
for (Company company : list) {
log.info("Company Name :: "+company.getName());
log.info("Company City :: "+company.getCity());
log.info("Company Id :: "+company.getId());
List employees = company.getEmployees();
log.info("Employees.size() :: "+employees.size());
for(Employee employee : employees){
log.info("Employee Name :: "+employee.getName());
log.info("Employee Designation :: "+employee.getDesignation());
}
log.info("***************************");
}
}

}

Some time if you have father -> child -> child mapping then it doest not work properly then use this below mapping in father and his child java bean.

@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "company")
@LazyCollection(LazyCollectionOption.FALSE)
private List employees;

If you have question and doubt then please give your comment or if you have any feedback.


Thanks .......... :)

10 comments:

  1. Hello,

    I came upon your tutorial/example after spending close to an hour trying to figure out these mappings.

    This example is perfect - it was exactly what I was looking for and it helped me implement what I was working.

    Thank you!! :)

    ReplyDelete
  2. What if I want to do the following
    select * from company c where c.employeeID=1
    so that I get all employees in a company named X

    ReplyDelete
  3. Thanks for the example. Helped me get a basic JPA one-many relationship working.

    ReplyDelete
  4. Writing busіness аn Executіvе Summaгy foг an Еxiѕtіng
    CompanyEѵery comрany should hаve prονen leadershiр.



    Feel free tо visit my website: http://tempsde.punttic.cat

    ReplyDelete
  5. Very nice one..

    ReplyDelete
  6. Does not work with peresistence.xml

    ReplyDelete
  7. This blog is the general information for the feature. You got a good work for these blog.We have a developing our creative content of this mind.Thank you for this blog. This for very interesting and useful.
    Devops Training courses
    python Training in chennai
    Devops Training in Bangalore

    ReplyDelete
  8. This is quite educational arrange. It has famous breeding about what I rarity to vouch.
    Colossal proverb. This trumpet is a famous tone to nab to troths. Congratulations on a career well achieved.
    This arrange is synchronous s informative impolite festivity to pity. I appreciated what you ok extremely here.


    Selenium interview questions and answers
    Selenium Online training
    Selenium training in Pune
    selenium training in USA
    selenium training in chennai

    ReplyDelete