首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SpringBoot2 - jpa实体不是托管类型。

SpringBoot2 - jpa实体不是托管类型。
EN

Stack Overflow用户
提问于 2019-06-15 07:39:51
回答 4查看 13.5K关注 0票数 0

我有一个用javax.persistence.Entity标记的类,SpringBoot说它不是托管类型。

这门课如下

代码语言:javascript
复制
@Entity
@Table(name="users")
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

private String name;

@Column(unique = true)
private String username;

...

UserRepository.java

代码语言:javascript
复制
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

代码语言:javascript
复制
@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

代码语言:javascript
复制
@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();
    }

    ....

}

申请课..。

代码语言:javascript
复制
@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

整个堆栈跟踪非常广泛,它的开头是:

代码语言:javascript
复制
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

我不明白用户类的问题是什么。

更新:--我在SpringSecurityCongig.java中添加/修改了注释,并尝试了

代码语言:javascript
复制
@Configuration
@EnableWebSecurity
@ComponentScan({"com.bae.dbauth.security", "com.bae.dbauth.model"})

代码语言:javascript
复制
@Configuration
@EnableWebSecurity
@ComponentScan("com.bae.dbauth.security")
@EntityScan(basePackages = {"com.bae.dbauth.model"})

其中,com.bae.dbauth.modelUser实体所在的包,而com.bae.dbauthSpringSecurityConfig.java和主application类所在的包。

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

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2019-06-15 08:08:26

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

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

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

代码语言:javascript
复制
em.setPackagesToScan(new String[] { "com.bae.dbauth.models" });

当用户实体在:com.bae.dbauth.model中时

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

票数 4
EN

Stack Overflow用户

发布于 2021-10-06 06:26:58

除了应用程序类上的注释之外,如果您已经配置了多个DB (或单独定义的DB配置;@LocalContainerEntityManagerFactoryBean的Bean),那么请确保您已经用构建器(EntityManagerFactoryBuilder)定义了正确的包。

e.g

代码语言:javascript
复制
           builder
                .dataSource(dataSource)
                .packages("com.xyz.abc.entity")
                .persistenceUnit("application-db")
                .build();
票数 2
EN

Stack Overflow用户

发布于 2019-06-15 07:48:03

首先尝试将User中的id类型更改为Long,而不是long

然后确保@ComponentScan还包括包含实体的java包。可以指定多个要扫描的包,请参阅春季医生。E充分:

代码语言:javascript
复制
@ComponentScan({"pkg1","pkg2"})
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56608398

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档