When my query is executed i receive stack
Caused by: org.hibernate.QueryException: Not all named parameters have been set: [param0] [select count(generatedAlias0.id)
from Position as generatedAlias0 where generatedAlias0.rank=:param0]
Method where is executed
public Long CountPosition(Rank aRank, List<Long> Status, List<Long> aStatusInternal) {
QueryBuilder<PozycjaWRankingu> aQuery = queryCountLarge();
aQuery.whereEquals("rank", aRank);
aQuery.whereInNotEmpty("status", Status);
aQuery.whereInNotEmptyAndNotEquals("internal.state", aStatusInternal);
return aQuery.countLarge();
}
And finally Query Builder
public static <T> QueryBuilder<T> createCountLarge(EntityManager aEntityManager, Class<T> aClass) {
QueryBuilder r = new QueryBuilder();
r.em = aEntityManager;
r.criteriaBuilder = r.em.getCriteriaBuilder();
r.criteria = ret.criteriaBuilder.createQuery(Long.class);
r.root = ret.criteria.from(aClass);
r.criteria.select(ret.criteriaBuilder.count(ret.root.get("id")));
return r;
}
Any idea where is might be a problem ?
Edit
queryCountLarge() returns
QueryBuilder.createCountLarge(em, myClass);
Related
This is the sql script that I have used to create the necessary classes :
CREATE CLASS ProductSummary;
CREATE PROPERTY ProductSummary.name STRING (NOTNULL, MANDATORY TRUE);
CREATE PROPERTY ProductSummary.modelNumber LONG (NOTNULL, MANDATORY TRUE);
ALTER CLASS ProductSummary STRICTMODE TRUE;
CREATE CLASS PricingSummary;
CREATE PROPERTY PricingSummary.price LONG (NOTNULL, MANDATORY TRUE);
CREATE PROPERTY PricingSummary.discount LONG (NOTNULL, MANDATORY TRUE);
ALTER CLASS PricingSummary STRICTMODE TRUE;
CREATE CLASS TotalSummary EXTENDS V;
CREATE PROPERTY TotalSummary.projectLink LINK Project (NOTNULL, MANDATORY TRUE);
CREATE PROPERTY TotalSummary.productSummaries EMBEDDEDLIST ProductSummary;
CREATE PROPERTY TotalSummary.pricingSummaries EMBEDDEDLIST PricingSummary;
ALTER CLASS TotalSummary STRICTMODE TRUE;
CREATE INDEX TotalSummary_projectLink_idx ON TotalSummary (projectLink) UNIQUE;
I am trying to insert some values into my TotalSummary class, where I also need to insert some values into the EmbeddedList for pricingSummaries and productSummaries.
public TotalSummary create(final TotalSummary totalSummary) {
final Long projectId = 1;
final StatementBuilder builder = new StatementBuilder();
final StringBuilder query = new StringBuilder();
final List<Map<?, ?>> productSummaries = totalSummary.getProductSummaries().stream()
.map(ProductSummary::toMap)
.collect(Collectors.toList());
final List<Map<?, ?>> pricingSummaries = totalSummary.getPricingSummaries().stream()
.map(PricingSummary::toMap)
.collect(Collectors.toList());
builder.addAttribute("projectLink = (SELECT FROM project WHERE id = ?)", projectId);
if ( ! productSummaries.isEmpty()) {
builder.addAttribute("productSummaries = ?", productSummaries);
}
if ( ! pricingSummaries.isEmpty()) {
builder.addAttribute("pricingSummaries = ?", pricingSummaries);
}
try {
insert(TotalSummary.class.getSimpleName(), builder.attributes(), statement -> {
builder.init(statement);
return statement;
});
} catch (final UncategorizedSQLException e) {
throw new ConstraintViolationException(totalSummary, ExceptionUtils.getRootCauseMessage(e), e);
}
return assertNotNull(findById(projectId));
}
This is the utility method that I am using to build the insert query :
protected String insert(final String vertex, final String fieldValuePairs, final PreparedStatementInitializer initializer) {
final String sql = "INSERT INTO " + vertex + " SET " + fieldValuePairs + " RETURN #rid";
return executeStatement(sql, initializer);
}
The toMap methods to convert the List<ProductSummary> to List<Map<?,?>>
**ProductSummary**
public Map<String, Object> toMap() {
final Map<String, Object> ret = new HashMap<>();
ret.put("name", name);
ret.put("model number", Long.valueOf(modelNumber));
return ret;
}
The toMap methods to convert the List<PricingSummary> to List<Map<?,?>>
**PricingSummary**
public Map<String, Object> toMap() {
final Map<String, Object> ret = new HashMap<>();
ret.put("price", Long.valueOf(price));
ret.put("discount", Long.valueOf(discount));
return ret;
}
I am getting the following exception when I execute the code
Constraint violation for: TotalSummary#58f79eeb[recordId=<null>,customProperties=[]]. Reason: OValidationException: The field 'TotalSummary.productSummaries' has been declared as EMBEDDEDLIST but an incompatible type is used.
Things that I have already tried :
I have tried to covert to list to json format before adding it to
the builder like so new Gson().toJson(pricingSummaries);
Converted the pricingSummaries and productSummaries toArray().
You defined the summaries as EMBEDDEDLIST ProductSummary but you are passing lists of maps as values.
Try to create real ProductSummary objects instead eg.
OElement ret = db.newEmbeddedElement("ProductSummary");
ret.setProperty("price", Long.valueOf(price));
ret.setProperty("discount", Long.valueOf(discount));
Connected to azure-cosmosdb and able to fire default queries like findAll() and findById(String Id). But I can't write a native query using #Query annotation as the code is not considering it. Always considering the name of the function in respository class/interface. I need a way to fire a custom or native query to azure-cosmos db. ?!
Tried with #Query annotation. But not working.
List<MonitoringSessions> findBySessionID(#Param("sessionID") String sessionID);
#Query(nativeQuery = true, value = "SELECT * FROM MonitoringSessions M WHERE M.sessionID like :sessionID")
List<MonitoringSessions> findSessions(#Param("sessionID") String sessionID);
findBySessionID() is working as expected. findSessions() is not working. Below root error came while running the code.
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property findSessions found for type MonitoringSessions
Thanks for the response. I got what I exactly wanted from the below link. Credit goes to Author of the link page.
https://cosmosdb.github.io/labs/java/technical_deep_dive/03-querying_the_database_using_sql.html
public class Program {
private final ExecutorService executorService;
private final Scheduler scheduler;
private AsyncDocumentClient client;
private final String databaseName = "UniversityDatabase";
private final String collectionId = "StudentCollection";
private int numberOfDocuments;
public Program() {
// public constructor
executorService = Executors.newFixedThreadPool(100);
scheduler = Schedulers.from(executorService);
client = new AsyncDocumentClient.Builder().withServiceEndpoint("uri")
.withMasterKeyOrResourceToken("key")
.withConnectionPolicy(ConnectionPolicy.GetDefault()).withConsistencyLevel(ConsistencyLevel.Eventual)
.build();
}
public static void main(String[] args) throws InterruptedException, JSONException {
FeedOptions options = new FeedOptions();
// as this is a multi collection enable cross partition query
options.setEnableCrossPartitionQuery(true);
// note that setMaxItemCount sets the number of items to return in a single page
// result
options.setMaxItemCount(5);
String sql = "SELECT TOP 5 s.studentAlias FROM coll s WHERE s.enrollmentYear = 2018 ORDER BY s.studentAlias";
Program p = new Program();
Observable<FeedResponse<Document>> documentQueryObservable = p.client
.queryDocuments("dbs/" + p.databaseName + "/colls/" + p.collectionId, sql, options);
// observable to an iterator
Iterator<FeedResponse<Document>> it = documentQueryObservable.toBlocking().getIterator();
while (it.hasNext()) {
FeedResponse<Document> page = it.next();
List<Document> results = page.getResults();
// here we iterate over all the items in the page result
for (Object doc : results) {
System.out.println(doc);
}
}
}
}
I am trying to run a SQL Server 2014 stored procedure from Java (Spring) code and get some xml results.
When I run this in a SQL client e.g. RazorSQL I get a bunch of xmls (which is expected because the there are multiple stored procedures within it, that returns those xml).
Here is the Exec call from my SQL client:
EXEC [dbo].[sp_GetType]
#TRAN_ID = 42
#QUAL_ID = 0
GetType does a RETURN 0 at the end (so basically if all steps succeed, it returns 0)
This opens multiple tabs in my client with the xmls.
And one example stored procedure within GetType has these lines:
SELECT TOP 1 ModifiedBy = CASE WHEN #IS_ID = 1 FROM TABLE23.dbo.TRX
TrxId WITH (NOLOCK) WHERE #DD_ID = #TRAN_ID
FOR XML AUTO, ELEMENTS
My goal is to capture all the xmls returned by GetType into a List of objects.
Here is my dao:
private final JdbcTemplate jdbcTemplate;
#Autowired
public TransactionDao(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
#Transactional(readOnly = true)
public List<Object> getTransaction(Integer tranId, Integer qualId) {
Object dt = new Object();
List<Object> resultList = (List<Object>) jdbcTemplate.execute(
new CallableStatementCreator() {
public CallableStatement createCallableStatement(Connection con) throws SQLException {
String storedProc = "{call sp_GetType(?,?)}";
CallableStatement cs = con.prepareCall(storedProc);
cs.setInt(1, tranId);
cs.setInt(2, qualId);
return cs;
}
}, new CallableStatementCallback() {
public Object doInCallableStatement(CallableStatement > cs) throws SQLException,
DataAccessException {
List<Object> results = new ArrayList<Object>();
cs.execute();
if(cs.getMoreResults())
{
ResultSet rs = cs.getResultSet();
while(rs.next()) //rs has only one record
{
InputStream in = null;
Clob clob = rs.getClob(1);
in = clob.getAsciiStream();
}
rs.close();
}
return results;
}
});
return resultList;
}
I'm using the jtds 1.3.1 driver (I tried connecting using mssql-jdbc but no luck).
Any help is much appreciated.
An error occurred while executing this code:
public Iterable<T> findAllByIds(List<Integer> ids) {
Path<Integer> idField = root.get("id");
Predicate in = idField.in(ids);
query.select(root);
query.where(in);
query.orderBy(builder.asc(idField));
List<T> result = entityManager.createQuery(query).getResultList();
return result;
}
In line 2 the following exception is thrown:
Caused by: java.lang.IllegalArgumentException: Unaware how to convert value [[100, 101] : java.util.Arrays$ArrayList] to requested type [java.lang.Integer]
Hibernate version 5.2.11.Final, Java 8.
Try this :-
public Iterable<T> findAllByIds(List<Integer> ids) {
Expression<Integer> exp = root.get("id");
Predicate in = exp.in(ids);
query.select(root);
query.where(in);
query.orderBy(builder.asc(root.get("id")));
List<T> result = entityManager.createQuery(query).getResultList();
return result;
}
Using Postgresql 8.1, Spring 3.0, Hibernate 3.6.
I have a method that calls a stored procedure that works without using Annotations, essentially it is
....
return (Integer) getJpaTemplate().execute(new JpaCallback() {
public Object doInJpa(EntityManager em) {
// Query query = em.createNamedQuery("checkZone");
Query query = em.createNativeQuery("select zoneArea from zoneArea(:pId, :zId)");
query.setParameter("pId", p.getId());
query.setParameter("zId", z.getId());
try {
return query.getSingleResult(); // Integer expected
} catch (NoResultException e) {
return 0;
}
}
});
....
How can I do this with Annotations, here's my attempt that does not work.
#NamedNativeQueries({
#NamedNativeQuery(
name = "checkZone",
query = "select zoneArea from zoneArea(:pId, :zId)",
hints = {
#QueryHint(name = "org.hibernate.callable", value = "true")
},
resultSetMapping = "scalar",
resultClass = Integer.class)})
#SqlResultSetMapping(name="scalar",columns=#ColumnResult(name="result"))
#Entity
and here is the Exception
Caused by: org.postgresql.util.PSQLException: This statement does not declare an OUT parameter. Use { ?= call ... } to declare one.
at org.postgresql.jdbc2.AbstractJdbc2Statement.registerOutParameter(AbstractJdbc2Statement.java:1849)
at org.postgresql.jdbc3.AbstractJdbc3Statement.registerOutParameter(AbstractJdbc3Statement.java:1513)
at org.hibernate.dialect.PostgreSQLDialect.registerResultSetOutParameter(PostgreSQLDialect.java:335)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1713)
at org.hibernate.loader.Loader.doQuery(Loader.java:801)
I have working code but would like to get this working with Annotations, any ideas appreciated.