My error is this:
org.postgresql.util.PSQLException: This connection has been closed.
at org.postgresql.jdbc.PgConnection.checkClosed(PgConnection.java:766)
at org.postgresql.jdbc.PgConnection.prepareStatement(PgConnection.java:1582)
at org.postgresql.jdbc.PgConnection.prepareStatement(PgConnection.java:372)
at com.ifpb.pw1.sysfood.dao.impl.UsuarioDaoBD.buscar(UsuarioDaoBD.java:61)
at com.ifpb.pw1.sysfood.managers.GerenciadorUsuario.buscaUsuario(GerenciadorUsuario.java:37)
at com.ifpb.pw1.sysfood.command.impl.Login.execute(Login.java:55)
at com.ifpb.pw1.sysfood.servlets.FrontController.processRequest(FrontController.java:26)
at com.ifpb.pw1.sysfood.servlets.FrontController.doPost(FrontController.java:48)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:491)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:764)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1388)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
But before my application authenticates the user through a query in the database (postgresql), and does not present any error.
But when I query to get the user data I get the following error (as shown above).
My code is this:
public Usuario buscar(String email) {
try {
String sql = "SELECT * FROM Usuario WHERE email = ?";
PreparedStatement stmt = conexao.prepareStatement(sql);
stmt.setString(1, email);
ResultSet resultado = stmt.executeQuery();
if(resultado.next()){
Usuario u = new Usuario(
resultado.getInt("id"),
resultado.getString("nome"),
resultado.getString("email"),
resultado.getString("profissao"),
resultado.getString("sexo"),
resultado.getBytes("fotoPerfil")
);
System.out.println("User from dao: " + u);
resultado.close();
stmt.close();
conexao.close();
return u;
}
resultado.close();
stmt.close();
conexao.close();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
Is something wrong with my code? What is wrong? can you help me?
I've done a lot of research, but so far I can not find anything about it.
Related
I am trying to port my application which writing InfluxDb data to TDengine via its schemaless interface. I think it should be very easy but actually not.
Java code is below:
public void batchInsert() {
JSONObject json = new JSONObject();
json.put("f0", "tt");
json.put("f1", "aa");
json.put("f2", "tt");
json.put("f3", "aa");
json.put("f4", "tt");
json.put("f5", "aa");
json.put("f6", "tt");
json.put("f7", "aa");
BatchPoints batchPoints = BatchPoints.database(database)
.precision(TimeUnit.MILLISECONDS)
.build();
for (int i = 0; i < 1; i++) {
Point point = Point.measurement(measurement)
.time(System.currentTimeMillis() - 3600000, TimeUnit.MILLISECONDS)
.addField("current", 10.2)
.addField("voltage", 219 + i)
.addField("phase", 0.32 + i)
.addField("strAtri", "123456781234567812345678")
.addField("json$j", json.toJSONString())
.tag("__deviceId__", "sensor" + i)
.build();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
batchPoints.point(point);
}
try {
JSONObject responseBody;
String sql = "CREATE DATABASE IF NOT EXISTS " + database
+ " REPLICA 1 QUORUM 1 DAYS 1 KEEP 365 UPDATE 2;";
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_JSON);
header.set("Authorization", getBasicAuth("root", "taosdata"));
HttpEntity<String> httpEntity = new HttpEntity<>(sql, header);
responseBody = restTemplate.postForObject(tdengineUrl, httpEntity, JSONObject.class);
System.out.println("database=" + responseBody.get("status"));
System.out.println(batchPoints.lineProtocol());
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(tdengineInfluxdbUrl, batchPoints.lineProtocol(), JSONObject.class);
if (responseEntity.getStatusCodeValue() == 204) {
System.out.println(responseEntity.getStatusCodeValue());
}
} catch (Exception e) {
e.printStackTrace();
}
I got result on the console:
sensor,deviceId=sensor0 current=10.2,json$j="{"f6":"tt","f7":"aa","f0":"tt","f1":"aa","f2":"tt","f3":"aa","f4":"tt","f5":"aa"}",phase=0.32,strAtri="123456781234567812345678",voltage=219i 1647569782596
org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 Internal Server Error: [{"code":"internal error","message":"[0x21f] Invalid column length"}]
at org.springframework.web.client.HttpServerErrorException.create(HttpServerErrorException.java:100)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:186)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:125)
at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:782)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:740)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:674)
at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:449)
at com.rootcloud.controller.InfluxController.batchInsert(InfluxController.java:112)
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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1589)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
I don't know why and appreciated if someone can point me how to solve it.
thanks,
for json text, an escape character should be used before double quote and comma,
for example
"ste,t1=35 json_test=L"{"carNumber":"","image":"","outParkingSpace":1638927251000,"parkingSpaceStatus":0}" 1645329601000"
I have a Spring Boot application that uses Hibernate. Below is the way I get the Hibernate session:
#Transactional
public class ParentDAO {
#PersistenceContext
private EntityManager entityManager;
protected Session getSession() {
if(entityManager!=null)
System.out.println("entity manager instantiated...");
return entityManager.unwrap(Session.class);
}
}
Then, I have the class which does the database access as the following,
#Repository
#Transactional
#SuppressWarnings("unchecked")
public class GmCircularsDaoImpl extends ParentDAO implements IGmCircularsDAO {
#Override
public GmCirculars saveOrUpdate(GmCirculars obj) {
Session session = null;
try {
session= this.getSession(); //Added by Zaid
session.beginTransaction();
session.saveOrUpdate(obj);
session.flush();
session.getTransaction().commit();
}
catch (Exception ex) {
ex.printStackTrace();
}
finally {
session.close();
System.out.println("Session closed.");
}
return obj;
}
#Override
public List<GmCirculars> find(GmCirculars obj, boolean activeOnly, int startOffset, int maxRows) {
Session session = null;
List<GmCirculars> discounts = null;
try {
if (null != obj) {
session= this.getSession(); //Added by Zaid
Criteria criteria = session.createCriteria(GmCirculars.class);
if (null != obj.getId() && !BigDecimal.ZERO.equals(obj.getId())) {
criteria.add(Restrictions.eq("id", obj.getId()));
}
if (StringUtil.isNotNullOrEmpty(obj.getTitle())) {
criteria.add(Restrictions.ilike("title", obj.getTitle(), MatchMode.ANYWHERE));
}
if(null != obj.getOrganizationId()) {
criteria.add(Restrictions.eq("organizationId", obj.getOrganizationId()));
}
/*if (null != obj.getTypeId() && !BigDecimal.ZERO.equals(obj.getTypeId())) {
criteria.add(Restrictions.eq("typeId", obj.getTypeId()));
}*/
if (null != obj.getSerialNo() && !BigDecimal.ZERO.equals(obj.getSerialNo())) {
criteria.add(Restrictions.eq("serialNo", obj.getSerialNo()));
}
if (null != obj.getYear() && !BigDecimal.ZERO.equals(obj.getYear())) {
criteria.add(Restrictions.eq("year", obj.getYear()));
}
if (activeOnly) {
criteria.add(Restrictions.eq("active", BigDecimal.ONE));
}
else {
criteria.add(Restrictions.or(Restrictions.ne("active", CommonConstants.DELETED_STATUS), Restrictions.isNull("active"))); //Except for deleted ones -> NVL(active,2)
}
//LIMIT startOffset, maxRows;
criteria.setFirstResult(startOffset);
criteria.setMaxResults(maxRows);
criteria.addOrder(Order.desc("id"));
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
System.out.println("criteria: "+ criteria.toString());
discounts = criteria.list();
System.out.println("returned list from db:"+discounts);
//session.getTransaction().commit();
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
session.close();
}
return discounts;
}
}
The method find(GmCirculars obj, boolean activeOnly, int startOffset, int maxRows) was first called for some query and it works just fine. However, after that I called saveOrUpdate(GmCirculars obj) , but I got the following errors on the line:
session.beginTransaction();
The error:
java.lang.IllegalStateException: Transaction already active
at org.hibernate.engine.transaction.internal.TransactionImpl.begin(TransactionImpl.java:74)
at org.hibernate.internal.AbstractSharedSessionContract.beginTransaction(AbstractSharedSessionContract.java:467)
at ae.gov.adm.saeed.dao.impl.circulars.GmCircularsDaoImpl.saveOrUpdate(GmCircularsDaoImpl.java:49)
at ae.gov.adm.saeed.dao.impl.circulars.GmCircularsDaoImpl$$FastClassBySpringCGLIB$$babc932a.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:769)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:366)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:99)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689)
at ae.gov.adm.saeed.dao.impl.circulars.GmCircularsDaoImpl$$EnhancerBySpringCGLIB$$718dc221.saveOrUpdate(<generated>)
at ae.gov.adm.saeed.service.circulars.CircularsService.saveOrUpdate(CircularsService.java:37)
at ae.gov.adm.CircularsMicroservice.saveCircularView(CircularsMicroservice.java:109)
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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:503)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:590)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:108)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
I tried to close the session before reusing it like
if(session.isOpen())
session.close();
I also tried to remove this line whenever I access the database again,
session.beginTransaction();
I checked the answer here but doesn't seem to work for my particular case.
All these attempts fail and I keep getting errors. How to solve the problem? Thanks.
Your classes are annotated with #Transactional which means Spring has already wrapped all methods with transaction handling. If you look at the stack trace you can see a line
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:366)
which reveals that the annotation is working. Hibernate will flush and commit automatically before leaving the transaction. Just remove the manual handling of transactions from you code, as well as the Session.close() calls and it should work...
I can't see the error of my code, I hope you can find it!
Language: Java
IDE: Eclipse
I've created an object.
This object contains this data:
public class ObjectTypeBean {
private Map<String, String> connectedOperators = new HashMap<String, String>();
public Map<String, String> getConnectedOperators() {
return connectedOperators;
}
public void setConnectedOperators(String operatorId, String label) {
this.connectedOperators.put(operatorId, label);
}
}
Then I've created a list of this object-class
List<ObjectTypeBean> name= new ArrayList<ObjectTypeBean>();
And I'm trying to add new Data to the map.
I'm trying it like this:
for(ObjectTypeBean n:name){
n.setConnectedOperators("one", "two");
}
But as soon as I tun this I get a
java.lang.UnsupportedOperationException
at java.base/java.util.AbstractMap.put(AbstractMap.java:209)
at ObjectTypeBean.setConnectedOperators(ObjectTypeBean.java:356)
at MyServlet.doPost(MyServlet.java:372)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at CharsetFilter.doFilter(CharsetFilter.java:31)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:836)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1839)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:834).
Thanks to your suggestions I found the answer!
The problem was, that I'm using a builder in my ObjectTypeBean-Object.
As the builder creates an Collections.emptyMap() so that the map can be empty.
I've removed the connectedOperators-Map from the builder and there is no error anymore.
Thankyou!
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I have a SQL database which we managed to get connected using the proper drivers. Firstly here's the code
package com.Derp.test.blah;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.io.PrintWriter;
public class DBConnect {
String databaseURL;
String user;
String password;
public DBConnect(String inurl, String inuser, String inpass) {
databaseURL = inurl;
user = inuser;
password = inpass;
}
#SuppressWarnings("null")
public List<String> dbConnector() throws ClassNotFoundException {
System.out.println("dburl: "+databaseURL);
System.out.println("user: "+user);
System.out.println("pass: "+password);
List<String> imgPaths = null;
Connection conn = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(databaseURL, "service_manager", "watermelon");
if (conn != null) {
System.out.println("Connected to the database");
Statement s = conn.createStatement();
//Count the amount of users in the Accounts table with the user name of the query
System.out.println("Before executeQuery");
ResultSet rs = s.executeQuery("SELECT * FROM testable");
while(rs.next()){
System.out.println(rs.getString("imgpath"));
imgPaths.add(rs.getString("imgpath"));
}
System.out.println("Size of Images: " + imgPaths.size());
//return imgPaths;
}
} catch (SQLException ex) {
System.out.println("An error occurred. Maybe user/password is invalid");
ex.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
return imgPaths;
Ignore how horrible some parts of this code is please. In the while loop
System.out.println(rs.getString("imgpath"));
Is printing out results to the console that are in the SQL database, however I am unable to add the results to the imgPaths String List, and am getting the following error.
Jan 30, 2019 10:20:20 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [com.Derp.test.blah.TestServlet] in context with path [/BlahTest] threw exception
java.lang.NullPointerException
at com.Derp.test.TestBlah.DBConnect.dbConnector(DBConnect.java:39)
at com.Derp.test.TestBlah.TestServlet.doGet(TestServlet.java:140)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:791)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Null pointer exception... Any help would be greatly appreciated.
Your imgPaths variable is initialized to null. Change the initialization to a list object then it would allow you to add items.
I keep on getting this error and I'm not sure why. Here is the code. Im not even executing any sql and it's still saying "Cannot close a connection while a transaction is still active"
DataAccess da = new DataAccess();
int param = Integer.parseInt(request.getParameter("geoAreaID"));
try (Connection tempConnection = DataAccess.OpenConnection())
{
tempConnection.rollback();
tempConnection.close();
}
catch (SQLException e)
{
e.printStackTrace();
System.exit(e.getErrorCode());
}
catch (Exception e)
{
e.printStackTrace();
System.exit(2);
}
The DataAccess class has the method to open the connection, here it is.
public static Connection OpenConnection() throws SQLException
{
Properties tempConnectionProperties = new Properties();
tempConnectionProperties.put("user", CONNECTION_USER);
tempConnectionProperties.put("password", CONNECTION_PASSWORD);
Connection tempConnection = DriverManager.getConnection(CONNECTION_STRING, tempConnectionProperties);
tempConnection.setAutoCommit(true);
tempConnection.createStatement().executeUpdate("SET SCHEMA APP");
return tempConnection;
}
this is the full error message
java.sql.SQLException: Cannot close a connection while a transaction is still active.
at org.apache.derby.client.am.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
at org.apache.derby.client.am.ClientConnection.closeResourcesX(Unknown Source)
at org.apache.derby.client.am.ClientConnection.closeX(Unknown Source)
at org.apache.derby.client.am.ClientConnection.close(Unknown Source)
at org.apache.derby.client.net.NetConnection.close(Unknown Source)
at dkaru.servlets.GeographicAreaServlet.doGet(GeographicAreaServlet.java:36)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Caused by: ERROR 25001: Cannot close a connection while a transaction is still active.
at org.apache.derby.client.am.ClientConnection.checkForTransactionInProgress(Unknown Source)
... 29 more
Setting the auto commit property of the connection worked for me. Code shown below :
conn.setAutoCommit(true);