Hibernate – Many-to-Many example – join table + extra column (Annotation)

In this tutorial, we show you how to use Hibernate to implements “many-to-many table relationship, with extra column in the join table“.

Note
For many to many relationship with NO extra column in the join table, please refer to this @many-to-many tutorial

1. Many-to-many table + extra columns in join table

The STOCK and CATEGORY many to many relationship is linked with a third / join table named STOCK_CATEGORY, with extra “created_by” and “created_date” columns.

many to many diagram

MySQL table script

CREATE TABLE `stock` (
  `STOCK_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `STOCK_CODE` VARCHAR(10) NOT NULL,
  `STOCK_NAME` VARCHAR(20) NOT NULL,
  PRIMARY KEY (`STOCK_ID`) USING BTREE,
  UNIQUE KEY `UNI_STOCK_NAME` (`STOCK_NAME`),
  UNIQUE KEY `UNI_STOCK_ID` (`STOCK_CODE`) USING BTREE
)
 
CREATE TABLE `category` (
  `CATEGORY_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `NAME` VARCHAR(10) NOT NULL,
  `DESC` VARCHAR(255) NOT NULL,
  PRIMARY KEY (`CATEGORY_ID`) USING BTREE
)
 
CREATE TABLE  `stock_category` (
  `STOCK_ID` INT(10) UNSIGNED NOT NULL,
  `CATEGORY_ID` INT(10) UNSIGNED NOT NULL,
  `CREATED_DATE` DATE NOT NULL,
  `CREATED_BY` VARCHAR(10) NOT NULL,
  PRIMARY KEY (`STOCK_ID`,`CATEGORY_ID`),
  CONSTRAINT `FK_CATEGORY_ID` FOREIGN KEY (`CATEGORY_ID`) 
             REFERENCES `category` (`CATEGORY_ID`),
  CONSTRAINT `FK_STOCK_ID` FOREIGN KEY (`STOCK_ID`) 
             REFERENCES `stock` (`STOCK_ID`)
)

2. Project Structure

Review the file project structure of this tutorial.

many to many project folder

3. Hibernate / JPA Annotation

The Hibernate / JBoss tools generated annotation codes are not working in this third table extra column scenario. To make it works, you should customize the code to use “@AssociationOverride“, in StockCategory.java to represent the many to many relationship.

See following customized codes :

File : Stock.java

package com.mkyong.stock;
 
import java.util.HashSet;
import java.util.Set;
 
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
 
@Entity
@Table(name = "stock", catalog = "mkyongdb", uniqueConstraints = {
		@UniqueConstraint(columnNames = "STOCK_NAME"),
		@UniqueConstraint(columnNames = "STOCK_CODE") })
public class Stock implements java.io.Serializable {
 
	private Integer stockId;
	private String stockCode;
	private String stockName;
	private Set<StockCategory> stockCategories = new HashSet<StockCategory>(0);
 
	public Stock() {
	}
 
	public Stock(String stockCode, String stockName) {
		this.stockCode = stockCode;
		this.stockName = stockName;
	}
 
	public Stock(String stockCode, String stockName,
			Set<StockCategory> stockCategories) {
		this.stockCode = stockCode;
		this.stockName = stockName;
		this.stockCategories = stockCategories;
	}
 
	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "STOCK_ID", unique = true, nullable = false)
	public Integer getStockId() {
		return this.stockId;
	}
 
	public void setStockId(Integer stockId) {
		this.stockId = stockId;
	}
 
	@Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10)
	public String getStockCode() {
		return this.stockCode;
	}
 
	public void setStockCode(String stockCode) {
		this.stockCode = stockCode;
	}
 
	@Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20)
	public String getStockName() {
		return this.stockName;
	}
 
	public void setStockName(String stockName) {
		this.stockName = stockName;
	}
 
	@OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.stock", cascade=CascadeType.ALL)
	public Set<StockCategory> getStockCategories() {
		return this.stockCategories;
	}
 
	public void setStockCategories(Set<StockCategory> stockCategories) {
		this.stockCategories = stockCategories;
	}
 
}

File : StockCategory.java

package com.mkyong.stock;
 
import java.util.Date;
 
import javax.persistence.AssociationOverride;
import javax.persistence.AssociationOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
 
@Entity
@Table(name = "stock_category", catalog = "mkyongdb")
@AssociationOverrides({
		@AssociationOverride(name = "pk.stock", 
			joinColumns = @JoinColumn(name = "STOCK_ID")),
		@AssociationOverride(name = "pk.category", 
			joinColumns = @JoinColumn(name = "CATEGORY_ID")) })
public class StockCategory implements java.io.Serializable {
 
	private StockCategoryId pk = new StockCategoryId();
	private Date createdDate;
	private String createdBy;
 
	public StockCategory() {
	}
 
	@EmbeddedId
	public StockCategoryId getPk() {
		return pk;
	}
 
	public void setPk(StockCategoryId pk) {
		this.pk = pk;
	}
 
	@Transient
	public Stock getStock() {
		return getPk().getStock();
	}
 
	public void setStock(Stock stock) {
		getPk().setStock(stock);
	}
 
	@Transient
	public Category getCategory() {
		return getPk().getCategory();
	}
 
	public void setCategory(Category category) {
		getPk().setCategory(category);
	}
 
	@Temporal(TemporalType.DATE)
	@Column(name = "CREATED_DATE", nullable = false, length = 10)
	public Date getCreatedDate() {
		return this.createdDate;
	}
 
	public void setCreatedDate(Date createdDate) {
		this.createdDate = createdDate;
	}
 
	@Column(name = "CREATED_BY", nullable = false, length = 10)
	public String getCreatedBy() {
		return this.createdBy;
	}
 
	public void setCreatedBy(String createdBy) {
		this.createdBy = createdBy;
	}
 
	public boolean equals(Object o) {
		if (this == o)
			return true;
		if (o == null || getClass() != o.getClass())
			return false;
 
		StockCategory that = (StockCategory) o;
 
		if (getPk() != null ? !getPk().equals(that.getPk())
				: that.getPk() != null)
			return false;
 
		return true;
	}
 
	public int hashCode() {
		return (getPk() != null ? getPk().hashCode() : 0);
	}
}

File : StockCategoryId.java

package com.mkyong.stock;
 
import javax.persistence.Embeddable;
import javax.persistence.ManyToOne;
 
@Embeddable
public class StockCategoryId implements java.io.Serializable {
 
	private Stock stock;
    private Category category;
 
	@ManyToOne
	public Stock getStock() {
		return stock;
	}
 
	public void setStock(Stock stock) {
		this.stock = stock;
	}
 
	@ManyToOne
	public Category getCategory() {
		return category;
	}
 
	public void setCategory(Category category) {
		this.category = category;
	}
 
	public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
 
        StockCategoryId that = (StockCategoryId) o;
 
        if (stock != null ? !stock.equals(that.stock) : that.stock != null) return false;
        if (category != null ? !category.equals(that.category) : that.category != null)
            return false;
 
        return true;
    }
 
    public int hashCode() {
        int result;
        result = (stock != null ? stock.hashCode() : 0);
        result = 31 * result + (category != null ? category.hashCode() : 0);
        return result;
    }
 
}

File : Category.java

package com.mkyong.stock;
 
import java.util.HashSet;
import java.util.Set;
 
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
 
@Entity
@Table(name = "category", catalog = "mkyongdb")
public class Category implements java.io.Serializable {
 
	private Integer categoryId;
	private String name;
	private String desc;
	private Set<StockCategory> stockCategories = new HashSet<StockCategory>(0);
 
	public Category() {
	}
 
	public Category(String name, String desc) {
		this.name = name;
		this.desc = desc;
	}
 
	public Category(String name, String desc, Set<StockCategory> stockCategories) {
		this.name = name;
		this.desc = desc;
		this.stockCategories = stockCategories;
	}
 
	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "CATEGORY_ID", unique = true, nullable = false)
	public Integer getCategoryId() {
		return this.categoryId;
	}
 
	public void setCategoryId(Integer categoryId) {
		this.categoryId = categoryId;
	}
 
	@Column(name = "NAME", nullable = false, length = 10)
	public String getName() {
		return this.name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	@Column(name = "[DESC]", nullable = false)
	public String getDesc() {
		return this.desc;
	}
 
	public void setDesc(String desc) {
		this.desc = desc;
	}
 
	@OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.category")
	public Set<StockCategory> getStockCategories() {
		return this.stockCategories;
	}
 
	public void setStockCategories(Set<StockCategory> stockCategories) {
		this.stockCategories = stockCategories;
	}
 
}

Done, the many to many relationship should be working now.

4. Run it – Case 1

For a new category and a new stock.

    session.beginTransaction();
 
    Stock stock = new Stock();
    stock.setStockCode("7052");
    stock.setStockName("PADINI");
 
    Category category1 = new Category("CONSUMER", "CONSUMER COMPANY");
    //new category, need save to get the id first
    session.save(category1);
 
    StockCategory stockCategory = new StockCategory();
    stockCategory.setStock(stock);
    stockCategory.setCategory(category1);
    stockCategory.setCreatedDate(new Date()); //extra column
    stockCategory.setCreatedBy("system"); //extra column
 
    stock.getStockCategories().add(stockCategory);
 
    session.save(stock);
 
    session.getTransaction().commit();

Output…

Hibernate: 
    INSERT 
    INTO
        mkyongdb.category
        (`DESC`, NAME) 
    VALUES
        (?, ?)
Hibernate: 
    INSERT 
    INTO
        mkyongdb.stock
        (STOCK_CODE, STOCK_NAME) 
    VALUES
        (?, ?)
Hibernate: 
    SELECT
        stockcateg_.CATEGORY_ID,
        stockcateg_.STOCK_ID,
        stockcateg_.CREATED_BY AS CREATED1_2_,
        stockcateg_.CREATED_DATE AS CREATED2_2_ 
    FROM
        mkyongdb.stock_category stockcateg_ 
    WHERE
        stockcateg_.CATEGORY_ID=? 
        AND stockcateg_.STOCK_ID=?
Hibernate: 
    INSERT 
    INTO
        mkyongdb.stock_category
        (CREATED_BY, CREATED_DATE, CATEGORY_ID, STOCK_ID) 
    VALUES
        (?, ?, ?, ?)

5. Run it – Case 2

Get an existing category and a new stock.

   session.beginTransaction();
 
    Stock stock = new Stock();
    stock.setStockCode("7052");
    stock.setStockName("PADINI");
 
    //assume category id is 7
    Category category1 = (Category)session.get(Category.class, 7);
 
    StockCategory stockCategory = new StockCategory();
    stockCategory.setStock(stock);
    stockCategory.setCategory(category1);
    stockCategory.setCreatedDate(new Date()); //extra column
    stockCategory.setCreatedBy("system"); //extra column
 
    stock.getStockCategories().add(stockCategory);
 
    session.save(stock);
 
    session.getTransaction().commit();

Output…

Hibernate: 
    SELECT
        category0_.CATEGORY_ID AS CATEGORY1_1_0_,
        category0_.`DESC` AS DESC2_1_0_,
        category0_.NAME AS NAME1_0_ 
    FROM
        mkyongdb.category category0_ 
    WHERE
        category0_.CATEGORY_ID=?
Hibernate: 
    INSERT 
    INTO
        mkyongdb.stock
        (STOCK_CODE, STOCK_NAME) 
    VALUES
        (?, ?)
Hibernate: 
    SELECT
        stockcateg_.CATEGORY_ID,
        stockcateg_.STOCK_ID,
        stockcateg_.CREATED_BY AS CREATED1_2_,
        stockcateg_.CREATED_DATE AS CREATED2_2_ 
    FROM
        mkyongdb.stock_category stockcateg_ 
    WHERE
        stockcateg_.CATEGORY_ID=? 
        AND stockcateg_.STOCK_ID=?
Hibernate: 
    INSERT 
    INTO
        mkyongdb.stock_category
        (CREATED_BY, CREATED_DATE, CATEGORY_ID, STOCK_ID) 
    VALUES
        (?, ?, ?, ?)

Done.

Reference

  1. Hibernate Mapping Documentation
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: ionizer payment plan()

  • Pingback: payment plan()

  • Pingback: leather electrician tool belts()

  • Pingback: more hints()

  • Pingback: house blue()

  • Pingback: plumbing apps for ipad()

  • Pingback: auto locksmith finder()

  • Pingback: locksmith kalamazoo()

  • Pingback: helpful hints()

  • Pingback: made my day()

  • Pingback: water ionizer loans()

  • Pingback: laan penge nu og her()

  • Pingback: mobile porn movies()

  • Pingback: bedste laan lige nu()

  • Pingback: car parking()

  • Pingback: parking()

  • Pingback: DIRECTV packages()

  • Pingback: Steamy deep throats and rims her bf bootie()

  • Pingback: Blue Coaster33()

  • Santi

    In my case, what happens is as if STOCK_ID is a null value when it tries to make the insert into Stock_Category table.

  • Santi

    Whatever I try I get the following exception:

    org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property […]
    at org.hibernate.id.ForeignGenerator.generate(ForeignGenerator.java:101)
    at org.hibernate.mapping.Component$ValueGenerationPlan.execute(Component.java:422)
    at org.hibernate.id.CompositeNestedGeneratedValueGenerator.generate(CompositeNestedGeneratedValueGenerator.java:121)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117)
    at org.hibernate.ejb.event.EJB3PersistEventListener.saveWithGeneratedId(EJB3PersistEventListener.java:78)
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:208)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:151)
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:843)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:836)
    at org.hibernate.ejb.engine.spi.EJB3CascadingAction$1.cascade(EJB3CascadingAction.java:53)
    at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:388)
    at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:331)
    at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:209)
    at org.hibernate.engine.internal.Cascade.cascadeCollectionElements(Cascade.java:418)
    at org.hibernate.engine.internal.Cascade.cascadeCollection(Cascade.java:358)
    at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:334)
    at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:209)
    at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:166)

    I’m using a DB2 (AS/400) database.

  • Pingback: Hibernate many to many mapping, join table with PK and extra columns | Ask & Answers()

  • Soledad

    Hi, I’m working with your tutorial, but I’m facing the same problem that this person in this link http://stackoverflow.com/questions/12970799/hibernate-many-to-many-withe-extracolumn-criteria-problems

    Can you please help me about the way to create a criteria for the many-to-many relationship?

    Thanks!.

  • http://www.timestips.com Piyush

    can you solve this problem
    its about many to many mapping in hibernate

    http://stackoverflow.com/questions/19188751/how-to-prevent-hibernate-to-insert-into-one-table-in-many-to-many-mapping

    Thanks a lot.

  • http://www.rexart.pl Norr

    Why in file StockCategoryId.java in method hashCode in variable result you assign 31* ?

    • Murat Ates

      “The value 31 was chosen because it is an odd prime. If it were even and the multiplication overflowed, information would be lost, as multiplication by 2 is equivalent to shifting” Read Effective Java, Second Ed. Chapter 3, Item 9.

  • http://javadomain.in Diva

    you can find some more details in the below link,”http://javadomain.in/hibernate-join-annotation-example/

  • watou

    I have a question :

    is there any benefit to declare :
    private Set stockCategories
    in both classes Stock and Category ?

    I think that it will slow down the loading in java bean entities, especially when we have a lot of items in both tables stock and category in database.

    thank you.

  • Siddhant Sahu

    Hi sir,
    My name is siddhant.
    I have implemented ur example. But at the time of saving it is throwing an error
    Exception in thread “main” java.lang.NullPointerException

    /**
    package SampleJavaProject.Entity;

    import java.io.Serializable;

    /**
    * @author Siddhant_S
    *
    */
    @Entity
    @Table(name = “person”, schema = “test”)
    public class Person implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;
    @Column(precision = 2)
    private double amount;
    private Calendar birthDate;
    private String street;
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = “pk.person”)
    private Set bank;

    /**
    *
    */
    public Person() {
    }

    /**
    * @param name
    * @param amount
    * @param birthDate
    * @param street
    * @param bank
    */
    public Person(String name, double amount, Calendar birthDate, String street) {
    this.name = name;
    this.amount = amount;
    this.birthDate = birthDate;
    this.street = street;
    this.bank = bank;
    }

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

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

    /**
    * @return the name
    */
    public String getName() {
    return name;
    }

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

    /**
    * @return the amount
    */
    public double getAmount() {
    return amount;
    }

    /**
    * @param amount
    * the amount to set
    */
    public void setAmount(double amount) {
    this.amount = amount;
    }

    /**
    * @return the birthDate
    */
    public Calendar getBirthDate() {
    return birthDate;
    }

    /**
    * @param birthDate
    * the birthDate to set
    */
    public void setBirthDate(Calendar birthDate) {
    this.birthDate = birthDate;
    }

    /**
    * @return the street
    */
    public String getStreet() {
    return street;
    }

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

    /**
    * @return the bank
    */
    public Set getBank() {
    return bank;
    }

    /**
    * @param bank
    * the bank to set
    */
    public void setBank(Set bank) {
    this.bank = bank;
    }
    }

    /**
    package SampleJavaProject.Entity;

    import java.io.Serializable;

    /**
    * @author Siddhant_S
    *
    */
    @Entity
    @Table(name = “Bank”, schema = “test”)
    public class Bank implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;
    @Column(precision = 2)
    private double amount;
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = “pk.bank”)
    private Set associations;

    /**
    *
    */
    public Bank() {
    }

    /**
    * @param name
    * @param amount
    * @param associations
    */
    public Bank(String name, double amount) {
    this.name = name;
    this.amount = amount;
    }

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

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

    /**
    * @return the name
    */
    public String getName() {
    return name;
    }

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

    /**
    * @return the amount
    */
    public double getAmount() {
    return amount;
    }

    /**
    * @param amount
    * the amount to set
    */
    public void setAmount(double amount) {
    this.amount = amount;
    }

    /**
    * @return the associations
    */
    public Set getAssociations() {
    return associations;
    }

    /**
    * @param associations
    * the associations to set
    */
    public void setAssociations(Set associations) {
    this.associations = associations;
    }
    }

    /**
    package SampleJavaProject.Entity;

    import java.io.Serializable;

    /**
    * @author Siddhant_S
    *
    */
    @Entity
    @Table(name = “Person_Bank_Association”, schema = “test”)
    @AssociationOverrides({
    @AssociationOverride(name = “pk.person”, joinColumns = @JoinColumn(name = “person_id”)),
    @AssociationOverride(name = “pk.bank”, joinColumns = @JoinColumn(name = “bank_id”)) })
    public class PersonBankAssociation implements Serializable {
    @EmbeddedId
    private PersonBankId pk;
    private String name;
    private double amount;
    /**
    *
    */
    public PersonBankAssociation() {
    }
    /**
    * @param name
    * @param amount
    */
    public PersonBankAssociation(String name, double amount) {
    this.name = name;
    this.amount = amount;
    }
    /**
    * @return the pk
    */
    public PersonBankId getPk() {
    return pk;
    }
    /**
    * @param pk
    * the pk to set
    */
    public void setPk(PersonBankId pk) {
    this.pk = pk;
    }

    /**
    * @return the name
    */
    public String getName() {
    return name;
    }

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

    /**
    * @return the amount
    */
    public double getAmount() {
    return amount;
    }

    /**
    * @param amount
    * the amount to set
    */
    public void setAmount(double amount) {
    this.amount = amount;
    }

    /**
    *
    * @return person
    */
    @Transient
    public Person getPerson() {
    return getPk().getPerson();
    }

    public void setPerson(Person person) {
    getPk().setPerson(person);
    }

    /**
    *
    * @return bank
    */
    @Transient
    public Bank getBank() {
    return getPk().getBank();
    }

    public void setBank(Bank bank) {
    getPk().setBank(bank);
    }
    }

    /**
    package SampleJavaProject.Entity;

    import java.io.Serializable;

    /**
    * @author Siddhant_S
    *
    */
    @Embeddable
    public class PersonBankId implements Serializable {
    @ManyToOne
    private Person person;
    @ManyToOne
    private Bank bank;

    /**
    *
    */
    public PersonBankId() {
    }

    /**
    * @param person
    * @param bank
    */
    public PersonBankId(Person person, Bank bank) {
    this.person = person;
    this.bank = bank;
    }

    /**
    * @return the person
    */
    public Person getPerson() {
    return person;
    }

    /**
    * @param person
    * the person to set
    */
    public void setPerson(Person person) {
    this.person = person;
    }

    /**
    * @return the bank
    */
    public Bank getBank() {
    return bank;
    }

    /**
    * @param bank
    * the bank to set
    */
    public void setBank(Bank bank) {
    this.bank = bank;
    }

    }

    /**
    package SampleJavaProject.HibernateTransaction;

    import java.util.Calendar;

    /**
    * @author Siddhant_S
    *
    */
    public class PersonBankApp {
    private static final Logger _logger = LoggerFactory
    .getLogger(PersonBankApp.class);
    private static final Session session = HibernateUtil.getSessionFactory()
    .openSession();

    /**
    * @return the Logger
    */
    public static Logger getLogger() {
    return _logger;
    }

    /**
    * @return the session
    */
    public static Session getSession() {
    return session;
    }

    /**
    * @param args
    */
    public static void main(String[] args) {
    getSession().beginTransaction();
    Bank bank=new Bank(“SBI”, 2000.00);
    getSession().save(bank);
    Calendar birthDate=GregorianCalendar.getInstance();
    birthDate.setTime(new Date());
    Person person=new Person(“Siddhant”, 2000.00, birthDate, “lane4″);
    PersonBankAssociation associations=new PersonBankAssociation(“Sbi name”, 2000.00);
    associations.setPerson(person);
    associations.setBank(bank);
    person.getBank().add(associations);

    Integer personId= (Integer) getSession().save(person);
    getSession().getTransaction().commit();
    getSession().close();
    System.out.println(“Person id:”+personId);
    }

    }

    • Siddhant Sahu

      Please help me on this code i m not able to save the data in the DB.
      Please help me as soon as possible

      • siddhant sahu

        I got my solution for this problem.
        Actually it is because of the the initializations problem.

        • Gavino Ang

          Hi Siddhant, please elaborate on your answer, I believe I am getting the same issue as you. Thank you very much.