I'm trying to use a simple coding with Spring Boot, using the @PersistenceContext in the entitymanager, to create a object in MySQL, but I'm getting that my entitymanager object is null and not sure why, because the method that is using the entitymanager hast the @transaction annotation.
This is my code where I call the method to insert the data:
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;
}
Here is where I call the entitymanager and always is null:
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>