I got an exception when I use hibernate in Maven. The hibernate version is 5.1.0.Final. The exception is: Here is my project structure:
Here is my Entity class ABC:
package com;
import javax.persistence.*;
@Entity
@Table(name = "abc_inf")
public class ABC {
@Id@GeneratedValue
private Integer id;
private String name;
public ABC() {
}
setters and getters omitted
}
Here is my main class:
package com;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class Main {
public static void main(String[] args) {
Configuration conf = new Configuration().configure();
ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build();
SessionFactory sf = conf.buildSessionFactory(sr);
Session session = sf.openSession();
ABC abc = new ABC();
abc.setName("abc");
session.save(abc);
session.flush();
session.close();
sf.close();
}
}
Here is my hibernate.cfg.xml:
<hibernate-configuration>
<session-factory>
mysql connection and properties settings omitted
<mapping class="com.ABC"/>
</session-factory>
</hibernate-configuration>
It is a Hibernate 5 configuration problem. You can't use this code to build a session factory
Configuration conf = new Configuration().configure();
ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build();
SessionFactory sf = conf.buildSessionFactory(sr);
Use this instead
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Refer for additional notes
Hibernate 5 :- org.hibernate.MappingException: Unknown entity
如果使用Hibernate version 4,问题就解决了
You need to add the annotated classes to the hibernate config. Use the following code
AnnotationConfiguration conf = new AnnotationConfiguration();
conf.addAnnotatedClass(ABC.class);
SessionFactry sf = conf.configure(hbmFile).buildSessionFactory();
As for my case i'm use LocalSessionFactoryBean
and setPackagesToScan
, and services, writed for audit entities work fine.
But!!!
In our project we have table EntityInfo
with column entityname
, for example,
entytyname = bel.rdigital.cashbox.models.cbmain.merchantcore.versions.CBVersions
and this persist in db. Then I refactored entity CBVersions
and transfer it to package
bel.rdigital.cashbox.models.cbmain.versions.cashbox.CBVersions
,
but in db stayed old package, and than, when I using method CrossTypeRevisionChangesReader.findEntitiesGroupByRevisionType(revision)
,
I get exception Unknown entity: bel.rdigital.cashbox.models.cbmain.merchantcore.versions.CBVersions
So, this exaption means, that hiberante not find entity... Problem may be in package scanning or in location entity...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.