微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Spring-boot JPA EntityManager注入失败

在我的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文件夹中:

persistence-unit name="data" transaction-type="RESOURCE_LOCAL">
    sqlServerDialect" />
        sqlserver://localhost:1433;databaseName=qwerty;sendStringParametersAsUnicode=false" />
        sqlserver.jdbc.sqlServerDriver" />
        sql" value="false" />
    persistence-unit>

所以,当我尝试使用这个注入的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

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

祝好运!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐