getting NullPointerException when try to persist entity - jpa

I have the following code. When I run the junit test it's creating a table and fields but they are null. I'm also getting a NullPointerException..
Why isn't my user being added?
java.lang.NullPointerException
at com.testproject.repo.JPAUserRepo.addUser(JPAUserRepo.java:15)
at com.testproject.manager.UserManager.saveUser(UserManager.java:18)
at com.testproject.manager.test.UserManagerTest.testSaveUser(UserManagerTest.java:44)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
User.java
#Entity
#Table(name="USER")
#NamedQuery(name="getAllUser", query="SELECT a FROM User a ORDER BY a.userid")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="USER_ID")
private long userid;
#Column(name="USERNAME")
private String username;
#Column(name="PASSWORD")
private String password;
#Column(name="USER_EMAIL")
private String userEmail;
#Column(name="USER_PHONE")
private int userPhone;
public User() {
// TODO Auto-generated constructor stub
}
public User(String username, String password, String email, int userPhone) {
super();
this.username = username;
this.password = password;
this.userEmail = email;
this.userPhone = userPhone;
}
//Getters and Setters
JPAUserRepo.java
public class JPAUserRepo implements UserRepo {
EntityManager em;
#Override
public void addUser(User user) {
em.persist(user);
}
UserManager.java
public class UserManager {
UserRepo userRepo;
public void saveUser(User user){
userRepo.addUser(user);
}
UserManagerTest.java
public class UserManagerTest {
EntityManager em;
UserManager userManager;
User user;
#Before
public void setUp() throws Exception {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("persistenceUnitMySQL");
em = factory.createEntityManager();
userManager = new UserManager();
JPAUserRepo jpaUserRepo = new JPAUserRepo();
userManager.setUserRepo(jpaUserRepo);
em.getTransaction().begin();
user = new User("name", "password", "mail#mail.com", 1561234567);
}
#After
public void tearDown() throws Exception {
em.getTransaction().commit();
}
#Test
public void testSaveUser() {
userManager.saveUser(user);
}
}

Related

Where exactly is the NullPointer Exception?

I'm testing an API Rest resource with Spring and MongoDb.
This is the "chain" relation from Resource to Document:
The resource:
#RestController
#RequestMapping(CustomerResource.CUSTOMERS)
public class CustomerResource {
public static final String CUSTOMERS = "/customers";
public static final String CUSTOMER_ID = "/{id}";
#Autowired
private CustomerController customerController;
#PostMapping
public void createCustomer(#RequestBody CustomerDto customerDto) {
this.customerController.createCustomer(customerDto);
}
...
}
The controller:
#Controller
public class CustomerController {
private CustomerRepository customerRepository;
...
public void createCustomer(CustomerDto customerDto) {
Customer customer = new Customer(customerDto.getName(),
customerDto.getAddress());
this.customerRepository.save(customer);
}
...
}
The dto:
public class CustomerDto {
private String name;
private String address;
private Date date;
public CustomerDto (String name, String address) {
this.name = name;
this.address = address;
}
public CustomerDto() {
}
...(getters & setters & toString())...
}
The repository:
public interface CustomerRepository extends MongoRepository<Customer, String> {
public List<Customer> findByName(String name);
public Customer findById(String id);
public List<Customer> findAll();
#Query("{$and:[{'name':?0},{'address':?1}]}")
Customer findByNameAndAddress(String name, String address);
}
And the document:
#Document
public class Customer {
#Id
private String id;
private String name;
private String address;
private Date date;
public Customer (String name, String address) {
this();
this.name = name;
this.address = address;
this.date = new Date();
}
public Customer() {
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getDate() {
return date;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Customer other = (Customer) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
#Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", address=" + address + ", date=" + date + "]";
}
}
But when running the test, I get the NullPointer Exception, and I don't understand in which point of the proccess is the error.
The resource test:
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
#TestPropertySource(locations = "classpath:test.properties")
public class CustomerResourceFunctionalTesting {
#Rule
public ExpectedException thrown = ExpectedException.none();
#Autowired
private RestService restService;
private CustomerDto customerDto;
#Before
public void before() {
this.customerDto = new CustomerDto("Mark", "Washington");
}
#Test
public void testCreateCustomer() {
restService.restBuilder().path(CustomerResource.CUSTOMERS).body(this.customerDto).post().build();
}
}
I thought that it could be related to not declaring explicitly the id field, but since is would be "instantiated" through the #Id annotation, I don't think there's the problem.
This is the trace:
org.springframework.web.client.HttpServerErrorException: 500
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:88)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:708)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:661)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:636)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:557)
at account.persistence.resources.RestBuilder.build(RestBuilder.java:191)
at account.persistence.resources.CustomerResourceFunctionalTesting.testCreateCustomer(CustomerResourceFunctionalTesting.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:239)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
But I think it would be more useful the console log:
java.lang.NullPointerException: null
at account.persistence.controllers.CustomerController.createCustomer(CustomerController.java:36) ~[classes/:na]
at account.persistence.resources.CustomerResource.createCustomer(CustomerResource.java:36) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_144]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_144]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_144]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) ~[spring-webmvc-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) ~[spring-webmvc-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) ~[spring-webmvc-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) ~[spring-webmvc-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) ~[tomcat-embed-core-8.5.27.jar:8.5.27]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.27.jar:8.5.27]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.27.jar:8.5.27]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.27.jar:8.5.27]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108) ~[spring-web-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.27.jar:8.5.27]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.27.jar:8.5.27]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) ~[tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504) [tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) [tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.27.jar:8.5.27]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_144]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_144]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.27.jar:8.5.27]
at java.lang.Thread.run(Unknown Source) [na:1.8.0_144]
Edit:
This is the RestBuilder (in the same folder that the resoure test):
public class RestBuilder<T> {
private static final String SERVER_URI_DEFAULT = "http://localhost";
private static final int PORT_DEFAULT = 8080;
private RestTemplate restTemplate = new RestTemplate();
private String serverUri;
private int port;
private String path;
private List<Object> expandList;
private Map<String, String> headerValues;
private List<MediaType> mediaTytes;
private String authorization = null;
private Object body = null;
private MultiValueMap<String, String> params;
private Class<T> clazz;
private HttpMethod method;
private boolean log;
public RestBuilder(String serverUri, int port) {
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory()); // org.apache.httpcomponents.httpclient
this.serverUri = serverUri;
this.port = port;
this.path = "";
this.expandList = new ArrayList<>();
this.headerValues = new HashMap<>();
this.mediaTytes = new ArrayList<>();
this.params = new HttpHeaders();
this.log = false;
}
public RestBuilder() {
this(SERVER_URI_DEFAULT, PORT_DEFAULT);
}
public RestBuilder(int port) {
this(SERVER_URI_DEFAULT, port);
}
public RestBuilder(String serverUri) {
this(serverUri, PORT_DEFAULT);
}
public RestBuilder<T> clazz(Class<T> clazz) {
this.clazz = clazz;
return this;
}
public RestBuilder<T> port(int port) {
this.port = port;
return this;
}
public RestBuilder<T> serverUri(String serverUri) {
this.serverUri = serverUri;
return this;
}
public RestBuilder<T> path(String path) {
this.path = this.path + path;
return this;
}
public RestBuilder<T> expand(Object... values) {
for (Object value : values) {
this.expandList.add(value);
}
return this;
}
public RestBuilder<T> basicAuth(String token) {
return basicAuth(token, "");
}
public RestBuilder<T> basicAuth(String nick, String pass) {
String auth = nick + ":" + pass;
String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
String authHeader = "Basic " + encodedAuth;
this.authorization = authHeader;
return this;
}
public RestBuilder<T> param(String key, String value) {
this.params.add(key, value);
return this;
}
public RestBuilder<T> header(String key, String value) {
this.headerValues.put(key, value);
return this;
}
public RestBuilder<T> accept(MediaType mediaType) {
if (this.mediaTytes.isEmpty()) {
this.mediaTytes.add(MediaType.APPLICATION_JSON);
}
this.mediaTytes.add(mediaType);
return this;
}
public RestBuilder<T> body(Object body) {
this.body = body;
return this;
}
public RestBuilder<T> notError() {
restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
protected boolean hasError(HttpStatus statusCode) {
return false;
}
});
return this;
}
private HttpHeaders headers() {
HttpHeaders headers = new HttpHeaders();
for (String key : headerValues.keySet()) {
headers.set(key, headerValues.get(key));
}
if (authorization != null) {
headers.set("Authorization", authorization);
}
if (!this.mediaTytes.isEmpty()) {
headers.setAccept(this.mediaTytes);
}
return headers;
}
private URI uri() {
UriComponents uriComponents;
if (params.isEmpty()) {
uriComponents = UriComponentsBuilder.fromHttpUrl(serverUri + ":" + port + path).build();
} else {
uriComponents = UriComponentsBuilder.fromHttpUrl(serverUri + ":" + port + path).queryParams(params).build();
}
if (!expandList.isEmpty()) {
uriComponents = uriComponents.expand(expandList.toArray());
}
return uriComponents.encode().toUri();
}
public RestBuilder<T> log() {
this.log = true;
return this;
}
public T build() {
ResponseEntity<T> response;
if (log) {
Logger.getLogger(this.getClass()).info(method + " " + this.path + this.headers() + "{" + this.body + "}");
}
if (body != null && !method.equals(HttpMethod.GET)) {
response = restTemplate.exchange(this.uri(), method, new HttpEntity<Object>(body, this.headers()), clazz);
if (log) {
Logger.getLogger(this.getClass()).info(response.getStatusCode() + "==" + response.getHeaders());
}
return response.getBody();
} else {
response = restTemplate.exchange(this.uri(), method, new HttpEntity<Object>(this.headers()), clazz);
if (log) {
Logger.getLogger(this.getClass()).info(response.getStatusCode() + "==" + response.getHeaders());
}
return response.getBody();
}
}
public RestBuilder<T> post() {
this.method = HttpMethod.POST;
return this;
}
public RestBuilder<T> get() {
this.method = HttpMethod.GET;
return this;
}
public RestBuilder<T> put() {
this.method = HttpMethod.PUT;
return this;
}
public RestBuilder<T> patch() {
this.method = HttpMethod.PATCH;
return this;
}
public RestBuilder<T> delete() {
this.method = HttpMethod.DELETE;
return this;
}
}
And the RestService (in the same folder that RestBuilder):
#Service
public class RestService {
#Autowired
private Environment environment;
#Value("${server.contextPath}")
private String contextPath;
private int port() {
return Integer.parseInt(environment.getProperty("local.server.port"));
}
public <T> RestBuilder<T> restBuilder(RestBuilder<T> restBuilder) {
restBuilder.port(this.port());
restBuilder.path(contextPath);
return restBuilder;
}
public RestBuilder<Object> restBuilder() {
RestBuilder<Object> restBuilder = new RestBuilder<>(this.port());
restBuilder.path(contextPath);
return restBuilder;
}
}
Edit 2:
As an alternative, I've tried another approach, as I explain in Resource Access Exception by not using RestService and instead modifying the test and the restbuilder, but then I get a exception when accessing the resource.
Try adding an #Autowired annotation on your CustomerController
#Autowired
private CustomerRepository customerRepository;
Maybe the cause for that NullPointerException is that the repository is not properly injected.

NullPointerException is occurring with createNamedQuery and then persistence unit logins successfully

I can't seem to solve this issue. I have tried googling but can't put the pieces together to solve it. I have the following stack trace:
Warning: java.lang.NullPointerException
at org.eclipse.persistence.platform.server.ServerPlatformUtils.createServerPlatform(ServerPlatformUtils.java:99)
at org.eclipse.persistence.sessions.factories.SessionManager.init(SessionManager.java:77)
at org.eclipse.persistence.sessions.factories.SessionManager.<clinit>(SessionManager.java:71)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.addSessionToGlobalSessionManager(EntityManagerSetupImpl.java:907)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.initSession(EntityManagerSetupImpl.java:2671)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:675)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getAbstractSession(EntityManagerFactoryDelegate.java:205)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.createEntityManagerImpl(EntityManagerFactoryDelegate.java:305)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:337)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:318)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper._getDelegate(EntityManagerWrapper.java:197)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.createNamedQuery(EntityManagerWrapper.java:521)
at session.CategoryFacade.findRandom(CategoryFacade.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:64)
at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at com.sun.proxy.$Proxy173.findRandom(Unknown Source)
at session.__EJB31_Generated__CategoryFacade__Intf____Bean__.findRandom(Unknown Source)
at actions.ActionFacade.setFeaturedCategories(ActionFacade.java:82)
at actions.HomeAction.execute(HomeAction.java:16)
at controller.ControllerServlet.service(ControllerServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
Info: EclipseLink, version: Eclipse Persistence Services - 2.6.1.v20150605-31e8258
Info: /file:/Users/csexton/NetBeansProjects/ReadersParadise/build/web/WEB-INF/classes/_AffableBeanPU login successful
So if you look at the last two lines my persistent unit isn't logging in until I try to use the entity manager. If I do another query after the first one, everything is good, no errors, nothing......Error occurs on the createNamedQuery. The query exists and matches the exact name. I can call the same method twice and the first one causes a NPE but the second one works fine.
#Stateless(name="CategoryFacade")
public class CategoryFacade extends AbstractFacade<Category> {
#PersistenceContext(unitName = "AffableBeanPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public CategoryFacade() {
super(Category.class);
}
public List<Category> findRandom(int limit) {
return getEntityManager()
.createNamedQuery("Category.findRandomByLimit")
.setParameter(1, limit)
.getResultList();
}
}
I am doing a jndi lookup for the class
public class ActionFacade implements AutoCloseable {
private static ThreadLocal<ActionFacade> instance = new ThreadLocal<>();
private HttpServletRequest request;
private HttpSession session;
private CategoryFacade categoryFacade;
private BookFacade bookFacade;
private OrderManager orderManager;
private ShoppingCart cart;
public ActionFacade(HttpServletRequest request) {
this.request = request;
this.session = request.getSession();
try {
Context ctx = new InitialContext();
this.categoryFacade = (CategoryFacade) ctx.lookup(
"java:global/ReadersParadise/CategoryFacade!session.CategoryFacade");
System.out.print("JNDI lookup complete.");
this.bookFacade = (BookFacade) ctx.lookup(
"java:global/ReadersParadise/BookFacade!session.BookFacade");
this.orderManager = (OrderManager) ctx.lookup(
"java:global/ReadersParadise/OrderManager!session.OrderManager");
} catch (NamingException ex) {
System.err.println(ex);
}
}
public static ActionFacade create(HttpServletRequest request) {
ActionFacade facade = new ActionFacade(request);
instance.set(facade);
return facade;
}
public static ActionFacade getCurrentInstance() {
return instance.get();
}
#Override
public void close() {
instance.remove();
}
public void setSelectedCategory() {
String categoryName = request.getParameter("category");
Category selectedCategory = categoryFacade.findByName(categoryName);
if (selectedCategory == null) {
selectedCategory = categoryFacade.find(1);
}
session.setAttribute("selectedCategory", selectedCategory);
Collection<Book> categoryBooks = selectedCategory.getBookCollection();
session.setAttribute("categoryBooks", categoryBooks);
}
public void setAllCategories() {
request.setAttribute("categories", categoryFacade.findAll());
}
}
Then in my servlet I am using the ActionFacade like this....
try(ActionFacade facade = ActionFacade.create(request)) {
Action action = ActionFactory.getAction(request);
String view = action.execute(facade);
System.out.println(request.getServletPath());
if (request.getServletPath().equals("") || view.equals(request.getServletPath().substring(1))) {
request.getRequestDispatcher("/WEB-INF/views/" + view + ".jsp").forward(request, response);
} else {
response.sendRedirect(view);
}
} catch (NullPointerException e) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} catch (Exception e) {
throw new ServletException("Executing action failed.", e);
}
This is the category entity
#Entity
#Table(name = "category")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Category.findAll", query = "SELECT c FROM Category c"),
#NamedQuery(name = "Category.findById", query = "SELECT c FROM Category c WHERE c.id = :id"),
#NamedQuery(name = "Category.findByName", query = "SELECT c FROM Category c WHERE c.name= :name")
})
#NamedNativeQuery(name = "Category.findRandomByLimit",
query = "SELECT * FROM Category ORDER BY RAND() LIMIT ?1")
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "name")
private String name;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "category")
private Collection<Book> bookCollection;
public Category() {
}
public Category(Integer id) {
this.id = id;
}
public Category(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlTransient
public Collection<Book> getBookCollection() {
return bookCollection;
}
public void setBookCollection(Collection<Book> bookCollection) {
this.bookCollection = bookCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Category)) {
return false;
}
Category other = (Category) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.Category[ id=" + id + " ]";
}
}
Category Action Class which uses the ActionFacade
public class CategoryAction implements Action {
#Override
public String execute(ActionFacade facade) throws Exception {
facade.setSelectedCategory();
facade.setAllCategories();
return "category";
}
}
I think it is a problem of Glassfish 4.1.1 described here:
https://java.net/jira/browse/GLASSFISH-21468
According this, it may help, if you add
<property name="eclipselink.target-server" value="Glassfish"/>
to your persistence.xml

java.sql.SQLSyntaxErrorException: is not a column in table

I'm working on a JavaEE application using EJB and JPA
Two of my Entities are:
#Entity
public class Utente implements Serializable {
private static final long serialVersionUID = 1L;
#Override
public String toString() {
return "Utente [cod_utente=" + cod_utente + ", nome_utente="
+ nome_utente + ", morada_utente=" + morada_utente
+ ", dnasc_utente=" + dnasc_utente + ", tel_utente="
+ tel_utente + "]";
}
/**
*
*/
public Utente(String nome_utente, String morada_utente,
GregorianCalendar dnasc_utente, int tel_utente) {
super();
this.nome_utente = nome_utente;
this.morada_utente = morada_utente;
this.dnasc_utente = dnasc_utente;
this.tel_utente = tel_utente;
}
#Id
#GeneratedValue
private int cod_utente;
private String nome_utente;
private String morada_utente;
#Temporal(TemporalType.DATE)
private GregorianCalendar dnasc_utente;
private int tel_utente;
private List<GregorianCalendar> agenda;
#OneToMany
#JoinColumn(nullable=true)
private List<Prescricao> lista_presc;
public Utente(){
super();
}
public List<Prescricao> getLista_presc() {
return lista_presc;
}
public void setLista_presc(List<Prescricao> lista_presc) {
this.lista_presc = lista_presc;
}
public List<GregorianCalendar> getAgenda() {
return agenda;
}
public void setAgenda(List<GregorianCalendar> agenda) {
this.agenda = agenda;
}
public int getCod_utente() {
return cod_utente;
}
public void setCod_utente(int cod_utente) {
this.cod_utente = cod_utente;
}
public String getNome_utente() {
return nome_utente;
}
public void setNome_utente(String nome_utente) {
this.nome_utente = nome_utente;
}
public String getMorada_utente() {
return morada_utente;
}
public void setMorada_utente(String morada_utente) {
this.morada_utente = morada_utente;
}
public GregorianCalendar getDnasc_utente() {
return dnasc_utente;
}
public void setDnasc_utente(GregorianCalendar dnasc_utente) {
this.dnasc_utente = dnasc_utente;
}
public int getTel_utente() {
return tel_utente;
}
public void setTel_utente(int tel_utente) {
this.tel_utente = tel_utente;
}
}
and:
#Entity
public class FichaClinica implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
#Id
#GeneratedValue
private int cod_ficha;
#OneToOne
#JoinColumn
private Utente utente;
#OneToMany
#JoinColumn(nullable=true)
private List <AtoEnfermagem> lista_atos_enf;
#OneToMany
#JoinColumn(nullable=true)
private List <AtoMedico> lista_atos_medicos;
#OneToMany
#JoinColumn(nullable=true)
private List<Consulta> lista_consultas;
public FichaClinica(){ //construtor vazio
super();
}
public Utente getUtente() {
return utente;
}
public void setUtente(Utente utente) {
this.utente = utente;
}
#Override
public String toString() {
return "FichaClinica [cod_ficha=" + cod_ficha + ", lista_atos_enf="
+ lista_atos_enf + ", lista_atos_medicos=" + lista_atos_medicos
+ ", lista_consultas=" + lista_consultas + "]";
}
public FichaClinica(Utente utente){
super();
this.utente=utente;
}
public FichaClinica(Utente utente,
ArrayList<AtoEnfermagem> lista_atos_enf,
ArrayList<AtoMedico> lista_atos_medicos,
ArrayList<Consulta> lista_consultas) {
super();
this.lista_atos_enf = lista_atos_enf;
this.lista_atos_medicos = lista_atos_medicos;
this.lista_consultas = lista_consultas;
}
//Adicionar elementos às listas
public int getCod_ficha() {
return cod_ficha;
}
public void setCod_ficha(int cod_ficha) {
this.cod_ficha = cod_ficha;
}
public List<AtoEnfermagem> getLista_atos_enf() {
return lista_atos_enf;
}
public void setLista_atos_enf(List<AtoEnfermagem> lista_atos_enf) {
this.lista_atos_enf = lista_atos_enf;
}
public List<AtoMedico> getLista_atos_medicos() {
return lista_atos_medicos;
}
public void setLista_atos_medicos(ArrayList<AtoMedico> lista_atos_medicos) {
this.lista_atos_medicos = lista_atos_medicos;
}
public List<Consulta> getLista_consultas() {
return lista_consultas;
}
public void setLista_consultas(ArrayList<Consulta> lista_consultas) {
this.lista_consultas = lista_consultas;
}
public void adicionar_ato_medico(AtoMedico a_medico){
lista_atos_medicos.add(a_medico);
}
public void adiconar_consulta(Consulta c){
lista_consultas.add(c);
}
public void adicionar_ato_enf(AtoEnfermagem a_enf){
lista_atos_enf.add(a_enf);
}
}
When I try to execute the following method:
#Override
public String cria_utente(String nome_utente, String morada_utente,GregorianCalendar dnasc_utente, int tel_utente) {
Utente u=new Utente(nome_utente,morada_utente,dnasc_utente,tel_utente);
em.persist(u);
FichaClinica fc=new FichaClinica(u);
em.persist(fc);
return "Utente "+Integer.toString(u.getCod_utente())+" (Ficha Clinica "+Integer.toString(fc.getCod_ficha())+") cirado!";
}
An error occurs. Here is the complete stacktrace:
Exception in thread "main" javax.ejb.EJBException: Transaction aborted
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:725)
at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:503)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4566)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2074)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2044)
at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:212)
at com.sun.ejb.containers.EJBObjectInvocationHandlerDelegate.invoke(EJBObjectInvocationHandlerDelegate.java:79)
at com.sun.proxy.$Proxy238.cria_utente(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie.dispatchToMethod(ReflectiveTie.java:143)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:173)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:1425)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleInput(MessageMediatorImpl.java:930)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:213)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:694)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.dispatch(MessageMediatorImpl.java:496)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.doWork(MessageMediatorImpl.java:2222)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)
Caused by: javax.transaction.RollbackException: Transaction marked for rollback.
at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:490)
at com.sun.enterprise.transaction.JavaEETransactionManagerSimplified.commit(JavaEETransactionManagerSimplified.java:854)
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:719)
... 24 more
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: 'UTENTE_COD_UTENTE' is not a column in table or VTI 'APP.FICHACLINICA'.
Error Code: 20000
Call: INSERT INTO FICHACLINICA (COD_FICHA, UTENTE_COD_UTENTE) VALUES (?, ?)
bind => [2 parameters bound]
Query: InsertObjectQuery(FichaClinica [cod_ficha=10, lista_atos_enf={[]}, lista_atos_medicos={[]}, lista_consultas={[]}])
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl$1.handleException(EntityManagerSetupImpl.java:696)
at org.eclipse.persistence.transaction.AbstractSynchronizationListener.handleException(AbstractSynchronizationListener.java:275)
at org.eclipse.persistence.transaction.AbstractSynchronizationListener.beforeCompletion(AbstractSynchronizationListener.java:170)
at org.eclipse.persistence.transaction.JTASynchronizationListener.beforeCompletion(JTASynchronizationListener.java:68)
at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:452)
... 26 more
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: 'UTENTE_COD_UTENTE' is not a column in table or VTI 'APP.FICHACLINICA'.
Error Code: 20000
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:340)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:682)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:558)
at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:2002)
at org.eclipse.persistence.sessions.server.ClientSession.executeCall(ClientSession.java:298)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:242)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:228)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.insertObject(DatasourceCallQueryMechanism.java:377)
at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:165)
at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:180)
at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.insertObjectForWrite(DatabaseQueryMechanism.java:489)
at org.eclipse.persistence.queries.InsertObjectQuery.executeCommit(InsertObjectQuery.java:80)
at org.eclipse.persistence.queries.InsertObjectQuery.executeCommitWithChangeSet(InsertObjectQuery.java:90)
at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.executeWriteWithChangeSet(DatabaseQueryMechanism.java:301)
at org.eclipse.persistence.queries.WriteObjectQuery.executeDatabaseQuery(WriteObjectQuery.java:58)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:899)
at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:798)
at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWorkObjectLevelModifyQuery(ObjectLevelModifyQuery.java:108)
at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWork(ObjectLevelModifyQuery.java:85)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2896)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1804)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1786)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1737)
at org.eclipse.persistence.internal.sessions.CommitManager.commitNewObjectsForClassWithChangeSet(CommitManager.java:226)
at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsForClassWithChangeSet(CommitManager.java:193)
at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsWithChangeSet(CommitManager.java:138)
at org.eclipse.persistence.internal.sessions.AbstractSession.writeAllObjectsWithChangeSet(AbstractSession.java:4207)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabase(UnitOfWorkImpl.java:1441)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1531)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.issueSQLbeforeCompletion(UnitOfWorkImpl.java:3168)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.issueSQLbeforeCompletion(RepeatableWriteUnitOfWork.java:352)
at org.eclipse.persistence.transaction.AbstractSynchronizationListener.beforeCompletion(AbstractSynchronizationListener.java:158)
... 28 more
Caused by: java.sql.SQLSyntaxErrorException: 'UTENTE_COD_UTENTE' is not a column in table or VTI 'APP.FICHACLINICA'.
at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
at org.apache.derby.client.am.Connection.prepareStatement(Unknown Source)
at com.sun.gjc.spi.base.ConnectionHolder.prepareStatement(ConnectionHolder.java:586)
at com.sun.gjc.spi.jdbc40.ConnectionWrapper40.prepareCachedStatement(ConnectionWrapper40.java:255)
at com.sun.gjc.spi.jdbc40.ConnectionWrapper40.prepareCachedStatement(ConnectionWrapper40.java:52)
at com.sun.gjc.spi.ManagedConnectionImpl.prepareCachedStatement(ManagedConnectionImpl.java:992)
at com.sun.gjc.spi.jdbc40.ConnectionWrapper40.prepareStatement(ConnectionWrapper40.java:173)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.prepareStatement(DatabaseAccessor.java:1556)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.prepareStatement(DatabaseAccessor.java:1505)
at org.eclipse.persistence.internal.databaseaccess.DatabaseCall.prepareStatement(DatabaseCall.java:778)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:619)
... 58 more
Caused by: org.apache.derby.client.am.SqlException: 'UTENTE_COD_UTENTE' is not a column in table or VTI 'APP.FICHACLINICA'.
at org.apache.derby.client.am.Statement.completeSqlca(Unknown Source)
at org.apache.derby.client.net.NetStatementReply.parsePrepareError(Unknown Source)
at org.apache.derby.client.net.NetStatementReply.parsePRPSQLSTTreply(Unknown Source)
at org.apache.derby.client.net.NetStatementReply.readPrepareDescribeOutput(Unknown Source)
at org.apache.derby.client.net.StatementReply.readPrepareDescribeOutput(Unknown Source)
at org.apache.derby.client.net.NetStatement.readPrepareDescribeOutput_(Unknown Source)
at org.apache.derby.client.am.Statement.readPrepareDescribeOutput(Unknown Source)
at org.apache.derby.client.am.PreparedStatement.readPrepareDescribeInputOutput(Unknown Source)
at org.apache.derby.client.am.PreparedStatement.flowPrepareDescribeInputOutput(Unknown Source)
at org.apache.derby.client.am.PreparedStatement.prepare(Unknown Source)
at org.apache.derby.client.am.Connection.prepareStatementX(Unknown Source)
... 68 more
Can please someone help me find what's wrong here?
The error occurs because you probably didn't create the column UTENTE_COD_UTENTE in the table APP.FICHACLINICA. Creating the column (type integer) should fix the problem.
The code:
#OneToOne
#JoinColumn
private Utente utente;
doesn't specify a name for the join column and therefore creates a default join column based on this rule (from #JoinColumn):
Default (only applies if a single join column is used): The
concatenation of the following: the name of the referencing
relationship property or field of the referencing entity or embeddable
class; ""; the name of the referenced primary key column. If there is
no such referencing relationship property or field in the entity, or
if the join is for an element collection, the join column name is
formed as the concatenation of the following: the name of the entity;
""; the name of the referenced primary key column.
You can set a name for the join column like this:
#OneToOne
#JoinColumn(name = "SOMETHING_UTENTE")
private Utente utente;
But then you'll have to create a column named like this.
See also:
JPA JoinColumn vs mappedBy

getIdentifier method of PersistenceUnitUtil not working for Composite keys

I am getting below error when trying to retrieve identity using getIdentifier method of PersistenceUnitUtil. Is there anything I am doing wrong.
Local Exception Stack:
Exception [EclipseLink-0] (Eclipse Persistence Services - 2.4.2.v20130514-5956486): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: An internal error occurred accessing the primary key object [202].
Internal Exception: java.lang.NullPointerException
Descriptor: RelationalDescriptor(com.sample.Person --> [DatabaseTable(PERSON)])
at org.eclipse.persistence.exceptions.DescriptorException.errorUsingPrimaryKey(DescriptorException.java:1923)
at org.eclipse.persistence.internal.jpa.CMP3Policy$FieldAccessor.setValue(CMP3Policy.java:686)
at org.eclipse.persistence.descriptors.CMPPolicy.createPrimaryKeyInstance(CMPPolicy.java:453)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.getIdentifier(EntityManagerFactoryImpl.java:75)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getIdentifier(EntityManagerFactoryDelegate.java:679)
at com.sample.PersistenceUtil.getEntityIdentifier(PersistenceUtil.java:27)
at com.sample.PersistenceUtil.getEntityIdentifier(PersistenceUtil.java:18)
at com.sample.OverrideUtilTest.canconfirmEntityEqualsforCompositeId2(OverrideUtilTest.java:147)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.NullPointerException
at org.eclipse.persistence.internal.jpa.CMP3Policy$FieldAccessor.setValue(CMP3Policy.java:682)
... 29 more
The code sample I am trying is this:
#Entity
#IdClass(PersonPK.class)
#Table(name = "PERSON")
public class Person {
#Id
#Column(name = "CODE_C")
private String code;
#Column(name = "NAME_C")
private String name;
#Id
#Column(name = "COUNTRY_C")
private String country;
public Person() {
}
public Person(String code, String country) {
this.code = code;
this.country = country;
}
public String getCode() {
return this.code;
}
public String getCountry() {
return this.country;
}
}
public class PersonPK implements Serializable {
private static final long serialVersionUID = 1L;
private final String code;
private final String country;
public PersonPK(String city, String country) {
super();
this.code = city;
this.country = country;
}
#Override
public boolean equals(Object object) {
return super.equals (object);
}
#Override
public int hashCode() {
return super.hashCode();
}
}
The code to retrieve identity I am using is
getEntityManagerFactory(persistenceUnitName).getPersistenceUnitUtil()
.getIdentifier(entity);
Any help is appreciated
The primary key class must be public and must have a public no-arg constructor.
Hibernate message in similar situation is a little bit more informative
javax.persistence.PersistenceException: org.hibernate.InstantiationException: No default constructor for entity: : PersonPK
Solution: Add default constructor to PersonPK

When using inheritance throw exception java.lang.NoSuchFieldError: __odbTracker on NetBeans 7.3 Jboss 7.1.1 ObjectDB 2.5.1

When using inheritance throw exception java.lang.NoSuchFieldError: __odbTracker on NetBeans 7.3 + ObjectDB 2.5.1 + Jboss 7.1.1, but works fine on NetBeans 7.3 + ObjectDB 2.5.1 + GlassFish 3.1
#Entity
public class Person extends AbstractObject {
private static final long serialVersionUID = 1L;
#ManyToOne #Index
private City city;
#OneToMany(mappedBy = "owner")
private List<City> cities;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public City getCity() {
return city;
}
public void setCity(City city) {
this.city = city;
}
public List<City> getCitys() {
return cities;
}
public void setCitys(List<City> citys) {
this.cities = citys;
}
}
#Entity
public class City extends AbstractObject {
private static final long serialVersionUID = 33L;
#OneToMany(mappedBy = "city")
private List<Person> persons;
#ManyToOne #Index
private Person owner;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Person> getPersons() {
return persons;
}
public void setPersons(List<Person> persons) {
this.persons = persons;
}
public Person getOwner() {
return owner;
}
public void setOwner(Person owner) {
this.owner = owner;
}
}
#Entity
public abstract class AbstractObject implements IAbstractObject {
//private static final long serialVersionUID = 1L;
#Id
private String id = UUID.randomUUID().toString();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof AbstractObject)) {
return false;
}
AbstractObject other = (AbstractObject) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "test.AbstractObject[ id=" + id + " ]";
}
}
This code throw exception:
Person person = new Person();
person.setName(name);
City city = new City();
city.setName("Москва");
person.setCity(city);
entityManager.persist(city);
entityManager.persist(person);
The exception:
java.lang.NoSuchFieldError: __odbTracker
test.City.__odbSet_name(City.java:1)
test.City.setName(City.java:39)
ejb.PersonBean.create(PersonBean.java:32)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.jboss.as.ee.component.ManagedReferenceMethodInterceptorFactory$ManagedReferenceMethodInterceptor.processInvocation(ManagedReferenceMethodInterceptorFactory.java:72)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:374)
org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.doMethodInterception(Jsr299BindingsInterceptor.java:127)
org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.processInvocation(Jsr299BindingsInterceptor.java:135)
org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:36)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.invocation.WeavedInterceptor.processInvocation(WeavedInterceptor.java:53)
org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:36)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.as.jpa.interceptor.SBInvocationInterceptor.processInvocation(SBInvocationInterceptor.java:47)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.as.weld.ejb.EjbRequestScopeActivationInterceptor.processInvocation(EjbRequestScopeActivationInterceptor.java:82)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.invocation.InitialInterceptor.processInvocation(InitialInterceptor.java:21)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
org.jboss.as.ee.component.interceptors.ComponentDispatcherInterceptor.processInvocation(ComponentDispatcherInterceptor.java:53)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.as.ejb3.component.pool.PooledInstanceInterceptor.processInvocation(PooledInstanceInterceptor.java:51)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInOurTx(CMTTxInterceptor.java:228)
org.jboss.as.ejb3.tx.CMTTxInterceptor.required(CMTTxInterceptor.java:304)
org.jboss.as.ejb3.tx.CMTTxInterceptor.processInvocation(CMTTxInterceptor.java:190)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.as.ejb3.component.interceptors.CurrentInvocationContextInterceptor.processInvocation(CurrentInvocationContextInterceptor.java:41)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.as.ejb3.component.interceptors.LoggingInterceptor.processInvocation(LoggingInterceptor.java:59)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.as.ee.component.NamespaceContextInterceptor.processInvocation(NamespaceContextInterceptor.java:50)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.as.ejb3.component.interceptors.AdditionalSetupInterceptor.processInvocation(AdditionalSetupInterceptor.java:32)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.as.ee.component.TCCLInterceptor.processInvocation(TCCLInterceptor.java:45)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
org.jboss.as.ee.component.ViewService$View.invoke(ViewService.java:165)
org.jboss.as.ee.component.ViewDescription$1.processInvocation(ViewDescription.java:173)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
org.jboss.as.ee.component.ProxyInvocationHandler.invoke(ProxyInvocationHandler.java:72)
ejb.PersonBeanLocal$$$view66.create(Unknown Source)
servlet.TestServlet.processRequest(TestServlet.java:68)
servlet.TestServlet.doGet(TestServlet.java:107)
javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
org.jboss.weld.servlet.ConversationPropagationFilter.doFilter(ConversationPropagationFilter.java:62)
if remove the inheritance works fine. On GlassFish 3.1 with inheritance also works fine.
Why "person.setName(name);" works fine? But "city.setName("Москва");" throw exception
Thanks for your help.
if someone is interested in the answer - objectdb support
I added this code in build.xml. the project works fine.
<target name="-post-compile">
<java classname="com.objectdb.Enhancer" fork="true" classpath="C:/projects/test/lib/objectdb.jar">
<arg line="-s ./build/classes/test/*.class"/>
</java>
</target>