Spring JPA多数据源配置报错:@ManyToMany指向未映射类
解决Hibernate @OneToMany/@ManyToMany指向未映射类的异常
这个异常org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class本质上是Hibernate没把Permission类识别为合法的JPA实体,问题根源很清晰:你的实体扫描范围漏了Permission所在的包,而且配置里的包名和实体类实际包名还不匹配!
问题拆解
看你的代码细节:
User实体明明在com.example.local.model.entity包,但LocalDbConfiguration里entityManagerFactory的packages参数写的是com.sepehrpay.mps.model.entity,这明显是包名拼写错误;Permission实体在com.example.local.core.auth.domain包,这个包完全没被加入到Hibernate的实体扫描范围里,所以Hibernate根本不知道这是一个JPA实体,自然会抛出关联异常。
修复方案
修改LocalDbConfiguration中的两处关键配置:
- 修正
entityManagerFactory的packages参数,把所有实体类所在的包都加进去(包括User的正确包和Permission的包); - 修正
@EnableJpaRepositories的basePackages参数,确保指向你实际Repository所在的包(对应User的DAO应该在com.example.local.model.dao)。
修改后的配置类代码:
@Configuration @PropertySource({"classpath:application.yml"}) // 修正Repository扫描包为实际路径 @EnableJpaRepositories( basePackages = "com.example.local.model.dao") @EnableJpaAuditing(auditorAwareRef = "auditorProvider") public class LocalDbConfiguration { @Primary @Bean(name = "dataSource") @ConfigurationProperties(prefix = "spring.datasource") public DataSource userDataSource() { return DataSourceBuilder.create().build(); } @Primary @Bean(name = "entityManagerFactory") public LocalContainerEntityManagerFactoryBean entityManagerFactory( EntityManagerFactoryBuilder builder, @Qualifier("dataSource") DataSource dataSource ) { Map<String, Object> properties = new HashMap<>(); properties.put("hibernate.hbm2ddl.auto", "update"); properties.put("database.platform", "org.hibernate.dialect.Oracle10gDialect"); return builder .dataSource(dataSource) // 加入所有实体类所在包:User的包、Permission的包 .packages("com.example.local.model.entity", "com.example.local.core.auth.domain") .persistenceUnit("MpsPU") .properties(properties) .build(); } @Primary @Bean(name = "transactionManager") public PlatformTransactionManager transactionManager( @Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory ) { return new JpaTransactionManager(entityManagerFactory); } @Bean AuditorAware<Long> auditorProvider() { return new AuditorProviderAware(); } }
额外验证点
- 确认
Permission类上的@Entity注解是javax.persistence.Entity(你的代码里已经满足,没问题); - 如果项目里还有其他实体类,也要把它们的包加入到
packages参数中,避免再次出现类似的未映射异常。
内容的提问来源于stack exchange,提问作者Kamyar Kimiyabeigi
相关产品推荐
相关产品推荐

