参考这篇博文http://www.blogjava.net/yxhxj2006/archive/2012/06/30/381861.html
有两种方式。
如果出现NullPoint的错误就是hibernate.cfg.xml配置出现问题。
如果是上述org.hibernate.MappingException: Unknown entity问题,发现以下可能:
1.如果你使用的.hbm.xml方式,尝试换为注解方式。
2.注解方式中:
//HibernateUtil.java
static {
try {
//加载Hibernate配置文件
Configuration cfg = new Configuration().configure();
cfg.addAnnotatedClass(UserEntity.class);//该句不能漏掉
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
//实例化SessionFactory
sessionFactory = cfg.buildSessionFactory(serviceRegistry);
}catch (HibernateException e){
e.printStackTrace();
}
}
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://localhost:3306/desalination</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!--数据库登录用户名-->
<property name="connection.username">root</property>
<!--数据库连接密码-->
<property name="connection.password">123456</property>
<!--打印SQL语句-->
<property name="hibernate.show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- DB schema will be updated if needed -->
<property name="hbm2ddl.auto">update</property>
<mapping class="com.entity.UserEntity"/>
<!--注意此句为class-->
</session-factory>
</hibernate-configuration>
3.第三种可能是导入的包错误,注解的文件中导入包错误。
//import javax.persistence.*;
import javax.persistence.Entity;//entity导入为该包而不是org.hibernate.annotations.Entity
对于xml映射方式,没有发现处理方法。