hibernate 出现org.hibernate.MappingException: Unknown entity的解决办法

最近在使用hibernate时根据ID查询时,出现了org.hibernate.MappingException: Unknown entity异常

经过百度得知出现这两种错误的原因无外乎两种

  1. 如果你使用的是注解方式,那么可能是包导错了,需要将import org.hibernate.annotations.Entity;修改为import javax.persistence.Entity;一般来说错误就可以解决了
  2. 如果你使用的是xml配置,那么可能是在cfg文件中没有将实体类的.hbm.xml文件引入,将其正确引入一般就可以解决问题,如果还是解决不了,那可能是session出现问题,检查你的获取session时的代码是否正确,不同版本有不同的方式
  3. 如果你偷懒使用的是逆向工程自动生成的代码,就像我一样,当你正确的配置xml文件或者注解时没有出现任何问题,那么出现这种问题的原因就是session出现了问题,看看你自动生成的dao文件,其中有一项根据ID来查找,将其中的                                                                                     public ProductInfo findById(java.lang.Integer id) {
    log.debug("getting ProductInfo instance with id: " + id);
    try {
    ProductInfo instance = (ProductInfo) getCurrentSession().get(
    "ProductInfo", id);
    return instance;
    } catch (RuntimeException re) {
    log.error("get failed", re);
    throw re;
    }
    }
    修改为                                                                                                                                                                                                     public ProductInfo findById(java.lang.Integer id) {
    log.debug("getting ProductInfo instance with id: " + id);
    try {
    ProductInfo instance = (ProductInfo) getCurrentSession().get(
    ProductInfo.class, id);
    return instance;
    } catch (RuntimeException re) {
    log.error("get failed", re);
    throw re;
    }
    }
  4. 如果不是以上几种情况就要自行解决了

猜你喜欢

转载自blog.csdn.net/dfsethtdfd/article/details/80726122