【发布时间】:2017-03-20 14:22:36
【问题描述】:
我正在尝试使用 Spring Boot 的简单编码,使用 entitymanager 中的 @PersistenceContext 在 MySQL 中创建一个对象,但我发现我的 entitymanager 对象为 null 并且不知道为什么,因为该方法即使用entitymanager 有@transaction 注解。
这是我调用插入数据的方法的代码:
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
public class VehicleService implements IVehicleService {
@Autowired
IFileService fileService;
@Transactional
public void addVehicle(Vehicle vehicle) throws ServiceException{
Vehicle vehicleNew = new Vehicle();
vehicleNew.setName(vehicle.getName());
vehicleNew.setType(vehicle.getType());
vehicleNew.setEnrollment(vehicle.getEnrollment());
try{
fileService.createVehicle(vehicle);
}catch(Exception e){
}
}
}
import org.hibernate.service.spi.ServiceException;
import org.springframework.transaction.annotation.Transactional;
public interface IFileService {
@Transactional
void createVehicle(Vehicle vehicle) throws ServiceException;
}
这里是我调用 entitymanager 的地方,并且总是为空:
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Component;
@Component
public class FileService implements IFileService{
@PersistenceContext
protected EntityManager entityManager;
public void createVehicle(Vehicle vehicle) {
System.out.println("Inserting........................");
entityManager.persist(vehicle);
System.out.println("Inserted!");
return;
}
}
hibernate.cfg.xml
<hibernate-configuration>
<session-factory name="hibernateSessionFactory">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">global</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/testDB</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- <property name="hibernate.hbm2ddl.auto">create</property> -->
<mapping class="com.org.testing.Vehicle"/>
</session-factory>
</hibernate-configuration>
【问题讨论】:
-
你能显示你的 application.propreties 文件吗?
-
更新了我的问题!
标签: java mysql entitymanager spring-transactions