java - SpringBoot2 - jpa 实体不是托管类型
问题描述
我有一个标有javax.persistence.Entity
它SpringBoot
说不是托管类型的类。
班级如下
@Entity
@Table(name="users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
@Column(unique = true)
private String username;
...
用户存储库.java
public interface UserRepository extends CrudRepository<User, Long> {
User findByUsername(String username);
List<User> findByName(String name);
@Query("UPDATE AppUser u SET u.lastLogin=:lastLogin WHERE u.username = ?#{ principal?.username }")
@Modifying
@Transactional
public void updateLastLogin(@Param("lastLogin") Date lastLogin);
}
AuthenticationSuccessHandler.java
@Component
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
@Autowired
private UserRepository userRepository;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
userRepository.updateLastLogin(new Date());
}
}
和 SpringSecurityConfig.java
@Configuration
@EnableWebSecurity
@ComponentScan("com.bae.dbauth.security")
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private WebApplicationContext applicationContext;
private CustomUserDetailsService userDetailsService;
@Autowired
private AuthenticationSuccessHandlerImpl successHandler;
@Autowired
private DataSource dataSource;
@PostConstruct
public void completeSetup() {
userDetailsService = applicationContext.getBean(CustomUserDetailsService.class);
}
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(encoder())
.and()
.authenticationProvider(authenticationProvider())
.jdbcAuthentication()
.dataSource(dataSource);
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/resources/**");
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login")
.permitAll()
.and()
.formLogin()
.permitAll()
.successHandler(successHandler)
.and()
.csrf()
.disable();
}
....
}
和应用程序类...
@SpringBootApplication
@PropertySource("classpath:persistence-h2.properties")
@EnableJpaRepositories(basePackages = { "com.bae.dbauth.repositories" })
@EnableWebMvc
@Import(SpringSecurityConfig.class)
public class BaeDbauthApplication implements WebMvcConfigurer {
@Autowired
private Environment env;
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("driverClassName"));
dataSource.setUrl(env.getProperty("url"));
dataSource.setUsername(env.getProperty("user"));
dataSource.setPassword(env.getProperty("password"));
return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.bae.dbauth.models" });
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(additionalProperties());
return em;
}
public static void main(String[] args) {
SpringApplication.run(BaeDbauthApplication.class, args);
}
}
当我运行应用程序时,我收到一条很长的错误消息,其中包括Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.bae.dbauth.model.User
整个堆栈跟踪非常广泛,它开始于:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'springSecurityConfig': Unsatisfied dependency expressed through field 'successHandler'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authenticationSuccessHandlerImpl': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.bae.dbauth.model.User
而且我不明白 User 类有什么问题。
更新:
我添加/修改注释SpringSecurityCongig.java
并尝试
@Configuration
@EnableWebSecurity
@ComponentScan({"com.bae.dbauth.security", "com.bae.dbauth.model"})
和
@Configuration
@EnableWebSecurity
@ComponentScan("com.bae.dbauth.security")
@EntityScan(basePackages = {"com.bae.dbauth.model"})
实体所在com.bae.dbauth.model
的包在哪里,而主类和主类在哪里。User
com.bae.dbauth
SpringSecurityConfig.java
application
结果在每种情况下都是相同的 - 相同的错误消息。
解决方案
未发现实体。如果您的实体管理器工厂自动配置,您有 2 个选项:
- 添加@EntityScan
- 将您的实体放在您的应用程序下的包中(这些包按约定进行扫描)
我可以看到您自己配置了实体管理器工厂。
em.setPackagesToScan(new String[] { "com.bae.dbauth.models" });
当您的用户实体位于:com.bae.dbauth.model
这让我觉得这只是一个错字。
推荐阅读
- javascript - 使用多维数组的登录页面?
- java - 如何通过标签名称检索多个标签中的元素以进行硒自动化测试
- localization - 使用清单的 MS Teams 应用本地化不起作用
- r - 将顶点属性数据从 igraph 移动到矩阵
- c# - 是否可以为代码重复创建方法?
- azure - 如何通过验证源和目标中文件的大小来归档 Azure 数据湖中的数据
- linux - 如果我们允许 root 用户特权在一个 pod 中进行进程,co pod 是否有任何风险?
- sql - 如何调试此查询
- javascript - 使用 NODE.js 在 MySQL 数据库中查找电子邮件
- javascript - 如何在 Firestore 文档中创建 Auto-ID?