问题描述
我在我的项目中使用了 Google guice
,现在我尝试将框架完全转换为 SpringBoot
.
I was using Google guice
in my project and now I tried to convert the framework to SpringBoot
totally.
我为 persistence.xml
配置了 Bean,如下面的
I configured the Bean for persistence.xml
like below in
@Autowired
@Bean(name = "transactionManager")
public LocalContainerEntityManagerFactoryBean entityManagerFactory()
{
LocalContainerEntityManagerFactoryBean lEMF = new LocalContainerEntityManagerFactoryBean();
lEMF.setPersistenceUnitName("leaseManagementPU");
lEMF.setPersistenceXmlLocation("persistence.xml");
return lEMF;
}
现在我需要配置(注入)EntityManager
em,来做JPA操作
,比如em.persist()
,em.find
等...我如何配置,也有人尝试用示例代码解释这一点
Now I need to configure(Inject) EntityManager
em, to do JPA operations
like em.persist()
, em.find
etc... How do I configure, also someone try to explain this with sample code
推荐答案
使用 Spring Boot
不需要像 persistence.xml
这样的任何配置文件.您可以使用 annotations
进行配置,只需在
With Spring Boot
its not necessary to have any config file like persistence.xml
. You can configure with annotations
Just configure your DB config for JPA in the
spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@DB...
spring.datasource.username=username
spring.datasource.password=pass
spring.jpa.database-platform=org.hibernate.dialect....
spring.jpa.show-sql=true
然后您可以使用 Spring 提供的 CrudRepository
,其中您有标准的 CRUD
事务方法.在那里你也可以实现你自己的 SQL's
,比如 JPQL
.
Then you can use CrudRepository
provided by Spring where you have standard CRUD
transaction methods. There you can also implement your own SQL's
like JPQL
.
@Transactional
public interface ObjectRepository extends CrudRepository<Object, Long> {
...
}
如果您仍然需要使用Entity Manager
,您可以创建另一个类.
And if you still need to use the Entity Manager
you can create another class.
public class ObjectRepositoryImpl implements ObjectCustomMethods{
@PersistenceContext
private EntityManager em;
}
这应该在你的 pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.11.Final</version>
</dependency>
</dependencies>
这篇关于Spring boot - 配置EntityManager的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!