I'am adding some record in db using hibernate, but when i try to get the same record in some millis then it is returning 0 results.
This is the flow:
Create a put request.
Put result in db.
Response received 202 accepted.
Then same controller sends the request to another controller which then tries to update that record.
It returns result as failure.
Environment:
JDK 8
Spring boot 1.2.5
Hibernate 4.3.11.Final
I tried following ways:
Set session flush mode to ALWAYS and COMMIT.
Manually did session.flush() and session.clear()
Please provide the solution as soon as possible.
Related
I'm creating a resource subscription using transaction 1, before this transaction 1 returns , it adds the request , response and jpa query fetched just created subscription resource into a queue which is taken care by by executor service threads.
This executorService starts separate transaction 2, a uses to jpa query to read a specific attribute of subscription resource ,but it gets null value , but the previous transaction 1 found it(coz may be it itself created it). Transaction 2 need to read the current value but not founding it.
I'm using Ecliplink 2.6, JDK 1.8 and Wildfly 10.Final.
I have looked into whether eclipselink have persisted it to DB or kept in persistenceContext coz, transaction is still not complete and new transaction trying to read it.
That's normal transaction behavior.
As long as T1 is not commited T2 cannot see the data from T1.
I was wondering if there is a specific way to override database connection timeout in the properties file in my Java web project? I am using Hibernate, Spring, and MySQL DB. I have tried several different property fields and reduced the timeout time to 1 millsecond, yet the connection is still completed with transactions still being processed properly.
These are the property fields I have used to no avail...
spring.jpa.properties.javax.persistence.query.timeout=1
spring.jdbc.template.query-timeout=1
hibernate.c3p0.timeout=1
Is hibernate overriding this timeout value or am I just setting it improperly?
Thanks in advance!
Assuming that you're using Spring Boot you can try:
spring.transaction.defaultTimeout=1
This property sets defaultTimeout for transactions to 1 second.
(Looking at the source code of TransactionDefinition it seems that it is not possible to use anything more precise than seconds.)
See also: TransactionProperties
javax.persistence.query.timeout
This is a hint for Query. It is supposed to work if you use it like this:
entityManager.createQuery("select e from SampleEntity e")
.setHint(QueryHints.SPEC_HINT_TIMEOUT, 1)
.getResultList();
See also QueryHints
spring.jdbc.template.query-timeout
Remember that according to the JdbcTemplate#setQueryTimeout javadoc:
Any timeout specified here will be overridden by the remaining transaction timeout when executing within a transaction that has a timeout specified at the transaction level.
hibernate.c3p0.timeout
I suspect that this property specifies timeout for getting from the connection pool, not for a query execution
i'm trying to implement one transaction per request in my spring boot application.
I have a filter with HIGHEST_PRECEDENCE order that opens a transaction, lets other filters and the app's services do their job and commits the transaction. However, if commit fails, the servlet response has already been written and committed (with a success code), i can't modify it's status and message body to provide info about the error.
I need the servlet response to be modifiable in my filter, but something commits it.
I've disabled jackson commits, but right after the last filter (WsFilter) the message is commited anyway. The buffer size is as big as possible. I guess the embedded tomcat commits by default after WsFilter?
I've also tried using a wrapper and forbidding flush until a Boolean flag is set to true in my transaction filter, but null pointer exception occurres - coyoteResponse is null.
How do i keep a response uncommitted?
I ended up using ContentCachingResponseWrapper. This way all filters after my transaction filter use the wrapper instead of the original response. Since the original response is untouched it is not commited. After my filter close the transaction i call responseWrapper.copyBodyToResponse() to "flush" all data from the wrapper to the original response.
in general the code looks like this:
// create a transaction
// create a wrapper
chain.doFilter(request, responseWrapper);
// end the transaction
responseWrapper.copyBodyToResponse();
I would like to set a timeout on a javax.persistence.TypedQuery.
I've found this easy method :
TypedQuery<Foo> query = ... ;
query.setHint("javax.persistence.query.timeout", 1000);
query.getReturnList();
But it seems that does not work, it's just ignored.
From the PRO JPA 2 book:
"Unfortunately, setting a query timeout is not portable behavior. It
may not be supported by all database platforms nor is it a requirement
to be supported by all persistence providers. Therefore, applications
that want to enable query timeouts must be prepared for three
scenarios.
The first is that the property is silently ignored and has no effect.
The second is that the property is enabled and any select, update, or
delete operation that runs longer than the specified timeout value is
aborted, and a QueryTimeoutException is thrown. This exception may be
handled and will not cause any active transaction to be marked for
rollback.
The third scenario is that the property is enabled, but in doing so
the database forces a transaction rollback when the timeout is
exceeded. In this case, a PersistenceException will be thrown and the
transaction marked for rollback. In general, if enabled the
application should be written to handle the QueryTimeoutException, but
should not fail if the timeout is exceeded and the exception is not
thrown."
Does anyone knows any other method to specify a timeout on a TypedQuery?
Or how can I make this "hint" working?
Thanks
EDIT: Oracle 11.2.0.4.0 and PostgreSql 9.2.9
with JPA 2.1 / Hibernate
I know its late to reply, but we faced similar problem Oracle 11g, JPA2.0 and this hint wasn't working.
Actually the problem was we were using it as #NamedQuery hint and were calling the function inside #transactional aspect. As #NamedQuery gets loaded and compiled at the time of context load this timeout was overridden by transaction timeout.
You can find more info at http://javadeveloperz0ne.blogspot.in/2015/07/why-jpa-hints-on-namedquery-wont-work.html.
Solution would be fetching named query again and then applying timeout.
Query query = entityManager.createNamedQuery("NamedQueryName");
query.setHint("org.hibernate.timeout", "5");
query.getSingleResult();
Hope it helps!
Yeah Hint ignored and its not work please review this question . you should set timeout for javax.persistence.query.timeout
Set timeout on EntityManager query
I've got an error that looks like this:
Could not initialize proxy - no Session
I'm working with java, hibernate and spring. This error comes up when trying to generate a PDF document, and I'm following the next steps to generate it on the fly and store in the database.
I sent a request to the app through a POST method. This generates the PDF on the fly and shows to the user.
Just after that request I send another, but through an ajax a request. This will generate the same PDF but will save it in the DB.
The error shows that a query could not be executed due to "could not initialize proxy - no Session" error.
Is there something that am I doing wrong, calling the same methods twice from the same user session? Could it be that the session is closed before both requests have finished?
Hope someone can help me to understand what is happening.
Your problem is that the hibernate Session lives only for one request. It opens in the start of the request and closes at the end. You guessed the answer: Hibernate session is closed before both requests are finished.
Exactly what is happening? Your entity objects live during both requests. How? They are stored in the HTTP session (which is a different thing called session) You don't give much information about the framework you are using, so I can't give you more details, but it is certain that the framework you are using somehow keeps your entities in the HTTP session. This is how the framework makes it easy for you to work with the same objects for more than one requests.
When the processing of the second request starts, the code is trying to access some entity (usually an element of a collection) that is lazily initialized by hibernate. The entity is not attached to a hibernate session, and so hibernate can't initialize the hibernate proxy before reading it. You should open a session and re-attach your entity to it at the beginning of the ajax request processing.
EDIT:
I will try to give a brief explanation of what is happening behind the scene. All java web frameworks have one or more servlets that handle the requests. The servlet handles each request (HttpRequest) by creating a new thread that will finally produce the response (HttpResponse). The method that processes each request is executed inside this thread.
At the beginning of the request processing your application should allocate the resources that it needs for processing (Transaction, Hibernate session etc). At the end of the processing cycle these resources are released (Transaction is committed, hibernate session is closed, JDBC connections are released etc). Lifecycle of these resources could be managed by your framework, or could be done by your code.
In order to support application state in a stateless protocol as HTTP, we have the HttpSession object. We (or the frameworks) put on HttpSession the information that remains relevant between different request cycles of the same client.
During the processing of the first request hibernate reads (lazily) an entity from the database. Due to lazy initialization some parts of this object's structure are hibernate proxy objects. These objects are associated with the hibernate session that created them.
The framework finds the entity from the previous request in the HttpSession object when you try to process the second request. Then it is trying to access a property from a child entity that was lazily initialized and now is a hibernate proxy object. The hibernate proxy object is an imitation of the real object that will ask its hibernate session to fill it with information from the database when someone tries to access one of its properties. This what your hibernate proxy is trying to do. But its session was closed at the end of the previous request processing, so now it doesn't have a hibernate session to use in order to be hydrated (filled with real info).
Note that it is possible that you have already opened a hibernate session at the beginning of the second request, but it isn't aware of the entity that contains the proxy object because this entity was read by a different hibernate sesion. You should re-attach the entity to the new hibernate session.
There is a lot of discussion about how to re-attach a detached entity, but the simplest approach right now is session.update(entity).
Hope it helps.