JPA One-to-Many Relationship

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

JPA One-to-Many Relationship

JPA One-to-Many Relationship

        

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

One-to-Many: In this relationship each record in Table-A may have many related records in Table-B, but each record in Table-B may have only one corresponding record in Table-A.

Here, we are going to describe the one-to-many relation. The @OneToMany annotation to provide the one-to-many relation. There are three tables: parent, child and parentchild. One parent has many children. 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 one-to-many relationship:

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

Database Table:
  • 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/hibernateannotation"/>
<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:
  • OneToManyRelation.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`), 
    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")
    public class Parent {

    @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="pname", nullable=false, length=50, insertable=true)
    private String pname;

    /**
    * @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;
    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")
    }
    )
    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:
  • OneToManyRelation.java
    /**

    */
    package roseindia;

    import java.util.HashMap;
    import java.util.HashSet;

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

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

    /**
    * @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();
    Parent parent = new Parent();
    parent.setPname("Vinod");
    Child child = new Child();
    child.setCname("Monu");
    Child child1 = new Child();
    child1.setCname("Pintu");
    Child child2 = new Child();
    child2.setCname("Sintu");
    HashSet childSet = new HashSet();
    childSet.add(child);
    childSet.add(child1);
    childSet.add(child2);
    parent.setChildren(childSet);
    em.persist(parent);
    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 (?)

Hibernate: insert into child (cname) values (?)

Hibernate: insert into ParentChild (parentId, childrenId) values (?, ?)

Hibernate: insert into ParentChild (parentId, childrenId) values (?, ?)

Hibernate: insert into ParentChild (parentId, childrenId) values (?, ?)

Done

 

Table parent:

Table child:

Table parentchild:

 

Download JPA Annotation Relationship Application