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

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
108 Comment threads
38 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
116 Comment authors
ARAJRizwanAjitHtfjoff Recent comment authors
newest oldest most voted
ashokayengar
Guest
ashokayengar

There is a simpler way to implement this.
reference : http://forum.springsource.org/showthread.php?126461-How-to-realize-a-many-to-many-relation-type-with-attributes
Although the example is using spring roo however it is perfectly applicable to regular JPA entity.

Here is the example:
Join entity needs the following annotation to ensure that there are not two entries with the same composite (not primary) key (human, qualification)

@RooJavaBean
@RooToString
@RooJpaActiveRecord
@Table(uniqueConstraints=@UniqueConstraint(columnN ames={"human","qualification"}), name="myUniqueConstraint")
public class HumanQualification {

@ManyToOne
private Human human;

@ManyToOne
private Qualification qualification;

private Float weight;
}

In Human and Qualification there must be “orphanRemoval=true” to delete corresponding join entities if a Human or Qualification is deleted:

@OneToMany(cascade = CascadeType.ALL, mappedBy = "human", orphanRemoval=true)
private Set<HumanQualification> humanQualification = new HashSet<HumanQualification>();

Hope this simplifies the solution

joff
Guest
joff

isn’t the job of jpa/hibernate is to make us focus on object oriented programming rather than thinking in solving relational model problem? because this solution is relational model oriented.

Ajit
Guest
Ajit

Hi I am getting below compile time error.

Persistent type of override attribute “pk.stock” cannot be resolved
Persistent type of override attribute “pk.catagory” cannot be resolved

I am using JPA,jdk7,eclipse mars2…. Please help me out.

jose
Guest
jose

Hi, thanks for the tutorial, was really helpful

Elias Castaรฑo
Guest
Elias Castaรฑo

Good tutorial. I have a prblem when I try to save more records . I get the following error: org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session : This is my code: public void addContacto(Proyecto proyecto, Contacto contacto, String tipo) { Session session = sessionFactory.openSession(); Transaction tx = null; try{ tx = session.beginTransaction(); ContactoProyecto contactoProyecto = new ContactoProyecto(); Proyecto p = (Proyecto)session.get(Proyecto.class, proyecto.getId()); Contacto c = (Contacto)session.get(Contacto.class, contacto.getId()); contactoProyecto.setContacto(c); contactoProyecto.setProyecto(p); contactoProyecto.setTipo(tipo); p.getContactoProyectos().add(contactoProyecto); session.saveOrUpdate(p); tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } }

trackback
Hibernate โ€“ Many-to-Many example (XML Mapping)

[…] mapping file (hbm). Note For many to many with extra columns in join table, please refer to this tutorial. Tools and technologies used in this tutorials […]

Martin
Guest
Martin

Thanks, but you should not talk about Hibernate. THIS is JPA implemented using Hibernate. All of the code in this article would work using any other Java Persistence Api provider.

Jemaru
Guest
Jemaru

Hi Sir mKyong, Can you please help me? I want to join 3 tables in 1 join table. Ex. Table User, Application, and Role will be joined in a table User_App_Role containing IDs of each tables. I tried to follow your example and here is my codes: User.java @OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.cmUser") public Collection getCMUserApplicationRole() { return this.cmUserAppRole; } public void setCMUserApplicationRole(Collection cmUserAppRole) { this.cmUserAppRole = cmUserAppRole; } private Collection cmUserAppRole = new ArrayList(0); CMApplication.java @OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.cmApplication") public Collection getCMUserApplicationRole() { return this.cmUserAppRole; } public void setCMUserApplicationRole(Collection cmUserAppRole) { this.cmUserAppRole = cmUserAppRole; } private… Read more »

Derek Lee
Guest
Derek Lee

This error typically occurs when you are mixing “field” and “property” access strategy.
From what you have pasted up there I cannot tell if you put the

@Id

annotation above the method or attribute, so make sure you only stick to one access strategy. ๐Ÿ™‚

DE OLIVEIRA
Guest
DE OLIVEIRA

Hello,

Thanks for this example. I have errors on
@AssociationOverrides({
@AssociationOverride(name = “pk.stock”,
joinColumns = @JoinColumn(name = “STOCK_ID”)),
@AssociationOverride(name = “pk.category”,
joinColumns = @JoinColumn(name = “CATEGORY_ID”)) })

Errors are :
– Persistent type of override attribute pk.stock cannot be resolved
– Persistent type of override attribute pk.category cannot be resolved

Any idea about this problem ?
Thanks for your help

antony
Guest
antony

hi, i had the same problem as you but it was because i used jpa. don’t use jpa to do it. use pure hibernate and the file hibernate.cfg.xml

Manoj
Guest
Manoj

Can you please tell me which tutorial?
I need xml mapping for many-to-many with extra columns.

Manoj
Guest
Manoj

I followed the xml mapping as in the attached zip but when trying to persist object I got the following error In java when trying to save the object Stocks stock = new Stocks(); stock.setStockCode("7052"); stock.setStockName("PADINI"); // session().save(stock); Cat cat1 = new Cat(); cat1.setName("consumer"); cat1.setDesc("consumer company"); //new category, need save to get the id first session().save(cat1); StockCategory stockCategory = new StockCategory(); stockCategory.setCategoryId(cat1); stockCategory.setStockId(stock); stockCategory.setCreatedDate(new Date()); stockCategory.setCreatedBy("user"); stock.setStockCategories(new HashSet()); StockCategoryId scId = new StockCategoryId(); stock.getStockCategories().add(stockCategory); session().save(stock); Following hibernate error is generated org.springframework.orm.hibernate3.HibernateSystemException: ids for this class must be manually assigned before calling save(): com.mkyong.ternary.StockCategory; nested exception is org.hibernate.id.IdentifierGenerationException: ids for this… Read more »

G Suresh
Guest
G Suresh

Useful example for many to many

JohnJ
Guest
JohnJ

Hello,

I was looking at Case1 and I don’t see where category1.stockCategories is being updated.
Maybe I am missing something ?

Thanks

John

Nassa
Guest
Nassa

Hello, I used your ManyToMany example with additionnals columns in the join table with hibernate 3.6.1. – When I save the Stock entity with categories associated : All is Ok. – When I read the Stock entity : All is Ok. – When I delete The Stocke entity the joint table records are also removed : All is Ok – But when I update the Stock entity (without to change associated categories) Hibernate go to stack overflow error : java.lang.StackOverflowError at com.mysql.jdbc.Util.handleNewInstance(Util.java:431) at com.mysql.jdbc.PreparedStatement.getInstance(PreparedStatement.java:872) at com.mysql.jdbc.ConnectionImpl.clientPrepareStatement(ConnectionImpl.java:1490) at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4253) at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4152) at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:534) at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:452) at org.hibernate.jdbc.AbstractBatcher.prepareQueryStatement(AbstractBatcher.java:161) at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1700) at org.hibernate.loader.Loader.doQuery(Loader.java:801)… Read more »

beginner_
Guest
beginner_

I have exactly the same issue in hibernate4. Were you able to resolve this?

RobertL
Guest
RobertL

I have the same issue and can’t found any solution on that

DaFoot
Guest
DaFoot

Hello,
Thankyou for taking the time to create/share the tutorial.

I’ve tried to implement it in my Spring/Hibernate application but I seem to get some sort of object nesting recursion going when I make the call for fetch an object from one side of the relationship.

I’ve detailed the problem/code on coderanch here:
http://www.coderanch.com/t/560053/Spring/Spring-hibernate-manytomany-mapping-problems

And on Spring Source here:
http://forum.springsource.org/showthread.php?118938-Hibernate-manytomany-mappings

I suspect it’s something silly/obvious but as a noob to Spring/Hibernate I’m struggling. If you could spare 10 minutes to have a quick look for anything obvious it would be much appreciated ๐Ÿ™‚

Ilan
Guest
Ilan

I have the same problem. Did you solve the problem?

Marc Schipperheyn
Guest
Marc Schipperheyn

Hi,

I’d like to get some feedback on this approach vs ManyToMany in relation to lazy loading and using Set. When you insert an item into a Set, in a @ManyToMany, usually the whole set will be loaded to ensure uniqueness. However, since the stockCategory represents the two ids of the related items, an equals comparison could be done solely based on the ids and the related entity should not have to load. Is this true? If so, would this work like this in the above example?

Chris457
Guest
Chris457

Dear Mr. MkYong, I frequently enjoy your blog and it has given me a number of solutions for problems. Thank you for using your time to share your knowledge! Having said that I was wondering whether this article’s initial statement: “The Hibernate / JBoss tools generated annotation codes are not working in this third table extra column scenario.” was really true. To clarify, I used the “JPA-Project” under Eclipse Java EE IDE for Web Developers “Indigo”, apparently a different tool(!?) but it ships with my Eclipse-version, so no need for an extrag plugin. My Hibernate Version is hibernate-distribution-3.5.0-Final with Java… Read more »

Kedar
Guest
Kedar

Can you give me some pointers on how to delete the mapping. I tried removing the StockCategory from the attached set and updating the Stock product. Though it updated without errors the records were not deleted from join table. My implementation is in spring.

Essentially my code is

 
Stock stock = loadStock(stockId)

StockCategory associationToRemove = new StockCategory();
associationToRemove.setStock(stock);
associationToRemove.setCategory(loadCategory(catId));
stock.getStockCategory().remove(associationToRemove);

update(stock);

Fetch and assign works as expected.

Thanks!

Kedar
Guest
Kedar

Got it. Had to delete my association explicitly

Abel Bravo Camacho
Guest
Abel Bravo Camacho

How do you persist a stockCategory instance getting an existing stock and an existing category?

Thanks in advance!

Abel Bravo Camacho
Guest
Abel Bravo Camacho

Well I got the assocition, but how query a extra field from de join class using Criteria?
Thanks for your help

Abel Bravo Camacho
Guest
Abel Bravo Camacho

Using criteria for quering…

DetachedCriteria criteria = DetachedCriteria.forClass(StockCategory.class,”stock-cat”);
criteria.createAlias(“stock-cat.pk”,”p”);
criteria.createAlias(“p.stock”,”st”);
criteria.add(Restrictions.eq(“st.stockName”, “abc”);

When this query run it throws:
org.postgresql.util.PSQLException: ERROR: missing FROM-clause entry for table “st1_”

what is wrong?

thanks in advance!

Joe
Guest
Joe

Mkyong, I posted a question to StackOverflow regarding this tutorial with my custom requirements. Would you mind taking a look when you have a chance? http://stackoverflow.com/questions/9549294/looping-through-hibernate-many-to-many-in-jsp I’ve been battling with this for about a week. Thanks for your helpful blog!

Rakesh
Guest
Rakesh

New at Hibernate .. pardon my ignorance

In the example that you have shown .. Is there a way to get set of Category for given stock entity or vice verse return set of Stock for given Category?

Thanks
Rakesh

aminos
Guest
aminos

Hi , thanks for this tutorial I want the same solution but with xml , if u can help me thanks I searched at google and stackoverflow but i didnt found a solution

John Hunsley
Guest
John Hunsley

Thanks for the great tutorial.

One issue i’ve found when using this strategy is you might get a NullPointer when hibernate tries to set the id values in the EmbeddedId object. This comes out in the stack trace with the following exception –

org.hibernate.PropertyAccessException: could not set a field value by reflection setter …..

I solved it by constructing a blank EmbeddedId instance in the constructor of the class in which the id is embedded. In your example i’d add the following –

public StockCategory() {
pk = new StockCategoryId;
}

p00m
Guest
p00m

Hey Mkyong

Great examples & tutorials!

But I’m having some trouble adding another table to the jointable. Using your example what I need is to add lets say a table projects connected to the stock_category table.

In my case stock is users and category is projects and the added table would be the number of hours worked on a specific project (using a date).

A database example:
http://i48.tinypic.com/4q1k48.png

Any idea how I could do this?

Cheers

p00m

Dexy
Guest
Dexy

Hi mkyong, This example works fine, but there’s a performance problem with Hibernate when you run a HQL like this: SELECT s FROM Stock s LEFT JOIN FETCH s.stockCategories cRel WHERE s.stockId = :id i.e. you want to fetch a stock with all its all categories in one SQL (avoiding n+1 selects) This fetch doesn’t work properly. Actually, it does the join and executes the correct SQL, but immediately after that, for each stock_category Hibernate executes additional SQLs to fetch the associated stock and category separately!!! I think it’s a bug in Hibernate that forces separate SQLs for each part… Read more »

Marc Schipperheyn
Guest
Marc Schipperheyn

I suggest logging a bug with Hibernate on this

Mehdi.M
Guest
Mehdi.M

hi
in your case you have check you many to one mappin
when you choose class=” you r class” your class in not set to object yo define in getter setter
have enjoy ๐Ÿ˜‰

antony
Guest
antony

this tuto is to great, i transform it with attribute override to make one to many association with extra columns