首页 > 解决方案 > SpringBoot2 - jpa 实体不是托管类型

问题描述

我有一个标有javax.persistence.EntitySpringBoot说不是托管类型的类。

班级如下

@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的包在哪里,而主类和主类在哪里。Usercom.bae.dbauthSpringSecurityConfig.javaapplication

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

标签: javaspring-bootspring-data-jpa

解决方案


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

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

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

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

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

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


推荐阅读