JPA Many-to-one Relationship

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

JPA Many-to-one Relationship

        

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.

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

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:

To develop the JPA Many-to-One 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:
    • 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`), 
    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: 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");
    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:

    Table child:

    Table parentchild:

     

    Download JPA Annotation Relationship Application