加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Spring-boot JPA EntityManager注入失败

发布时间:2020-12-15 01:48:06 所属栏目:大数据 来源:网络整理
导读:在我的J2EE应用程序中,我尝试使用spring-boot和JPA技术,将EntityManager注入DAO层.但是,我有一些问题我的用户CRUD存储库: @Repositorypublic class UserRepositoryImpl implements UserRepository {@PersistenceContext(unitName = "data")private EntityMa

在我的J2EE应用程序中,我尝试使用spring-boot和JPA技术,将EntityManager注入DAO层.但是,我有一些问题…我的用户CRUD存储库:

@Repository
public class UserRepositoryImpl implements UserRepository {

@PersistenceContext(unitName = "data")
private EntityManager entityManager;
// and crud methods
}

我的spring-boot应用程序类:

@SpringBootApplication
public class App {
    public static void main(String [] args) {
        SpringApplication.run(App.class,args);
    }

}

最后我的persistence.xml,位于src / main / resources / META-INF文件夹中:

所以,当我尝试使用这个注入的entityManager时,我得到NullPointerException.注入其他@Autowired字段没有任何问题.这段代码出了什么问题?我需要一些额外的配置吗?
我是初学者(甚至不是初级开发人员),我确实对Spring-boot是什么以及如何配置它有一些误解,比如Spring在xml文件中.如果由于注入EM而需要这样的xml配置,请说明如何执行此操作.

UPD2.依赖


最佳答案
您应该使用spring-boot-starter-data-jpa的依赖项


要使用持久性xml,您应该按照文档中的说明定义bean.

Spring doesn’t require the use of XML to configure the JPA provider,and Spring Boot assumes you want to take advantage of that feature. If you prefer to use persistence.xml then you need to define your own @Bean of type LocalEntityManagerFactoryBean (with id ‘entityManagerFactory’,and set the persistence unit name there.

http://docs.spring.io/spring-boot/docs/current/reference/html/howto-data-access.html#howto-use-traditional-persistence-xml

或者,您可以完全跳过persistence.xml并在application.properties文件中定义连接属性.

从文档中引用

DataSource configuration is controlled by external configuration properties in spring.datasource.*. For example,you might declare the following section in application.properties:

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html#boot-features-connect-to-production-database

(更改驱动程序和其他数据以匹配您的环境)

祝好运!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读