java - SpringBoot2 - jpa 实体不是托管类型

标签 java spring-boot spring-data-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.modelUser 实体所在的包,而 com.bae.dbauthSpringSecurityConfig.java 和主要的 application 类是。

每种情况下的结果都相同 - 相同的错误消息。

最佳答案

实体未被发现。如果您的实体管理器工厂自动配置,您有 2 个选项:

  • 添加@EntityScan
  • 将您的实体放在您的应用程序下的包中(这些包按照惯例进行扫描)

我可以看到您自己配置实体管理器工厂。

em.setPackagesToScan(new String[] { "com.bae.dbauth.models" });

当您的用户实体位于:com.bae.dbauth.model

这让我觉得这只是一个错字。

关于java - SpringBoot2 - jpa 实体不是托管类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56608398/

相关文章:

java - 从 html 调用小程序

java - 可执行 jar 文件找不到 main

java - 在自定义身份验证过滤器中处理 Spring Boot 上的错误

java - 如何使用spring boot来处理不同的搜索?

java - 如何在java中以无符号方式将字节数组转换为Base 64字符串?

java - 在Java中,如何从后到前迭代文本文件中的行

angularjs - 更改jHipster登录认证页面

java - 使用 RequestBodyAdvice 验证 REST 请求

java - 使用 hsql hibernate 数据源隔离 Junit 测试

java - 与 Spring Data JPA 和泛型类型混淆