Issuu on Google+

JPA Many-to-one Relationship

1 of 9

http://www.roseindia.net/jpa/eclipsejpaexamples/jparelationship/many-to...

View Latest Questions and Answers | Ask Questions? | Tutorials

Home

Java

Home

Jpa

Frameworks

Eclipsejpaexamples

Google Advance Search

Database

Jparelationship

Technology

Web Development

Build/Test Tools

Servers

PHP

JPA Many-to-one Relationship

RoseIndia.Net Search Search

JPA Many-to-one Relationship Posted on: June 17, 2009 at 12:00 AM

In this section, you will learn about the many-to-one relationship and how to develop a many-to-one relation in your JPA Application.

JPA Many-to-one Relationship In this section, you will learn about the many-to-one relationship and how to

Malaysia Airlines Sales www.MalaysiaAirlines.com/promotion World's Leading Airline-Luxury For Less.Get Guilt Free Pampering Now! Java Persistence Tools www.myeclipseide.com OpenJPA, Toplink, Hibernate Suppt No Lock-in, Eclipse-Based Dedicated Server Sql YesupHost.com 1TB Bandwidth, 8GB RAM, 100% Uptime Free KVM, Try Risk Free For 7 Days! Shoo-fly Insect Systems www.shoo-fly.com Safely controlling flying insects in barns for over 30 years

Amazing 41MP Camera to hit Indian Market Today

Ask Questions?

Hibernate Framework

Ask your questions, our development team will try to give answers to your questions.

develop a many-to-one relation in your JPA Application.

Tutorial Topics

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

( 836 )

Spring Framework

( 567 )

XML

( 196 )

Ajax

( 528 )

JavaScript

( 109 )

Java

( 1806 )

Web Services

1 Like

( 1057 )

Struts Framework

3,568 people like this. Be the first of your friends.

( 71 )

Database

( 145 )

Technology

( 90 )

Many-to-One: In this relationship many related records in Table-A may have one related record in

Web Development

( 503 )

Table-B.

PHP

( 406 )

Here, we are going to describe the many-to-many relation. The @ManyToOne annotation to provide the many-to-one relation. There are three tables: parent, child and parentchild. Many children have one parent. The parent and child tables are integrated with the parentchild table through the files: parentId and childrenId. In the parentchild table, the one parentId has different childrenId. [Note: If in the database hasn't required table and you run this application then it will automatically create in your database according to your given model class. Otherwise, it only insert the value in your database table.] You see the following image that represents many-to-one relationship:

Malaysia Airlines Promo www.MalaysiaAirlines.com/promotion Fly Asia's Leading Business class Airline.Enjoy Malaysian Hospitality Download Free Fonts Downloads-Fonts.PCWorld.com Download Free Fonts at PCWorld.com. 1,000's of Downloads to Choose From Eclipse EJB IDE www.myeclipseide.com Visual designer, Roundtrip Engine. Direct edit, Export as XMI & More Fly Fishing in Montana www.montanatroutscout.com Top secret streams, blue ribbon rivers, no crowds!

To develop the JPA Many-to-One relation, you need the following files: Database Table:

6/13/2012 3:10 PM


JPA Many-to-one Relationship

2 of 9

http://www.roseindia.net/jpa/eclipsejpaexamples/jparelationship/many-to...

parent child parentchild META-INF => persistence.xml <?xml version="1.0" encoding="UTF-8"?> <persistence> <persistence-unit name="default"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <class>roseindia.Person</class> <class>roseindia.Address</class> <class>roseindia.Parent</class> <class>roseindia.Child</class> <class>roseindia.Author</class> <class>roseindia.Book</class> <properties> <property name="hibernate.connection.url" value="jdbc:mysql://192.168.10.146:3306/hiber <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" <property name="hibernate.connection.password" value="root"/> <property name="hibernate.connection.username" value="root"/> <property name="hibernate.hbm2ddl.auto" value="update"/> <!-- Echo all executed SQL to stdout --> <property name="hibernate.show_sql" value="true"/> </properties> </persistence-unit> </persistence> Model Class: Parent.java Child.java Main Class: ManyToOneRelation.java Database Table: parent CREATE TABLE `parent` ( `id` int(11) NOT NULL auto_increment, `pname` varchar(50) NOT NULL, PRIMARY KEY (`id`) ); child CREATE TABLE `child` ( `id` int(11) NOT NULL auto_increment, `cname` varchar(50) NOT NULL, PRIMARY KEY (`id`) ); parentchild CREATE TABLE `parentchild` ( `parentId` int(11) NOT NULL default '0', `childrenId` int(11) NOT NULL, PRIMARY KEY (`parentId`,`childrenId`), UNIQUE KEY `childrenId` (`childrenId`), KEY `FK9E5C7E72A1A8B75` (`parentId`), KEY `FK9E5C7E725FABE430` (`childrenId`),

6/13/2012 3:10 PM


JPA Many-to-one Relationship

3 of 9

http://www.roseindia.net/jpa/eclipsejpaexamples/jparelationship/many-to...

CONSTRAINT `FK9E5C7E725FABE430` FOREIGN KEY (`childrenId`) REFERENCES `child` (`id`), CONSTRAINT `FK9E5C7E72A1A8B75` FOREIGN KEY (`parentId`) REFERENCES `parent` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 Model Class: Parent.java /** * */ package roseindia;

import java.util.Set;

import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.OneToMany; import javax.persistence.Table;

/** * @author Administrator * */ @Entity @Table(name="parent")

Ads by Google

Persistence Java Java Applet Download Desktop

public class Parent { Ads by Google

@Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="id")

Persistence Java Java Applet Download Desktop

private int id;

/** * @return the id */ public int getId() {

Ads by Google

Persistence Java Java Applet Download Desktop

return id; }

/** * @param id the id to set */ public void setId(int id) { this.id = id; }

@Column(name="pname", nullable=false, length=50, insertable=true) private String pname;

6/13/2012 3:10 PM


JPA Many-to-one Relationship

4 of 9

http://www.roseindia.net/jpa/eclipsejpaexamples/jparelationship/many-to...

/** * @return the pname */ public String getPname() { return pname; }

/** * @param pname the pname to set */ public void setPname(String pname) { this.pname = pname; }

@OneToMany(cascade=CascadeType.ALL) @JoinTable(name = "ParentChild", joinColumns = { @JoinColumn(name="parentId", unique = true) }, inverseJoinColumns = { @JoinColumn(name="childrenId") } ) private Set<Child> children;

/** * @return the children */ public Set<Child> getChildren() { return children; }

/** * @param children the children to set */ public void setChildren(Set<Child> children) { this.children = children; }

} Child.java /** * */ package roseindia;

import java.util.Set;

import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToOne;

6/13/2012 3:10 PM


JPA Many-to-one Relationship

5 of 9

http://www.roseindia.net/jpa/eclipsejpaexamples/jparelationship/many-to...

import javax.persistence.OneToMany; import javax.persistence.Table;

/** * @author Administrator * */ @Entity @Table(name="child") public class Child {

@Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="id") private int id;

/** * @return the id */ public int getId() { return id; }

/** * @param id the id to set */ public void setId(int id) { this.id = id; }

@Column(name="cname", nullable=false, length=50, insertable=true) private String cname;

/** * @return the cname */ public String getCname() { return cname; }

/** * @param cname the cname to set */ public void setCname(String cname) { this.cname = cname; }

@ManyToOne(optional=true) @JoinTable(name = "ParentChild", joinColumns = { @JoinColumn(name="childrenId") }, inverseJoinColumns = { @JoinColumn(name="parentId") }

6/13/2012 3:10 PM


JPA Many-to-one Relationship

6 of 9

http://www.roseindia.net/jpa/eclipsejpaexamples/jparelationship/many-to...

) private Parent parent;

/** * @return the parent */ public Parent getParent() { return parent; }

/** * @param parent the parent to set */ public void setParent(Parent parent) { this.parent = parent; }

} Main Class: ManyToOneRelation.java /** * */ package roseindia;

import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Set;

import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence;

/** * @author Administrator * */ public class ManyToOneRelation {

/** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub

EntityManagerFactory emf=null; EntityManager em=null; try{ emf=Persistence.createEntityManagerFactory("default", new HashMap()); em=emf.createEntityManager(); em.getTransaction().begin(); Child child=new Child(); child.setCname("Tommy"); Child child1=new Child(); child1.setCname("Rocky");

6/13/2012 3:10 PM


JPA Many-to-one Relationship

7 of 9

http://www.roseindia.net/jpa/eclipsejpaexamples/jparelationship/many-to...

HashSet childSet=new HashSet(); childSet.add(child); childSet.add(child1); Parent parent = new Parent(); parent.setPname("Moc"); parent.setChildren(childSet); em.persist(parent);

Parent parentRecord = em.find(Parent.class, parent.getId()); System.out.println("Parent: "+parentRecord.getPname()); Set<Child> parentSet= parentRecord.getChildren(); Iterator it = parentSet.iterator(); while (it.hasNext()){ Child ch = (Child)it.next(); System.out.println("Childs: "+ch.getCname()); }

em.getTransaction().commit(); System.out.println("Done"); } catch(Exception e){ System.out.println(e.getMessage()); } finally{ emf.close(); em.close(); }

}

} Output:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version). log4j:WARN Please initialize the log4j system properly. Hibernate: insert into parent (pname) values (?) Hibernate: insert into child (cname) values (?) Hibernate: insert into child (cname) values (?) Parent: Moc Childs: Tommy Childs: Rocky Hibernate: insert into ParentChild (parentId, childrenId) values (?, ?) Hibernate: insert into ParentChild (parentId, childrenId) values (?, ?) Done

Table parent:

6/13/2012 3:10 PM


JPA Many-to-one Relationship

8 of 9

http://www.roseindia.net/jpa/eclipsejpaexamples/jparelationship/many-to...

Table child:

Table parentchild:

Download JPA Annotation Relationship Application

Malaysia Airlines Experience Asia's Leading Airline Exclusive Promo Fares. Book Now! www.MalaysiaAirlines.com/promotion

Related Tags for JPA Many-to-one Relationship: c, table, io, ip, this, tab, record, records, to, relationship, sh, e, man, in, m, relation, relations, many-to-one, rel, s, at, any, late, is, ha, relate, rds, s, s, rd, th, av, ab, abl, ati, many, on, o

ÂŤPrevious

Ask Questions?

Index

NextÂť

Discuss: JPA Many-to-one Relationship

Post your Comment

6/13/2012 3:10 PM


JPA Many-to-one Relationship

9 of 9

http://www.roseindia.net/jpa/eclipsejpaexamples/jparelationship/many-to...

Your Name (*) :

Your Email :

Subject (*):

Your Comment (*):

SUBMIT

Services Software Solutions

Website Development

Web Promotion Services Content Development

Web Hosting Services

E-Commerce Solutions

JSF Development Outsourcing ERP M-Commerce Flex Development

Web Designing Web Redesigning Web Development Logo Design Web Design Packages Domain Registration

SEO Services Search Eng. Optimization Search Eng. Submission SEO Tips SEO Portfolio Web Promotion Plans

ASP.NET Hosting Unix Hosting E-Commerce Hosting Windows Hosting Hosting Plan

CRM

Home

Content Development Article Writing Blog Writing News Writing SEO Copywriting Technical Documentation Article Marketing

Privacy Policy

Š All Rights are Reserved for Rose India

6/13/2012 3:10 PM


JPA Many-to-one Relationship