QueryDSL simple query will not cast to object - java

I am testing QueryDSL against the World database in MySql. I can retrieve the data as a List, but I cannot get it to return as a List. I am querying via SQL, nothing else. This is what I have.
private void getSomething(Connection connection) {
QCountry country = QCountry.country;
SQLTemplates dialect = new HSQLDBTemplates();
SQLQuery query = new SQLQueryImpl(connection, dialect);
//List<Object[]> countries = query.from(country).list(country.all());
List<QCountry> countries = query.from(country).list(country);
System.out.println(countries);
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I get this error:
java.lang.IllegalArgumentException: RelationalPath based projection can only be used with generated Bean types

You need to generate bean types as described here http://blog.mysema.com/2011/01/querying-in-sql-with-querydsl.html under Bean class generation.

Related

SQL Query to to acces Excel data - Java

I am trying to read from excel using Fillo-1.18. Below is my code:
public static void main(String[] args) {
Fillo fillo=new Fillo();
Connection connection;
try {
connection = fillo.getConnection("C:\\Users\\Dish\\Desktop\\1.xlsx");
String strQuery="Select sum(Amount) as amnt, Run_ID from Sheet1 group by Run_ID";
Recordset recordset=connection.executeQuery(strQuery);
while(recordset.next()){
System.out.println(recordset.getField("amnt"));
}
recordset.close();
connection.close();
} catch (FilloException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It works fine for normal select clause. But when I am trying to use aggregate functions like SUM(), I am not able to access that field. Inside while I am get the following error:
com.codoid.products.exception.FilloException: amnt field is not found
at com.codoid.products.fillo.Recordset.getField(Recordset.java:163)
at ReadExcelSheetData.main(ReadExcelSheetData.java:18)
How can I resolve this?

Stored procedures call (namedparameterjdbctemplate)

I'm trying to call a stored procedure using jdbc. My connection is being passed through namedParameterJdbcTemplate and that's what I have to use to call it, but when I attempt to do this:
public void storedProcedure(long fileId, String Action) {
String sql = "call procedureName(?)";
try {
namedParameterJdbcTemplate.update(sql, Long.valueOf(fileId) );
} catch (Exception e) {
logger.error("Error while running stored procedure {}", sql, e);
}
}
I get the following error:
Cannot resolve method 'update(java.lang.String, java.lang.Long)'
Sources I've tried looking at and can't make it work:
https://docs.spring.io/spring-framework/docs/4.2.x/spring-framework-reference/html/jdbc.html
https://lalitjc.wordpress.com/2013/07/02/different-ways-of-calling-stored-procedure-using-spring/
https://www.logicbig.com/tutorials/spring-framework/spring-data-access-with-jdbc/spring-call-stored-procedure.html
Most of them are creating a connection from the beginning but I already have it (namedParameterJdbcTemplate), also some are using datasource which I don't need because again, I have already the connection.
How can I make the call with namedParameterJdbcTemplate?
Thank you
This is how it works:
final String sql = "call procedureName (:variable)";
SqlParameterSource namedParameters = new MapSqlParameterSource("variable", variable);
try {
namedParameterJdbcTemplate.update(sql, namedParameters);
} catch (Exception e){
...
}
Your syntax looks wrong. When calling update using NamedParameterJdbcTemplate, you need to call the method with either of these two method signatures.
update(String sql, Map<String,?> paramMap)
or
update(String sql, SqlParameterSource paramSource)
For further information - https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplate.html
Further example here - https://netjs.blogspot.com/2016/11/insert-update-using-namedparameterjdbctemplate-spring.html

Catch an SQL Exception with Spring Data JPA

The following methods tries to write data to DB (firmRepository.save()) and to ElasticSearch (firmSearchRepository.save()).
The problem is that I do not want to write to ES repository if the DB save failed. I am trying to catch the exception with DataAccessException, but through my tests I see that such exceptions as unique constraint violation -> get through and persistence in ElasticSearch still executes.
#Override
public FirmDTO save (FirmDTO firmDTO) {
log.info("Database Request to save Firm: {}", firmDTO.getFirmId());
Firm firm = firmMapper.firmDTOtoFirm(firmDTO);
try {
firm = firmRepository.save(firm);
firmSearchRepository.save(firm);
return firmMapper.firmToFirmDTO(firm);
} catch (DataAccessException ex) {
log.error(ex.getLocalizedMessage());
return null;
}
}
Is there way to catch those specific exceptions related to SQL?
Using the saveAndFlush() JPA repository method made catching Spring Data exceptions possible.
#Override
#Transactional
public FirmDTO save (FirmDTO firmDTO) {
log.info("Database Request to save Firm: {}", firmDTO.getFirmId());
Firm firm = firmMapper.firmDTOtoFirm(firmDTO);
try {
firm = firmRepository.saveAndFlush(firm);
firmSearchRepository.save(firm);
return firmMapper.firmToFirmDTO(firm);
} catch (DataAccessException ex) {
log.error("my exception");
log.error(ex.getLocalizedMessage());
return null;
}
}

Preloaded Ehcache Ignored when using #Cacheable Annotation

I'm still new to the ehcache API so I may be missing something obvious but here's my current issue.
I currently have a persistent-disk cache that's being stored on my server. I'm currently implementing a passive write-behind cache method that saves key/value pairs to a database table. In the event the persistent-disk cache is lost, I'd like to restore the cache from the database table.
Example I'm using for my write-behind logic:
http://scalejava.blogspot.com/2011/10/ehcache-write-behind-example.html
I'm building a disk persistent using the following method:
import com.googlecode.ehcache.annotations.Cacheable;
import com.googlecode.ehcache.annotations.KeyGenerator;
import com.googlecode.ehcache.annotations.PartialCacheKey;
#Cacheable(cacheName = "readRuleCache", keyGenerator=#KeyGenerator(name="StringCacheKeyGenerator"))
public Rule read(#PartialCacheKey Rule rule,String info) {
System.out.print("Cache miss: "+ rule.toString());
//code to manipulate Rule object using info
try{
String serialziedRule =objectSerializer.convertToString(Rule);
readRuleCache.putWithWriter(new Element(rule.toString(),serialziedRule ));
}
catch(IOException ioe)
{
System.out.println("error serializing rule object");
ioe.printStackTrace();
}
return rule;
}
The write method I'm overriding in my CacheWriter implementation works fine. Things are getting saved to the database.
#Override
public void write(final Element element) throws CacheException {
String insertKeyValuePair ="INSERT INTO RULE_CACHE (ID, VALUE) VALUES " +
"('"+element.getObjectKey().toString()+"','"
+element.getObjectValue().toString()+"')";
Statement statement;
try
{
statement = connection.createStatement();
statement.executeUpdate(insertKeyValuePair);
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Querying and De-serializing the string back in to an object works fine too. I've validated that all the values of the object are present. The disk persistent cache is also being populated when I delete the *.data file and restart the application:
public void preLoadCache()
{
CacheManager cacheManager = CacheManager.getInstance();
readRuleCache = cacheManager.getCache("readRuleCache");
Query query=em.createNativeQuery("select * from RULE_CACHE");
#SuppressWarnings("unchecked")
List<Object[]> resultList = query.getResultList();
for(Object[] row:resultList)
{
try {
System.out.println("Deserializing: "+row[1].toString());
Rule rule = objectSerializer.convertToObject((String)row[1]);
rule= RuleValidator.verify(rule);
if(rule!=null)
{
readAirRuleCache.putIfAbsent(new Element(row[0], rule));
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Question
Everything looks OK. However when I pass Rule objects with keys that should exist in the cache the "read" method is called regardless and the *.data file size is increased. Though the write method for the database doesn't attempt to insert existing keys again. Any ideas on what I'm doing wrong?
It turns out this was the culprit:
keyGenerator=#KeyGenerator(name="StringCacheKeyGenerator")
The source material I read on this suggested that the "toString()" method I overrode would be used as the key for the cache key/value pair. After further research it turns out that this is not true. Though the "toString()" key is used. It is nested within class information to create a much larger key.
Reference:
http://code.google.com/p/ehcache-spring-annotations/wiki/StringCacheKeyGenerator
Example Expected key:
"[49931]"
Example Actual Key:
"[class x.y.z.WeatherDaoImpl, getWeather class x.y.z.Weather, [class java.lang.String], [49931]]"

Set the default parameter value for the report by code

all my crystal report are publish on my business object server.
all of them are connected to Business Views Object.
all of these Business Views use the same dynamic Data Connection.
This make that my report have this Dynamic Data Connection Parameter.
I can change this parameter via the Central Management Console.
But now I would like to be able to change it via code with the BO's SDK.
I have this method that I think is near achieving what i want , I just can save the changes.
public static void updateParameter(IInfoObject report){
// get all parameters
try {
IReport rpt = (IReport) report;
int i = 0;
IReportParameter params;
for(i=0;i<rpt.getReportParameters().size();i++){
params = (IReportParameter) rpt.getReportParameters().get(i);
int y = 0;
for(y=0;y<params.getCurrentValues().getValues(IReportParameter.ReportVariableValueType.STRING).size();y++){
IParameterFieldDiscreteValue val = (IParameterFieldDiscreteValue) params.getCurrentValues().getValues(IReportParameter.ReportVariableValueType.STRING).getValue(y);
if(val.getDescription().contains("Data Connection")){
val.setValue(boConstance.conn_EXAMPLE1);
val.setDescription(boConstance.desc_EXAMPLE1);
//save the new parameter ?????
System.out.println("report parameters modified");
}
}
}
} catch (SDKException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Any Idea ? Thanks,
Since you are already setting the parameters you should just need to call the save method on the IReport itself. You wouldn't save the parameters directly since they are data belonging to the report.
So to finish your example after the for loop
try {
IReport rpt = (IReport) report;
int i = 0;
IReportParameter params;
for(i=0;i<rpt.getReportParameters().size();i++){
// do for loop here setting the parameters
}
rpt.save();
} catch (SDKException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Categories

Resources