我正在尝试使用 Spring Boot 的简单编码,在实体管理器中使用 @PersistenceContext,在 MySQL 中创建一个对象,但我发现我的实体管理器对象为空,不知道为什么,因为使用的方法实体管理器有@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;
}
这是我调用实体管理器并且始终为空的地方:
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-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>
我认为在你的情况下你应该与休眠会话工厂 and 休眠会话代替实体经理,如果您想与实体经理合作,只需转到您的应用程序属性在您的资源文件中并添加以下内容:
spring.datasource.url = jdbc:mysql://localhost:3306/testDB
# Username and password
spring.datasource.username = root
spring.datasource.password = global
# Show or not log for each sql query
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
不要忘记在 pom.xml 中添加 spring jpa 依赖项
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)