我得到例外Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Building is not mapped [from Building]
我的建筑类映射
@javax.persistence.Entity
@Table(name = "building")
public class Building extends AbstractModel {
AbstractModel为空(仅适用于upcast)
设置packagesToScan
@Primary
@Bean
@Autowired
public EntityManagerFactory entityManagerFactory(DataSource dataSource) {
....
localContainerEntityManagerFactoryBean.setPackagesToScan("com.app.persistence.model");
....
}
代码抛出豁免
public <M extends AbstractModel> List<M> findAll() {
List<Building> buildings;
try {
buildings = (List<Building>) getHibernateTemplate().find("from Building");
} catch (Exception e) {
throw e;
}
return (List<M>) buildings;
}
我也设定了
@Bean
public LocalSessionFactoryBean localSessionFactoryBean(DataSource ds) throws ClassNotFoundException {
LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
localSessionFactoryBean.setDataSource(dataSource());
return localSessionFactoryBean;
}
答案 0 :(得分:1)
您正在配置用于JPA的EntityManagerFactory
,但是在您的代码中,您使用的是普通的Hibernate API,这需要正确配置SessionFactory
。
而不是使用普通的休眠,我强烈建议简单地使用JPA。只需重写代码即可使用EntityManager
代替Session
和/或HibernateTemplate
(后者是您应该避免使用的内容,因为自hibernate 3.0.1以来不再推荐使用!)。
@PersistenceContext
private EntityManager em;
public <M extends AbstractModel> List<M> findAll() {
return em.createQuery("select b FROM Building b", Building.class).getResultList();
}
删除普通休眠的设置,即LocalSessionFactoryBean
配置和HibernateTemplate
设置。
这就是你所需要的。现在,如果您要将Spring Data JPA添加到组合中,您甚至不需要这样,那么您只需要BuildingRepository
接口。
public interface BuildingRepository extends JpaRepository<Building, Long> {}
假设id的类型为Long
。
如果你真的想使用简单的Hibernate(我不建议这样做),你需要正确配置LocalSessionFactoryBean
并为其指定packagesToScan
。
@Bean
public LocalSessionFactoryBean localSessionFactoryBean(DataSource ds) throws ClassNotFoundException {
LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
localSessionFactoryBean.setDataSource(dataSource());
localSessionFactoryBean.setPackagesToScan("com.app.persistence.model");
return localSessionFactoryBean;
}