Hibernate Error – Collection has neither generic type or OneToMany.targetEntity()

Problem

In Hibernate development, defined one to many relationship via annotation.


package com.mkyong.user.model;

@Entity
@Table(name = "USER", schema = "MKYONG")
public class User implements java.io.Serializable {

    private Set address = new HashSet(0);
    //...

    @OneToMany(orphanRemoval=true, 
	cascade=CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
    public Set getAddress() {
        return this.address;
    }

}

But it hits following exception :


Initial SessionFactory creation failed. org.hibernate.AnnotationException: 
Collection has neither generic type or OneToMany.targetEntity() defined: com.mkyong.user.model.user

Solution

Class “User” has a raw type collection “Set address“, and Hibernate does not support this, because Hibernate does not know which “class” to link with.

For example,

  1. Set address; //The Set is raw type, Hibernate returns exception.
  2. Set<Address> address; //Hibernate knows the Set is Address class now.

So, your class need to change like this :


package com.mkyong.user.model;

@Entity
@Table(name = "USER", schema = "MKYONG")
public class User implements java.io.Serializable {

    private Set<Address> address = new HashSet<Address>(0);
    //...

    @OneToMany(orphanRemoval=true, 
	cascade=CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
    public Set<Address> getAddress() {
        return this.address;
    }

}

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
3 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
3 Comment authors
alejandro silva mMohitPM Recent comment authors
newest oldest most voted
alejandro silva m
Guest
alejandro silva m

funciona!

Mohit
Guest
Mohit

Thanks man.

PM
Guest
PM

How to make it automatically?
What if I’ve got 10 automaticlly genereted classes with this problem ?