Load objects from db by parameter Date - database

I have some objects in db. Every object has parameter Date in date format like a "Mon Oct 05 08:55:36 CEST 2015". I want load all objects from 24h before to present time. I am using hibernate entity manager. Can you help me please
Here is my entity params:
private Long id;
private String email;
private String answer1;
private String answer2;
private Date date;
Here is table schema:
ID ; email ; answer1 ; answer2 ; date
1 ; any#thing.com ; 1234 ; 4321 ; 2015-10-04 18:01:19

I assume then, that the type of the date table column is indeed SQL DATE. In that case, you can simply run a HQL/JPQL query
SELECT e FROM YourEntity e WHERE e.date BETWEEN :from AND :to
Make a PreparedStatement out of it and provide the desired values for the from and to parameters. Sample using JPA:
EntityManager em = ...;
Date to = new Date();
Calendar fromCalendar = Calendar.getInstance();
fromCalendar.setTime(to);
fromCalendar.add(Calendar.HOUR_OF_DAY, -24);
Date from = fromCalendar.getTime();
em
.createQuery("SELECT e FROM YourEntity e WHERE e.date BETWEEN :from AND :to", YourEntity.class)
.setParameter("from", from, TemporalType.TIMESTAMP)
.setParameter("to", to, TemporalType.TIMESTAMP)
.getResultList();
Using JodaTime or Java8 Time package may make the whole date manipulation easier (didn't know if you were using those, so I gave an example using the "basic" Java classes).

Related

salesforce SOQL can't get datetime in local time

My objective is to count Lead records based on simple date range query in local time
Integer TotalLeads = [ Select Count() From Lead where createddate >= fromdate CreatedDate <= todate];
Fairly basic. However, the issue I'm running into is I only want to count the leads for the "local" time not UTC; createddate is in UTC for lead records.
Sample dates:
From: 03/23/2017
To: 03/29/2017
For these sample dates and my local time is UTC - 7 (Los Angeles), so my query would be
Integer TotalLeads = [ Select Count() From Lead where createddate >= 2017-03-23T07:00:00z AND CreatedDate <= 2017-03-30T06:59:59z];
If these are my dates, how do I append the local time so from date is 2017-03-23T07:00:00z and to date is 2017-03-30T06:59:59z?
Using from date first, I was able to do the following but can't figure how to keep it in local time
// Date
date ds = date.valueof('2017-03-23');
string dm = string.valueOf( ds.month());
string dd = string.valueOf(ds.day());
string dy = string.valueOf(ds.year());
// DateTime Midnight (UTC)
String SDate = string.valueof(dm +'/' + dd + '/' + dy + ' 12:00 AM');
system.debug(SDate); // -> 3/23/2017 12:00 AM
// DateTime (Local Time)
datetime ds2 = datetime.parse(SDate );
system.debug(ds2); // -> 2017-03-23 07:00:00
system.debug(ds2.format('yyyy-MM-dd\'T\'hh:mm:ss'')); // -> 2017-03-23T12:00:00
As you can see, using ds2.format put its in the format I need but back to UTC (midnight), I need it to be 2017-03-23T07:00:00
Any suggestions?
Thanks!
Figured what I was doing wrong. The date calculation was fine, it had to do with how this was being passed to a batch job.

How to convert SQL Query into LinQ

I'm new to SQL, please Help me how to convert this query into LinQ
This is My Table Dept:
Id Name Sal Department
1 John 40000 Dotnet
2 mick 45000 DotNet
3 Pillay 777 Sql
Here I want to display Salary Based On Department Name, like:
DepartmentName ToalSal
Dotnet 85000
Sql 777
select DeprtmentName,sum(sal) from Dept_Emp Group by DeprtmentName
I wrote some Part of query
public IEnumerable<Dept_Emp> GetJam()
{
var x = from n in db.Dept_Emp
group n by n.Sal into g
select new
{
DeprtmentName = g.Key
};
// what I mention Here;
}
You are missing calculating sum of sal fields of grouped entities. Also you are grouping by wrong field. You should use department name for grouping
from de in db.Dept_Emp
group de by de.DeprtmentName into g
select new {
DepartmentName = g.Key,
TotalSalary = g.Sum(x => x.Sal) // aggregation here
}
What you have as output is anonymous objects. You cannot return them directly from method. You have several options here
Create custom class like DepartmentTotals with name and total salary fields, and return instances of this class instead of anonymous objects. Then return type will be IEnumerable<DepartmentTotals>.
Create Tuple<string, int> (or whatever type of salary). And return such tuples.
Use C# 7 tuples.

SQlite creating a database with a timestamp column and adding a value in

I am trying to create a database that called rawData. The db will hava a column for the id, a foreign user id (_id from another table), data and finally a timestamp.
My question is how can I create a timestamp in SQlite and store it in the db also what type should the column be, text? the database needs to be able to store 150 float values a second and time stamp each of those 150 entries. Additionally since SQlite doesn't have a float type should i use real as the column type?
public class RawDatabase{
public static final String TABLE_RAW_DATA = "rawData";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_FOREIGN_USER_ID = "foreignUserId";
public static final String COLUMN_DATA = "data";
public static final String COLUMN_TIME_STAMP = "timeStamp";
// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_RAW_DATA + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_FOREIGN_USER_ID
+ " integer, " + COLUMN_DATA
+ " real, " + COLUMN_TIME_STAMP
+ " text not null);";
}
The documentation says:
SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:
TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.
If you need only seconds precision, use integers in Unix Time format.
Otherwise, use floating-pointer numbers for fractional seconds.
This is a running example of DAO with SQlite and Date in Java:
First create column MY_DATE TIMESTAMP in your TABLE and populate like this:
PreparedStatement st = connection.prepareStatement("INSERT INTO ......");
st.setDate(1, new java.sql.Date(lettura.getData().getTime()));
And to retrieve data first i get date in String type:
String dateStr = rs.getString(1);
Date myDate = new java.util.Date(Long.parseLong(dateStr));

Scala Slick Lifted Date GroupBy

I'm using Scala 2.10 with Slick 1.0.0 and trying to do a lifted query.
I have a table, "Logins", where I'm attempting to do a load, and groupBy on a Timestamp column. However, when I attempt to groupBy, I am running into an issue when I try and format the Timestamp field to extract only the day portion, to group the objects by the same day.
Given the objects:
id | requestTimestamp
1 | Jan 1, 2013 01:02:003
2 | Jan 1, 2013 03:04:005
3 | Jan 1, 2013 05:06:007
4 | Jan 2, 2013 01:01:001
I'd like to return a grouping out of the database by similar days, where, for the sake of brevity, the the following Formatted timestamp to id relationship happens, where the id's would actually be a list of objects
Jan 1, 2013 -> (1, 2, 3)
Jan 2, 2013 (4)
I've got the following slick table object:
private implicit object Logins extends Table[(Int, Timestamp)]("LOGINS") {
def id = column[Int]("ID", O.PrimaryKey)
def requestTimeStamp = column[Timestamp]("REQUESTTIMESTAMP", O.NotNull)
def * = logId ~ requestTimeStamp
}
The following Query method:
val q = for {
l <- Logins if (l.id >= 1 && l.id <= 4)
} yield l
val dayGroupBy = new java.text.SimpleDateFormat("MM/dd/yyyy")
val q1 = q.groupBy(l => dayGroupBy.format(l.requestTimeStamp))
db.withSession {
q1.list
}
However, instead of getting the expected grouping, I get an exception on the line where I attempt the groupBy:
java.lang.IllegalArgumentException: Cannot format given Object as a Date
Does anyone have any suggestions on properly grouping by Timestamps out of the database?
Timestamp and Date are not the same thing! Try to convert Timestamp to Human understandable text using calendar or SimpleDateTime.
Not so sure about the second one though!

Move Data from one entity to another entity

I have 2 entities Documents(Id,Number,Content,Date_Added) and Adocuments(archives of documents)(Ida,Number,Content,Date_Added) and I want to move the Documents (for example) from march in my archive entity. My tables have the same fields.
Select part
WPF_TestEntities WPFModel;
DateTime init_per = new DateTime(2012, 03, 01);
DateTime fina_per = new DateTime(2012, 03, 31);
var qry = from d in WPFModel.Document // qry - documents form march
where d.Date_Added >= init_per && d.Date_Added <= fina_per
select d;
Insert part
//WPFModel.Adocument.Insert/Add(qry);
After that I can delete the march documents from the Document entity.
How can I move the data(qry) from Documents to Adocuments? (will there be any problems with the uniqueness of my Id ?)
you can try this :
WPF_TestEntities WPFModel;
DateTime init_per = new DateTime(2012, 03, 01);
DateTime fina_per = new DateTime(2012, 03, 31);
var qry = from d in WPFModel.Document // qry - documents form march
where d.Date_Added >= init_per && d.Date_Added <= fina_per
select d;
foreach (Document doc in qryluna)
{
Adocument newadoc = new Adocument();
newadoc.IdA = doc.Id;
newadoc.Nr_intern = doc.Nr_intern;
newadoc.Obiect = doc.Obiect;
newadoc.Data_Added = doc.Data_Added ;
WPFModel.Adocument.AddObject(newadoc);
WPFModel.Document.DeleteObject(doc);
}
WPFModel.SaveChanges();
you can do trying downcasting the element result from query, if it will not run you should take each element and copy to a new bject, than you can save it in hystory table.
The id could be a problem, because if you settled the id as autoincrement (identity on sql server) of course the db will try to release a new id, instead your old one.
The most secure task that you should do is to questy the first entity, take each values and fill a new hystorical entity (related to the hystory table) and save it.
I guess that you could have the second table (Adocuments) with those fields:
id (your table identity id)
ida (your id copied from Documents table, to really maintain the history)
number
content
date_added
I hope this is useful for you :)

Resources