I am trying to do my homework in which I need to create a Restful Webservice using Spring. In addition, I use JPA (Eclipselink) to edit, search and display records in the database.
My persistence.xml is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="test">
<class>at.test.entities.UserEntity</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://myserver:3306/somedatabase"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="xxx"/>
<property name="javax.persistence.jdbc.password" value="xxx"/>
</properties>
</persistence-unit>
</persistence>
When I try to get entityManager via
entityManager = Persistence.createEntityManagerFactory("test").createEntityManager();
it works fine, but if I want to do it using annotation @PersistenceContext
@PersistenceContext(unitName = "test")
private EntityManager entityManager;
it does not work with the following stacktrace command:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestHandler': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'test' is defined
How it works:
@RestController
@RequestMapping(value = "/users")
public class RequestHandler {
private EntityManager entityManager;
@RequestMapping(value = "/test", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<UserTest> test(@RequestParam(value = "asd", defaultValue = "") String name) {
entityManager = Persistence.createEntityManagerFactory("test").createEntityManager();
UserTest user = entityManager.find(UserTest.class, 1);
entityManager.getTransaction().begin();
entityManager.persist(new UserTest("ASDASD", "ASDASdjnwco2eno2oc"));
entityManager.getTransaction().commit();
return new ResponseEntity<UserTest>(user, HttpStatus.CREATED);
}
}
How it doesn’t work:
@RestController
@RequestMapping(value = "/users")
public class RequestHandler {
@PersistenceContext(unitName = "test")
private EntityManager entityManager;
@RequestMapping(value = "/test", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<UserTest> test(@RequestParam(value = "asd", defaultValue = "") String name) {
UserTest user = entityManager.find(UserTest.class, 1);
entityManager.getTransaction().begin();
entityManager.persist(new UserTest("ASDASD", "ASDASdjnwco2eno2oc"));
entityManager.getTransaction().commit();
return new ResponseEntity<UserTest>(user, HttpStatus.CREATED);
}
}
thanks for the help
Decision
Both solutions, one of AdrianDuta and Branislav Lazic works. You can either define your beans or persistence file via an XML file or configure them for a Java class.
Although I have now used this template / example:
spring-boot-mysql-springdatajpa-hibernate