I am trying to create a named query for all the stringified arguments. This was how my stringified method was:
public Collection<Companypermcache> findExpiredPerms() {
String date = DateUtils.getSQLDate(DateUtils.getToday());
StringBuffer qbe = new StringBuffer("select cpc from Companypermcache cpc");
qbe.append(" where cpc.expire < '"+date+"'");
return super.findByQuery(qbe.toString());
}
I convert this to named query like below
String date = DateUtils.getSQLDate(DateUtils.getToday());
StringBuffer qbe = new StringBuffer("select cpc from Companypermcache cpc");
qbe.append(" where cpc.expire < :date");
return super.findByQuery(qbe.toString(),"date",date);
}
But this generates
java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Date
at org.hibernate.type.descriptor.java.JdbcTimestampTypeDescriptor.unwrap(JdbcTimestampTypeDescriptor.java:24)
at org.hibernate.type.descriptor.sql.TimestampTypeDescriptor$1.doBind(TimestampTypeDescriptor.java:48)
at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:74)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:253)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:248)
at org.hibernate.param.NamedParameterSpecification.bind(NamedParameterSpecification.java:52)
at org.hibernate.loader.hql.QueryLoader.bindParameterValues(QueryLoader.java:627) ...
Exception.
However If I update the named query like below I don't have any exception and everything looks good.
String date = DateUtils.getSQLDate(DateUtils.getToday());
DateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
Date edate = simpleDateFormat.parse(date);
StringBuffer qbe = new StringBuffer("select cpc from Companypermcache cpc");
qbe.append(" where cpc.expire < :date");
return super.findByQuery(qbe.toString(),"date",edate);
}
However I really did not understand the difference and and the need of parsing.I have many place in my project where I am using getSQLDate(), So I am concerned whether I want to parse all those dates?
In addition to that type for edate in my table is DATETIME
Why we need to parse the Date when we pass a date as argument to named query????
Related
I am running below command manager procedure in Microstrategy but it does not convert the string into date, tried lot of options. Can someone please assist?
*********** PROCEDURE***************************************
String sQuery = "LIST ALL SUBSCRIPTIONS FOR SCHEDULE \"" + sScheduleName + "\" FOR PROJECT \"" + projectName + "\";";
ResultSet oSubs=executeCapture(sQuery);
oSubs.moveFirst();
while(!oSubs.isEof()){
String sSubsName = oSubs.getFieldValueString(DisplayPropertyEnum.GUID);
ResultSet RecList = executeCapture("LIST ALL PROPERTIES FOR SUBSCRIPTION GUID " +sSubsName+ " FOR PROJECT \"projectname\";");
RecList.moveFirst();
while(!RecList.isEof()){
ResultSet oResultSetSubProps = (ResultSet)RecList.getResultCell(SUBSCRIPTION_RESULT_SET).getValue();
oResultSetSubProps.moveFirst();
while(!oResultSetSubProps.isEof())
{
String d1 = oResultSetSubProps.getFieldValueString(DisplayPropertyEnum.EXPIRATIONDATE);
// the below few lines in red return nothing, its unable to convert to Date as it is unable to recognize the Expiration date in the String format.
java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("M/dd/yyyy");
String dateInString = d1;
Date date = formatter.parse(dateInString);
printOut(formatter.format(date));
oResultSetSubProps.moveNext();
}
RecList.moveNext();
}
oSubs.moveNext();
}
This worked for me. The string was neither empty, nor null and no even blank but it would still not parse it so i had to use the length of the string.
java.text.DateFormat formatter = new java.text.SimpleDateFormat("M/d/yyyy",Locale.US);
String dateInString = d1;
if(d1.trim().length()>0)
{
Date date = formatter.parse(dateInString);
if(todaydate.compareTo(date)>0)
{
printOut(name+";"+formatter.format(date));
}
}
if(d1.contains("/"))
{
Date EDate=new Date(d1);
Date today= new Date();
if(d1.compareTo(today)<0)
{
printOut("Expired");
}
}
else
{
printOut("Active");
}
//blank or null values can be handled in Else condition instead.. Hope it helps..
I have a table timestamptest with a single column timestamp of type timestamp without time zone.
I inserted a value to this table :
insert into timestamptest values('2015-09-08 13:11:11')
The timestamp does not contain any millisecond value.
On selecting this data in pgAdmin, it is displayed same as above.
But when I fetch this data using jdbc connection, the value displayed is with milliseconds.
Class.forName("org.postgresql.Driver");
Connection lConnection = null;
lConnection = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/postgres","postgres", "Password#123");
String lQuery = "select * from timestamptest";
Statement lStatement = lConnection.createStatement();
ResultSet lResultSet = lStatement.executeQuery(lQuery);
while(lResultSet.next()) {
System.out.println(lResultSet.getTimestamp(1));
}
Output : 2015-09-08 13:11:11.0
The desired output is 2015-09-08 13:11:11
It can be achieved by using SimpleDateFormat :
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(lResultSet.getTimestamp(1).getTime())
Can it be possible without using SimpleDateFormat? Is there any other way by which the result set itself gives me in the desired format?
What I need is that the statement
lResultSet.getTimestamp(1)
directly gives me the output 2015-09-08 13:11:11.
Its not possible. Since ResultSet.getTimestamp(1) return class that extends java.sql.TimeStamp. Returning class based on Database driver. And also we cant change the toString implementation of that.
Yes you can - but you're not going to like it.
class MyTimestamp extends Timestamp {
public MyTimestamp(long time) {
super(time);
}
public MyTimestamp(Timestamp ts) {
this(ts.getTime());
}
#Override
public String toString() {
String s = super.toString();
return s.substring(0, s.lastIndexOf("."));
}
}
public void test() {
System.out.println("Hello");
Timestamp t = new Timestamp(System.currentTimeMillis());
System.out.println(t);
System.out.println(new MyTimestamp(t));
}
How do you convert a DatePicker value to a String?
Currently I have a TextView setup, which the DatePicker passes its value to. Its displayed fine. Using that String to pass to a SQLite database isn't working however and returns
android.widget.TextView#41258880
When the databases fields are pulled up. I am currently taking the value and passing it to a string within the following TRY/Catch statement:
case R.id.btnUpdateDB:
boolean worked = true;
try {
String dbWeight = curWeight.getText().toString();
String dbWaist = curWaist.getText().toString();
String dbChest = curChest.getText().toString();
String dbLegs = curLegs.getText().toString();
String dbArms = curArms.getText().toString();
String dbDate = displayDate.toString();
Stats entry = new Stats(MainActivity.this);
entry.open();
entry.createEntry(dbWeight, dbWaist, dbChest, dbLegs, dbArms, dbDate);
entry.close();
break;
I feel that the following line is incorrect:
String dbDate = displayDate.toString();
You called the method toString directly on the widget. According to the source code it prints :
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
That's why you get :
android.widget.TextView#41258880
You have to do instead :
String dbDate = displayDate.getText().toString();
if displayDate is TextView You get its value just like You do with other fields before
String dbDate = displayDate.getText().toString();
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
String dateFormat = dateformat.format(new Date(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth()));
I am using hibernate to take out some records from my MySql database. The DepTime attribute in my table is of time format (hh:mm:ss). How can I convert it into string in Java? Following code is giving a type mismatch error at line 6.
List<?> dataList3 = DBOperation.getqpidfromAssessment(6);
if(dataList3.size()>0)
{
for (Iterator<?> iterator = dataList.iterator(); iterator.hasNext();) {
Route rt = (Route) iterator.next();
String depTime=rt.getDepTime();
double lt=rt.getLatitude();
log.debug("Lat : "+lat);
}
}
Use .toString() function to convert anydata into string in java.
String depTime=rt.getDepTime().toString();
I'm creating an email using String Template but when I print out a date, it prints out the full date (eg. Wed Apr 28 10:51:37 BST 2010). I'd like to print it out in the format dd/mm/yyyy but don't know how to format this in the .st file.
I can't modify the date individually (using java's simpleDateFormatter) because I iterate over a collection of objects with dates.
Is there a way to format the date in the .st email template?
Use additional renderers like this:
internal class AdvancedDateTimeRenderer : IAttributeRenderer
{
public string ToString(object o)
{
return ToString(o, null);
}
public string ToString(object o, string formatName)
{
if (o == null)
return null;
if (string.IsNullOrEmpty(formatName))
return o.ToString();
DateTime dt = Convert.ToDateTime(o);
return string.Format("{0:" + formatName + "}", dt);
}
}
and then add this to your StringTemplate such as:
var stg = new StringTemplateGroup("Templates", path);
stg.RegisterAttributeRenderer(typeof(DateTime), new AdvancedDateTimeRenderer());
then in st file:
$YourDateVariable; format="dd/mm/yyyy"$
it should work
Here is a basic Java example, see StringTemplate documentation on Object Rendering for more information.
StringTemplate st = new StringTemplate("now = $now$");
st.setAttribute("now", new Date());
st.registerRenderer(Date.class, new AttributeRenderer(){
public String toString(Object date) {
SimpleDateFormat f = new SimpleDateFormat("dd/MM/yyyy");
return f.format((Date) date);
}
});
st.toString();
StringTemplate 4 includes a DateRenderer class.
My example below is a modified version of the NumberRenderer on the documentation on Renderers in Java
String template =
"foo(right_now) ::= << <right_now; format=\"full\"> >>\n";
STGroup g = new STGroupString(template);
g.registerRenderer(Date.class, new DateRenderer());
ST st = group.getInstanceOf("foo");
st.add("right_now", new Date());
String result = st.render();
The provided options for format map as such:
"short" => DateFormat.SHORT (default)
"medium" => DateFormat.MEDIUM
"long" => DateFormat.LONG
"full" => DateFormat.FULL
Or, you can use a custom format like so:
foo(right_now) ::= << <right_now; format="MM/dd/yyyy"> >>
You can see these options and other details on the DateRenderer Java source here
one very important fact while setting date format is to use "MM" instead of "mm" for month. "mm" is meant to be used for minutes. Using "mm" instead of "MM" very generally introduces bugs difficult to find.