JPA映射:“ QuerySyntaxException:未映射FooBar…”

时间:2018-11-10 16:30:09

标签: java spring jpa

即使我放置了所有必需的注释,我也遇到了FooBar is not mapped异常:

模型类中的Entity批注:

模型/FooBar.java *

@Data
@Entity
@Table(name = "ORDERS")
public class FooBar {}

DAO中的存储库,PersistenceContext和Transactioinal。另外,我通过类名“ FooBar”正确地引用了它

db / FooBarDao.java

@Repository
public class OrderDAO {
    @PersistenceContext
    private EntityManager em;

    @Transactional
    public List<FooBar> getFooBars() {
        return em.createQuery(
                "select fb from FooBar fb",
                FooBar.class
        ).getResultList();
    }
}

这是使所有功能正常工作的配置:

conf / DbConfig.java

@EnableTransactionManagement
@Configuration
@ComponentScan(basePackages = {"project.db"})
public class DbConfig {

    @Autowired
    public Environment env;

    @Bean
    public DataSource dataSource() {
        System.out.println("Configuring database!!!!!!!!");
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName("org.hsqldb.jdbcDriver");
        ds.setUrl("jdbc:hsqldb:mem:myjdbc");

        new JdbcTemplate(ds)
                .update(FileUtil.readFile2("./src/main/java/project/db/sql/initialize.sql"));

        return ds;
    }


    @Bean
    public PlatformTransactionManager transactionManager(
            EntityManagerFactory entityManagerFactory) {

        return new JpaTransactionManager(entityManagerFactory);
    }

    @Bean
    public EntityManagerFactory entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setPersistenceProviderClass(HibernatePersistenceProvider.class);
        factory.setPackagesToScan("model");
        factory.setDataSource(dataSource());
        factory.setJpaProperties(additionalProperties());
        factory.afterPropertiesSet();

        return factory.getObject();
    }

    private Properties additionalProperties() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.hbm2ddl.auto", "validate");
        properties.setProperty("hibernate.dialect",
                "org.hibernate.dialect.HSQLDialect");
        properties.setProperty("hibernate.show_sql", "true");
        properties.setProperty("hibernate.format_sql", "true");

        return properties;
    }

}

1 个答案:

答案 0 :(得分:0)

即使我正确设置了注释并正确引用了类,也找不到映射。因此,问题很可能与扫描模型类有关。

我的项目结构为/src/main/java/project/ ...

因此,扫描model

factory.setPackagesToScan("model");

将找不到任何豆。相反,我需要做

factory.setPackagesToScan("project.model");

这可以解决问题。