I want to run the following query however, I am getting some errors. I tested my query on neo4j workspace and it was working. I could not find any source for Java driver using IN query so I am not sure what is wrong with my code. I am using Neo4j Java driver 4.4.
ArrayList<String> changedMethods = ...
Query query = new Query(
"MATCH (changedFunction: Function) WHERE changedFunction.signature IN $changedMethods \n" +
"MATCH (affectedFunction: Function)-[:CALLS]->(changedFunction) \n" +
"RETURN affectedFunction.functionName", parameters("changedMethods", changedMethods));
try (Session session = driver.session(SessionConfig.forDatabase("neo4j"))) {
List<Record> a = session.readTransaction(tx -> tx.run(query)).list();
System.out.println(a.get(0).toString());
}
After running this code, I get the following error
org.neo4j.driver.exceptions.ResultConsumedException: Cannot access records on this result any more as the result has already been consumed or the query runner where the result is created has already been closed.
You cannot read the result of a transaction outside the transaction. You have to read the result from inside your transaction:
try (Session session = driver.session(SessionConfig.forDatabase("neo4j"))) {
List<Record> a = session.readTransaction(tx -> tx.run(query).list());
System.out.println(a.get(0).toString());
}
or
try (Session session = driver.session(SessionConfig.forDatabase("neo4j"))) {
session.readTransaction(tx -> {
List<Record> a = tx.run(query).list();
System.out.println(a.get(0).toString());
});
}
Related
I need to execute multiple queries via jdbc template in a single connection.
I am using SQL server with the mssql jdbc driver. Here is the query:
IF OBJECT_ID('tempdb..#temp') IS NULL
SELECT * INTO #temp FROM ( SELECT * FROM "complex query here" ) a
DECLARE #page_size INT
SET #page_size = ?
SELECT *
FROM ( SELECT TOP(#page_size) * FROM #temp
WHERE custom_column > ?
ORDER BY custom_column ) inner_query
(MULTIPLE JOINES HERE)
ORDER BY custom_column
The query simply puts the whole result from the complex query to the temp table if the table does not exist and selects pages from the generated temp table.
Since the temp tables have connection scope, i need to execute the whole paging with multiple queries in a single connection. This is the code i have tried:
try (Connection connection = dataSource.getConnection()) {
while (true) {
List<CustomObject> customObjects = customRepository.
.getCustomObjectsPage(connection, pageSize, minimumValueInWhere);
// business logic here..
if (customObjects.size() < pageSize) {
break;
}
minimumValueInWhere = customObjects.get(customObjects.size() - 1).getId().toString();
}
}
and getCustomObjectsPage():
public List<CustomObject> getCustomObjectsPage(Connection connection, int pageSize,
String parameter) {
JdbcTemplate singleConnectionJdbcTemplate = new JdbcTemplate(
new SingleConnectionDataSource(connection, true));
try {
return singleConnectionJdbcTemplate
.query("the query from above", new Object[]{pageSize, parameter},
JdbcTemplateMapperFactory.newInstance()
.newResultSetExtractor(CustomObject.class)); // the root entity.
}
}
But for some reasons the queries are not executed in a single connection, and if i hardcode the
parameters to the query instead of passing them to the jdbc template it works perfectly.
How to make this work independently of the parameters ?
Here I have added my code. Issue occurs in try block while I am trying fetch list of tables.
Database is MySql
Exception is : java.lang.IllegalArgumentException: node to traverse cannot be null!
public class DBOptimizationDAO extends HibernateDaoSupport {
private static final Log log = LogFactory.getLog(DBOptimizationDAO.class);
public void optimizeAdapter(String year)
{
List<com.ecw.adapterservice.beans.TransactionInbound> transactionInboundList = null;
StringBuilder queries = new StringBuilder();
try {
transactionInboundList = (List<com.ecw.adapterservice.beans.TransactionInbound>)super.getHibernateTemplate().find("from TransactionInbound where inboundTimestamp < '" + year+ "-01-01'order by 1 desc limit 2");
// Check if archive table exist or not
List<Object> inboundObj = getHibernateTemplate().find("SHOW TABLES LIKE transaction_outbound");
List<Object> outboundObj = getHibernateTemplate().find("SHOW TABLES LIKE 'transaction_outbound_archive'");
The HibernateTemplate::find expects a HQL query in the string parameter and you are passing a native statement. You can do native stuff (queries, statements, etc) using the Session object returned by HibernateTemplate::getSession. To pass a native select query you then have Session::createSQLQuery
BUT do you really want to rely on database specific code to do this? There is a more elegant way to do it by using DatabaseMetaData::getTables. See this answer. And you can get an instance of DatabaseMetaData from a callback method of your HibernateTemplate.
Try this:
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
if(!session instaceof SessionImpl){
//handle this, maybe throw an exception
}
else {
Connection con = (SessionImpl)session.connection();
...
}
I am using JsonDocument inserted = bucket.insert(doc); on couchbase-server-enterprise_4.1.0-ubuntu14.04_amd64.
What exactly happening is, I trigger this insert command and on success of this I trigger the Select command on same document. This Select command doesn't returns the update entries instead returns the old ones only. When I am using debugger before Select (wait for some seconds after insert and then call Select) it works totally fine. So i think insert behaves in async manner, not sure.
Other thing i have checked is upsert instead of insert, it is also not working. However when I do bucket.replace(doc) and then call Select, it returns the updated results. I have tried explicitly using the bucket.async().insert(doc) and the using toBlocking().single() on it, this also fails.
Is the issue with insert/upsert or I am doing something wrong.
Below is some of my code snippet ::
#Override
public T save(T entity, String username) {
String id = generateId(entity);
JsonObject data = JsonObject.fromJson(getContent(entity));
data.removeKey(ID);
data.put(TYPE, klass.getSimpleName());
data.put(CREATED_AT, new Date().getTime());
data.put(CREATED_BY, username);
data.put(MODIFIED_AT, new Date().getTime());
data.put(MODIFIED_BY, username);
data.put(ACTIVE, true);
T persistedEntity = getEntity(bucket.insert(JsonDocument.create(id, data)));
return persistedEntity;
}
#Override
public List findAll() {
Statement query = selectAll().where(typeExpression()).orderBy(Sort.desc(x(CREATED_AT)));
return getEntities(query);
}
protected AsPath selectAll() {
return Select.select("meta().id, *").from(i(bucket.name()));
}
N1QL queries can run with varying degrees of consistencies, unlike key/value operations which are always consistent (you "read-your-own-writes").
So there is a slight delay between an insertion and the indexer catching up to it. If you execute a N1QL query by default it will return what's the current state of the indexer, so if it is still indexing your document you won't see the update.
Try executing the query with a ScanConsistency of REQUEST_PLUS, where you do the bucket().query(...):
N1qlQuery n1qlQuery = N1qlQuery.simple(
selectStatement, //that's the Statement query in your example
N1qlParams
.build()
.consistency(ScanConsistency.REQUEST_PLUS)
);
This will instruct N1QL to wait for the indexer to finish indexing pending mutations.
Following is my code snippet:
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"classpath*:META-INF/spring/applicationContext*.xml");
JpaTransactionManager jpatm = (JpaTransactionManager) ctx
.getBean("transactionManager");
EntityManager em = jpatm.getEntityManagerFactory()
.createEntityManager();
String sqlQuery = "SELECT suc FROM SubUsrCont suc, UDMap uDMap WHERE suc.userid = uDMap.userid AND uDMap.parentuserid = :parentuserid";
TypedQuery<SubUsrCont> query = (TypedQuery<SubUsrCont>) em.createQuery(sqlQuery, SubUsrCont.class);
query.setParameter("parentuserid", parentid);
ArrayList<SubUsrCont> listContent = (ArrayList<SubUsrCont>) query.getResultList();
But when ever executed I get the following error:
[http-8080-1] ERROR org.hibernate.hql.PARSER - line 1:92: expecting OPEN, found '.'
Can anybody help???
Well, I found it and successfully tested it as well. It was due to my POJO package name. Previously it was in.myproject.myname. I changed it to com.myproject.myname. HQL was taking in as the SQL Keyword IN and was looking for OPEN '('.
Why are you using a Native SQL query inside em.createQuery()? This will not work because HQL can not have SELECT and furthermore you don't set the value for parameter :parentuserid.
String sqlQuery = "FROM SubUsrCont suc, UDMap uDMap WHERE suc.userid = uDMap.userid AND uDMap.parentuserid = :parentuserid";
TypedQuery<SubUsrCont> query = (TypedQuery<SubUsrCont>) em.createQuery(sqlQuery, SubUsrCont.class);
query.setParameter("parentuserid", <PARENT USER ID TO BE SEARCHED>);
Try this and see
If you would like to execute SQL use createNativeQuery. Also try "SELECT suc.* ...
Also you don't set the parameter :parentuserid
Use query setParameter("parentuserid",someValue)
i am new to this and today i tried to play hibernate with a method that returns the result of selected row...if is selected then it can return the result in int.. here is my method
public int validateSub(String slave, String source, String table){
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Query q = session.createQuery("from Subscribers where slave = :slave AND source = :source AND tbl = :tbl");
q.setParameter("slave", slave);
q.setParameter("source", source);
q.setParameter("tbl", table);
int result = q.executeUpdate();
return result;
}
from this method i tried to validate the 3 values that i get from the Subscribers table but at the end i tried to compile having this error
Exception in thread "Thread-0" org.hibernate.hql.QueryExecutionRequestException: Not supported for select queries [from com.datadistributor.main.Subscribers where slave = :slave AND source = :source AND tbl = :tbl]
You can have a look at the below links that how executeUpdate works, one is from the hibernate docs and other the java docs for JPA which defines when the exception is thrown by the method
http://docs.oracle.com/javaee/6/api/javax/persistence/Query.html#executeUpdate()
https://docs.jboss.org/hibernate/orm/3.2/api/org/hibernate/Query.html#executeUpdate()
Alternatively you can use
List list = query.list();
int count = list != null ? list.size() : 0;
return count;
you are running a select query, Eventhough you are not using the select keyword here hibernate will add that as part of the generated SQL.
what you need to do to avoid the exception is the say
q.list();
now, this will return a List (here is the documentation).
if you are trying to get the size of the elements you can say
Query q = session.createQuery("select count(s) from Subscribers s where slave = :slave AND source = :source AND tbl = :tbl");
Long countOfRecords = (Long)q.list().get(0);
you can execute update statements as well in HQL, it follows a similar structure as SQL (except with object and properties).
Hope this helps.
here you want to select record so it is posible without select key word
sessionFactory sesionfatory;
ArrayList list = (ArrayList)sessionfactory.getCurruntSession().find(from table where name LIKE "xyz");
long size = list.get(0);
I also happened to make the same mistake today.
Your SQL statement is not correct.
You can try:
DELETE from Subscribers WHERE slave = :slave AND source
Try this:
int result = q.list().size();