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
@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
public void setEmployees(List
}
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
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
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
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
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
If you have question and doubt then please give your comment or if you have any feedback.
Thanks .......... :)
Hello,
ReplyDeleteI 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!! :)
What if I want to do the following
ReplyDeleteselect * from company c where c.employeeID=1
so that I get all employees in a company named X
Thanks for the example. Helped me get a basic JPA one-many relationship working.
ReplyDeleteWriting busіness аn Executіvе Summaгy foг an Еxiѕtіng
ReplyDeleteCompanyEѵery comрany should hаve prονen leadershiр.
Feel free tо visit my website: http://tempsde.punttic.cat
Very good article
ReplyDeleteJava Training in Chennai
Very nice one..
ReplyDeleteDoes not work with peresistence.xml
ReplyDeleteThis 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.
ReplyDeleteDevops Training courses
python Training in chennai
Devops Training in Bangalore
v Python Online training
ReplyDeletepython Course institute in Chennai
Python Course institute in Bangalore
For Hadoop Training in Bangalore Visit : HadoopTraining in Bangalore
ReplyDeleteThanks for sharing your valuable post and keep doing Looking towards more
ReplyDeleteTo Enhance and Explore the Technical Knowledge's Learn Python
python training in chennai | python training in annanagar | python training in omr | python training in porur | python training in tambaram | python training in velachery
Thanks for sharing such an informative blog.Awaiting for your next update.
ReplyDeleteSelenium Training in chennai | Selenium Training in annanagar | Selenium Training in omr | Selenium Training in porur | Selenium Training in tambaram | Selenium Training in velachery
Thanks for sharing such an informative blog.Awaiting for your next update.
ReplyDeleteAWS training in Chennai
AWS Online Training in Chennai
AWS training in Bangalore
AWS training in Hyderabad
AWS training in Coimbatore
AWS training
ReplyDeleteAwesome blog. Thanks for sharing such a worthy information....
Java Training in Bangalore
Java Classes in Pune
This post is so interactive and informative.keep updating more information...
ReplyDeleteAWS Cloud Technologies
AWS Certified Jobs
replica bags from china free shipping replica bags louis vuitton replica bags in pakistan
ReplyDeleteCockos Reaper 6.70 Crack is a powerful and all-around digital audio composition app that can record from multiple monitors.Reaper License Key Free
ReplyDeletekralbet
ReplyDeletebetpark
tipobet
slot siteleri
kibris bahis siteleri
poker siteleri
bonus veren siteler
mobil ödeme bahis
betmatik
1E1MKQ
شركة كشف تسربات المياه بالاحساء pa6YmIZNiB
ReplyDelete