136

I'm finding my feet with Hibernate Annotations and I've hit a problem I hope someone can help with.

I have 2 entities, Section and ScopeTopic. The section has a List class member, so a One to Many relationship. When I run my unit test I am getting this exception:

Use of @OneToMany or @ManyToMany targeting an unmapped class: com.xxx.domain.Section.scopeTopic[com.xxx.domain.ScopeTopic]

I would assume that the error implies that my ScopeTopic entity isn't mapped to a table? I can't see with I have done wrong. Here are the Entity classes:


@Entity
public class Section {
    private Long id;
    private List<ScopeTopic> scopeTopics;

    public Section() {}

    @Id
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @OneToMany
    @JoinTable(name = "section_scope", joinColumns = {@JoinColumn(name="section_id")},
               inverseJoinColumns = {@JoinColumn(name="scope_topic_id")} )
    public List<ScopeTopic> getScopeTopic() {
        return scopeTopic;
    }

    public void setScopeTopic(List<ScopeTopic> scopeTopic) {
        this.scopeTopic = scopeTopic;
    }
}

@Entity
@Table(name = "scope_topic")
public class ScopeTopic {
    private Long id;
    private String topic;

    public ScopeTopic() {}

    @Id
    public Long getId() {
        return id;
    }

    public void setId() {
        this.id = id;
    }

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }
}

I'm pretty sure it's my own lack of understanding that's at fault so some guidance would be great, thanks!

Piotr Niewinski
  • 1,298
  • 2
  • 15
  • 27
C0deAttack
  • 24,419
  • 18
  • 73
  • 81

12 Answers12

282

Your annotations look fine. Here are the things to check:

  • make sure the annotation is javax.persistence.Entity, and not org.hibernate.annotations.Entity. The former makes the entity detectable. The latter is just an addition.

  • if you are manually listing your entities (in persistence.xml, in hibernate.cfg.xml, or when configuring your session factory), then make sure you have also listed the ScopeTopic entity

  • make sure you don't have multiple ScopeTopic classes in different packages, and you've imported the wrong one.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 23
    Ah, thanks! Point 2 was the key, I had forgotten to put ScopeTopic in my annotatedClasses property list when creating the SessionFactory, n00b error! – C0deAttack Feb 10 '11 at 12:20
  • 4
    For those just hitting this comment. org.hibernate.annotations.Entity is deprecated in Hibernate 4. Point 1 does not apply anymore. – gspatel Apr 22 '14 at 03:50
  • For me it was point 2, because I kept on editing the hibernate.cfg.xml in my build folder. – Torsten Oct 20 '15 at 12:14
  • In Spring Boot, I ran into a gotcha here, and point 2 is what helped me solve it. I had been letting Spring Boot auto configure my session factory, and in one branch I had added a new entity... then before that one got merged, I had another branch where I had to customize the session factory. Both branches got merged at the same time and I got the error listed in this problem. My new entity was no longer auto-scanned by spring boot since I had configured the sessionfactory and didn't think to include new entities from other branches. – AForsberg Jun 21 '16 at 14:05
  • In my case I forgot to scan the package using `packagesToScan` – Siva Aug 23 '16 at 12:31
  • I manually lists all my classes inside a test which checks the generated schema. Here I had a java.util.List containing all entity classes. One was missing resulting in this error. Thanks for the heads-up. – gkephorus Mar 21 '17 at 06:01
  • like most of the people here I also forgot about the mapping in hibernate configurations. introduced my Entity class to sessionBuilder.addAnnotatedClasses(CartItem.class); and it started working. – Rajan Chauhan May 03 '18 at 03:38
44

Mine was not having @Entity on the many side entity

@Entity // this was commented
@Table(name = "some_table")
public class ChildEntity {
    @JoinColumn(name = "parent", referencedColumnName = "id")
    @ManyToOne
    private ParentEntity parentEntity;
}
Youans
  • 4,801
  • 1
  • 31
  • 57
30

Your entity may not listed in hibernate configuration file.

c.sankhala
  • 850
  • 13
  • 27
13

Mostly in Hibernate , need to add the Entity class in hibernate.cfg.xml like-

<hibernate-configuration>
  <session-factory>

    ....
    <mapping class="xxx.xxx.yourEntityName"/>
 </session-factory>
</hibernate-configuration>
Sai prateek
  • 11,842
  • 9
  • 51
  • 66
5

In my case I had to add my classes, when building the SessionFactory, with addAnnotationClass

Configuration configuration.configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration
            .addAnnotatedClass(MyEntity1.class)
            .addAnnotatedClass(MyEntity2.class)
            .buildSessionFactory(builder.build());
VLazzarova
  • 93
  • 1
  • 6
4

If you are using Java configuration in a spring-data-jpa project, make sure you are scanning the package that the entity is in. For example, if the entity lived com.foo.myservice.things then the following configuration annotation below would not pick it up.

You could fix it by loosening it up to just com.foo.myservice (of course, keep in mind any other effects of broadening your scope to scan for entities).

@Configuration
@EnableJpaAuditing
@EnableJpaRepositories("com.foo.myservice.repositories")
public class RepositoryConfiguration {
}
Michael Peterson
  • 10,383
  • 3
  • 54
  • 51
3

I add the same problem, Please make sure that Two entity classes are in the same package or one other below.

For Example, When we are trying to map two entity classes User and Posts classes. The user class must be com.microservices.user and the second class should be com.microservices.user.posts

anil reddy
  • 31
  • 1
2

I had the same problem and I could solve it by adding the entity into persistence.xml. The problem was caused due to the fact that the entity was not added to the persistence config. Edit your persistence file:

<persistence-unit name="MY_PU" transaction-type="RESOURCE_LOCAL">
<provider>`enter code here`
     org.hibernate.jpa.HibernatePersistenceProvider
  </provider>
<class>mypackage.MyEntity</class>

...

Daniel Rodríguez
  • 548
  • 1
  • 10
  • 30
enka
  • 21
  • 3
2

-First Check you put the @Entity and top of all Models

-Second Check the @Table(name=" table_name ") with the correct table_name

-Third Check you add the Entity class in hibernate.cfg.xml or persistence.configuration

this error usually comes from above failure.

Sajjad Serajzadeh
  • 334
  • 1
  • 3
  • 13
1

Check the package structure for the @Entity classes.

I also faced an similar issue which occurred as I accidental misspelled the package name.

Make sure all you @Entity classes are under the package(folder) within or below the package of Class having your main() function, as the SpringBootApplication will scan only on and inside the same package.

In case your @Entity Class is not getting scanned, it will not be Mapped, and will give the mentioned error.

You can also check if your @Entity class is getting mapped or scanned correctly by checking the Database. Whenever a Class is marked as @Entity, a table is automatically generated by Hibernate/JPA in the applicable database.

0

I got the same error in this case:

was:

@ElementCollection(targetClass=**String**.class)
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "user_roles",
        joinColumns = @JoinColumn(name = "user_id"),
        inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> authorities = new HashSet<>();

Fixed to:

@ElementCollection(targetClass=**Role**.class)
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "user_roles",
        joinColumns = @JoinColumn(name = "user_id"),
        inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> authorities = new HashSet<>();
ACV
  • 9,964
  • 5
  • 76
  • 81
0

It also occurs if one of the mapped classes does not have @Entity

Mukai
  • 1
  • 4