Reputation: 257
I'm getting exception Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Building is not mapped [from Building]
My Building class mapped
@javax.persistence.Entity
@Table(name = "building")
public class Building extends AbstractModel {
AbstractModel is empty (just for upcast)
Setting packagesToScan
@Primary
@Bean
@Autowired
public EntityManagerFactory entityManagerFactory(DataSource dataSource) {
....
localContainerEntityManagerFactoryBean.setPackagesToScan("com.app.persistence.model");
....
}
Code throws excetion
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;
}
Also i setuped
@Bean
public LocalSessionFactoryBean localSessionFactoryBean(DataSource ds) throws ClassNotFoundException {
LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
localSessionFactoryBean.setDataSource(dataSource());
return localSessionFactoryBean;
}
Upvotes: 0
Views: 2057
Reputation: 124441
You are configuring an EntityManagerFactory
which is for use with JPA however in your code you are using the plain Hibernate API, which requires a correctly configured SessionFactory
instead.
Instead of using plain hibernate I strongly suggest to simply use JPA instead. Just rewrite your code to use an EntityManager
instead of Session
and/or HibernateTemplate
(The latter is something you should avoid using as that isn't recommended anymore since 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();
}
And remove the setup of plain hibernate i.e. the LocalSessionFactoryBean
configuration and HibernateTemplate
setup.
This is all you need. Now if you would add Spring Data JPA into the mix you don't even need this, you would only need a BuildingRepository
interface.
public interface BuildingRepository extends JpaRepository<Building, Long> {}
Assuming that the id is of type Long
.
If you really want to use plain Hibernate (which as stated is something I wouldn't recommend) you need to configure your LocalSessionFactoryBean
correctly and specify the packagesToScan
for it as well.
@Bean
public LocalSessionFactoryBean localSessionFactoryBean(DataSource ds) throws ClassNotFoundException {
LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
localSessionFactoryBean.setDataSource(dataSource());
localSessionFactoryBean.setPackagesToScan("com.app.persistence.model");
return localSessionFactoryBean;
}
Upvotes: 1