Main Tutorials

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 Author

author image
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

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Mohit
9 years ago

Thanks man.

alejandro silva m
5 years ago

funciona!

PM
9 years ago

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