lovk4ch
@lovk4ch

Spring Data JPA: Not a managed type Exception — варианты решения?

Перепробовал все советы, создаю проект с нуля третий раз подряд. Уже второй день вылетает ошибка при сборке, компилятор упёрся рогом.

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 spring.model.entity.User

Мои классы:

@Entity
@Table(name = "User")
public class User {
    private int id;
    private String name;
    private String password;
    ...
}

@Repository
public interface UserRepository extends CrudRepository<User, Long> { }

@SpringBootApplication
@ImportResource("classpath:applicationContext.xml")
@EntityScan(basePackages = "spring.model.entity")
@EnableJpaRepositories(basePackages = "spring.model.repositories")
public class Application {
    ....
        SpringApplication.run(Application.class);
    ....
}


Везде в гугле даётся только один совет: добавить аннотацию @EnableJpaRepositories. Я добавил, путь к пакетам корректный. Не помогло.

На всякий случай context.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/data/jpa https://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

    <!-- It register the beans in context and scan the annotations inside beans and activate them -->
    <context:component-scan base-package="spring" />
    <context:property-placeholder location="database.properties" />

    <!-- This produces a container-managed EntityManagerFactory;
         rather than application-managed EntityManagerFactory as in case of LocalEntityManagerFactoryBean-->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- This makes /META-INF/persistence.xml is no longer necessary -->
        <property name="packagesToScan" value="spring.model.entity" />
        <!-- JpaVendorAdapter implementation for Hibernate EntityManager.
             Exposes Hibernate's persistence provider and EntityManager extension interface -->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            </props>
        </property>
    </bean>

    <!-- Simple implementation of the standard JDBC DataSource interface,
         configuring the plain old JDBC DriverManager via bean properties -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${hibernate.connection.driver_class}" />
        <property name="url" value="${hibernate.connection.url}" />
    </bean>

    <!-- This transaction manager is appropriate for applications that use a single JPA EntityManagerFactory for transactional data access.
        JTA (usually through JtaTransactionManager) is necessary for accessing multiple transactional resources within the same transaction. -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>
</beans>
  • Вопрос задан
  • 11231 просмотр
Пригласить эксперта
Ответы на вопрос 1
azerphoenix
@azerphoenix Куратор тега Java
Java Software Engineer
Здравствуйте!
Я могу лишь предположить, где зарыта ошибка... А вам уже нужно будет исключить эти моменты..
Смотрите
public class User {
    private int id;
}

В качестве ID вы создаете int

@Repository
public interface UserRepository extends CrudRepository<User, Long> { }

А в репозиторий используете Long

Тогда правильнее будет использовать
public class User {
@Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
}


Другой момент, обратите внимание на наличие аннотаций @ID & @GeneratedValue(strategy = GenerationType.AUTO)
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы