[英]SpringBoot2 - jpa entity is not a managed type
我有一個標有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
類所在的包。
每種情況下的結果都是相同的 - 相同的錯誤消息。
首先嘗試在User
中將id
的類型更改為Long
而不是long
。
然后確保@ComponentScan
還包括包含實體的java包。 您可以指定多個軟件包進行掃描,請參見Spring docs 。 足夠:
@ComponentScan({"pkg1","pkg2"})
添加注釋@Repository
在UserRepository:
@Repository
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);
}
找不到實體。 如果您的實體管理員在出廠時已自動配置,則有兩個選項:
我可以看到您自己配置了實體管理器工廠。
em.setPackagesToScan(new String[] { "com.bae.dbauth.models" });
當您的用戶實體位於: com.bae.dbauth.model
這使我認為這只是一個錯字。
除了應用程序類上的注釋,如果您配置了多個 DB(或單獨定義的 DB 配置;LocalContainerEntityManagerFactoryBean 的 @Bean),請確保您已經使用構建器(EntityManagerFactoryBuilder)定義了正確的包。
例如
builder
.dataSource(dataSource)
.packages("com.xyz.abc.entity")
.persistenceUnit("application-db")
.build();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.