Eclipselink JPA criteria format select date - mysql

I'm developing a web app with Spring 4 MVC and EclipseLink with MySQL. I'm currently stucked with a criteria query to get results with a date field. I have the following code:
CriteriaBuilder criteriaBuilder = entityManager().getCriteriaBuilder();
CriteriaQuery<Tuple> query = criteriaBuilder.createTupleQuery();
Root<SsiCheque> fromSsiCheque = query.from(SsiCheque.class);
List<Predicate> predicates = new ArrayList<Predicate>();
if(parameters.containsKey("cheNumero")){
System.out.println("Param " + parameters.get("cheNumero"));
predicates.add(criteriaBuilder.like(fromSsiCheque.<String>get("cheNumero"), "%" + parameters.get("cheNumero") + "%"));
}
if(parameters.containsKey("cheFechas")){
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String[] fechas = parameters.get("cheFechas").split(" - ");
try {
predicates.add(criteriaBuilder.between(fromSsiCheque.<Date>get("cheFecha"), formatter.parse(fechas[0]), formatter.parse(fechas[1])));
} catch (ParseException e) {
e.printStackTrace();
}
}
if(parameters.containsKey("cheReceptor")){
predicates.add(criteriaBuilder.like(fromSsiCheque.<String>get("cheReceptor"), "%" + parameters.get("cheReceptor") + "%" ));
}
query.multiselect(fromSsiCheque.get("cheId"), fromSsiCheque.get("cheNumero"),
fromSsiCheque.get("cheReceptor"), fromSsiCheque.get("cheMonto"),
criteriaBuilder.function("DATE_FORMAT",
String.class, fromSsiCheque.<Date>get("cheFecha"),
criteriaBuilder.literal("'%d/%m/%Y'")).alias("cheFecha"), fromSsiCheque.get("cheConcepto"))
.where(predicates.toArray(new Predicate[]{}));
TypedQuery<Tuple> typed = entityManager().createQuery(query);
The problem is in the multiselect section where I'm defining a date to be returned and formatted in dd/MM/yyyy with MySQL function DATE_FORMAT:
criteriaBuilder.function("DATE_FORMAT",
String.class, fromSsiCheque.<Date>get("cheFecha"),
criteriaBuilder.literal("'%d/%m/%Y'")).alias("cheFecha")
In some posts say the function is called TO_CHAR but it seems to be part of Oracle Database API.
The strange thing here is that I'm not getting errors (maybe I need to change logging level) but is not working.
Also I set the persistence.xml to show the generated sql and is as follows:
SELECT che_id, che_numero, che_receptor, che_monto, DATE_FORMAT(che_fecha, ?), che_concepto FROM ssi_cheque WHERE che_numero LIKE ?
bind => [%d/%m/%Y, %12%]
What Am I missing in my criteria query to show dates formatted?
Thanks
UPDATE
What I am getting from the database is 1416895200000 (the date field in milliseconds I guess).
Thanks

Related

Displaying records of a particular month in mysql

I am trying to fetch records of a particular month from the database and the pattern of the data that column is ""
Query I am using is
select * from table_name WHERE column_name LIKE ''
for the month of September. But this is printing no results.
Please suggest.
Use direct date comparisons! Don't treat dates as strings. So something like:
where column_name >= '2000-09-01' and column_name < '2000-10-01'
Or, if you want all months, then extract the month. The standard function is extract():
where extract(month from column_name) = 9
or:
where month(column_name) = 9
However, the particular function depends on the database (not all databases support all the standard functions).
Building up on the answers and comments above. It seems like you want to use this in your C# code with the user selecting a value from a dropdown. One option would would be something like this:
string monthNumber = valueFromDropdown;
string connectionString = "put you connection string here";
string commandText = "select * from table_name "
+ "where month(column_name) = #MonthNumber";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#MonthNumber", SqlDbType.Int);
command.Parameters["#MonthNumber"].Value = monthNumber;
try
{
connection.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

How I can get the correct date of my Mysql query without the query itself subtracting one day to date

My problem is that in a table of my database with 7 columns, I have a column of date type, called "Fecnac". Through MYSQLworkbrench, I execute a simple query:
"SELECT * FROM tblAsegurados ORDER BY Name,Nss"
As a result of this query, the information of my columns or fields of the table is displayed, the table contains a column named "Fecnac" that shows the correct date, for example "2018-12-31".
MYSQLworkbrench Result image
However, I developed an application in intelliJ IDEA to execute the same query, and the query "by itself" returns the date with one day less, that is, it shows "2018-12-30". And so it does with all the dates found in the "Fecnac" column of the "tblAsegurados" table in my database.
public ArrayList<Asegurados> getAseguradosList(){
ArrayList<Asegurados> aseguradosList = new ArrayList<Asegurados>();
Connection connection = getConnection();
var query = "select * from tblAsegurados order by Nombre,Nss";
Statement st;
ResultSet rs;
try{
st = connection.createStatement();
rs = st.executeQuery(query);
Asegurados asegurado;
while(rs.next()){
asegurado = new Asegurados(
rs.getString("Nss"),
rs.getString("Nombre"),
rs.getString("Curp"),
rs.getBoolean("Esposa"),
rs.getInt("Semcot"),
rs.getInt("Hijos"),
rs.getDate("Fecnac"));
aseguradosList.add(asegurado);
System.out.println(asegurado.getFecnac());
System.out.println(rs.getDate("Fecnac"));
System.out.println(rs.getDate(7));
}
} catch (Exception e){
e.printStackTrace();
}
return aseguradosList;
}
The class "Asegurados" has an attribute of type "java.sql.date" defined, to receive "rs.getdate (Fecnac).
For i be sure of the values ​​returned by the query, in my code you can see that I made a "System.out.println" for each field date, and in all three I get the same value from the date with one day less.
Could someone help me know what happens?
Console debug IntelliJ Idea image
I already found the solution. In a part of my code, the parameter of the time zone had it defined as: serverTimezone = UTC
public static Connection getMySQLConnection() throws Exception {
String driver = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://localhost/imss"+
"?useUnicode=true&useJDBCCompliantTimezoneShift=true"+
"&useLegacyDatetimeCode=false&serverTimezone=America/Mexico_City"+
"&verifyServerCertificate=false"+
"&useSSL=true"+
"&requireSSL=true";
String username = "root";
String password = "juan1980";
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
I set it to: serverTimezone = america / Mexico_City, which is the zone that corresponds to me, and ready! the date is displayed correctly.

Error while Fetching Records using Custom Query in Liferay

I am passing Array of long values and trying to get the relevant records But it is throwing a Error Positional Parameter is not defined.
Here is the code
try {
String list = CustomSQLUtil.get(id of the query);
SQLQuery sqlQuery = session.createSQLQuery(list);
sqlQuery.setCacheable(false);
QueryPos q=QueryPos.getInstance(sqlQuery);
q.add(array of long values);
return processObjectListToEntityList(QueryUtil.list(sqlQuery, getDialect() ,QueryUtil.ALL_POS, QueryUtil.ALL_POS));
}
catch(Exception e){
log.error("Error while Fetching Records " + e);
} finally{
closeSession(session);
}
Query
SELECT
entity1.name
FROM
entityOne as entity1
JOIN
entityTwo as entity2
WHERE
entity1.id = entity2.id
AND
entity2.id IN (?);
Any help would be appreciated.
I recommend to parse your query to DinamycQuery API instead. This have many benefits as that you dont have to manage the session lifecycle and that you obtaing a List of liferay model objects directly.
An example would be:
DynamicQuery dynamicQuery = DynamicQueryFactoryUtil.forClass(AssetCategory.class, PortalClassLoaderUtil.getClassLoader());
Property nameProperty = PropertyFactoryUtil.forName("name");
Property groupIdProperty = PropertyFactoryUtil.forName("groupId");
dynamicQuery.add(nameProperty.eq(name));
dynamicQuery.add(groupIdProperty.eq(groupId));
List<AssetCategory> categoriesByName = AssetCategoryLocalServiceUtil.dynamicQuery(dynamicQuery);

SQL WHERE LIKE clause in JSF managed bean

Hi i have this managed bean where it makes MySQL queries, the problem here is the SQL statement makes a '=' condition instead of 'LIKE'
Here is the code in my managed bean.
Connection con = ds.getConnection();
try{
if (con == null) {
throw new SQLException("Can't get database connection");
}
}
finally {
PreparedStatement ps = con.prepareStatement(
"SELECT * FROM Clients WHERE Machine LIKE '53'");
//get customer data from database
ResultSet result = ps.executeQuery();
con.close();
List list;
list = new ArrayList();
while (result.next()) {
Customer cust = new Customer();
cust.setMachine(result.getLong("Machine"));
cust.setCompany(result.getString("Company"));
cust.setContact(result.getString("Contact"));
cust.setPhone(result.getLong("Phone"));
cust.setEmail(result.getString("Email"));
//store all data into a List
list.add(cust);
}
return list;
Here the SELECT command does not pull all the numbers in 'Machine' column which is like 53, but if i enter a whole value, such as the complete number (53544) in place of 53 then the result is pulled up. I am confused !!
Also if i replace the above select statement with SELECT * FROM Clients the entire database is stored in list. Any ideas ?
Use wildcards:
Like '%53%'
...means everything that contains '53'.
Like '%53' - it ends with 53
LIKE '53%' - it starts with 53
You can also use _ if You want to replace a single character.
You can find a descriptipn HERE
You sql query should be
"SELECT * FROM Clients WHERE Machine LIKE '%53%'

How to generate a JSON file from Mondrian output

I am new to Mondrian. I am using it in my project for OLAP operations.
I am testing it with Foodmart database.
The problem is that I need the OLAP operations results in JSON format.
I know that mondrian has the same structure as JSON in the form of hierarchies.
I want to generate a JSON file as an output from the result of mondrian MDX query.
The result should be similar to OLAP operations.
I don't know how to iterate over the result generated from MDX query.
Here is the code.
String connStr = "Provider=mondrian;" +
"Catalog=/WEB-INF/FoodMart.xml;" +
"JdbcDrivers=com.mysql.jdbc.Driver;" +
"Jdbc=jdbc:mysql://localhost/foodmart;" +
"jdbcUser=root;" +
"jdbcPassword=;";
String queryStr ="select {[Measures].[Unit Sales], [Measures].[Store Cost], [Measures].>Store Sales]} ON COLUMNS,"+"Crossjoin(Hierarchize(Union({[Promotion Media].[All Media]}, >[Promotion Media].[All Media].Children)), {[Product].[All Products]})
ON ROWS"+" from [Sales]"+"where [Time].[1997]";
Connection connection = DriverManager.getConnection(connStr, null);
Query query = connection.parseQuery(queryStr);
Result result = connection.execute(query);
result.print(new PrintWriter(System.out));
Actually I need to perform OLAP operations on data warehouse which is stored in MySQL.
The resulted data should be in JSON format which I will pass to D3 http://mbostock.github.com/d3 for visualizations.
For data format I have to use JSON format.
Please any suggestions how to iterate MDX result and convert it in JSON file.
I am using Pentaho Mondrian for this purpose.
Thanks.
if you are working with PHP you could use this library to transform the xmla result into Json
http://www.ibm.com/developerworks/xml/library/x-xml2jsonphp/
Here's an example of what i suppose you want to do:
Class.forName("mondrian.olap4j.MondrianOlap4jDriver"); //load the driver
Connection connection = DriverManager.getConnection("Provider=mondrian;" +
"Catalog=/WEB-INF/FoodMart.xml;" +
"JdbcDrivers=com.mysql.jdbc.Driver;" +
"Jdbc=jdbc:mysql://localhost/foodmart;" +
"jdbcUser=root;" +
"jdbcPassword=;");
OlapWrapper wrapper = (OlapWrapper) connection;
OlapConnection olapConnection = wrapper.unwrap(OlapConnection.class);
CellSet cellSet = statement.executeOlapQuery(query);
CellSetAxis rows = cellSet.getAxes().get(1); //cube rows
CellSetAxis columns = cellSet.getAxes().get(0); //cube columns
int resultSize = rows.getPositionCount() * columns.getPositionCount();
String resultValues[] = new String[resultSize];
int valueIndex = 0;
for (Position row : rows) {
for (Position column : columns) {
Cell cell = cellSet.getCell(column, row);
String cellValue = cell.getFormattedValue();
resultValues[valueIndex++] = cellValue;
}
}
Gson gson = new Gson(); //gson library instance
String resultString = gson.toJson(responseValues); //json string
olapConnection.close();
connection.close();