Postgres Timestamp column with Java util.Date - spring

I have a (start_time) column which is of type timestamp with time zone. and I have a JPA mapping entity which reads as below,
#Column(name = "start_time")
#Temporal(TemporalType.TIMESTAMP)
private Date startTime;// (util.date)
My table has value "2017-08-09 09:57:00+05:30". When I use JPA to map the values, I get the value as "2017-08-09 09:57:00.0"
when I try to debug, I can see CDATE inside the date attribute which shows me the correct value with timezone. How to map this correctly?

Try to change #Column(name = "start_time") on #Column(name = "start_time", columnDefinition = "TIMESTAMP WITH TIME ZONE")

Related

Sorting in Java | How to get value from other field of entity if the current field is null while sorting entity list in java?

Context :
Consider following entity in spring boot project,
#Entity
public class Transaction{
#Id
private Integer tId;
private Integer amount;
private LocalDate invoiceDate;
private LocalDate tDate;
}
A method which creates object of transaction, doesn't set tDate.
There is an independent method which sets tDate.
So, in the database some entries don't have 'tDate'.
Problem :
Now, I want to show all the entries in database sorted using tDate but, for those entries which does not contain tDate it should consider invoiceDate.
Sample Database entries
t_id
amount
invoice_date
t_date
1
1200
2/3/2022
4/3/2022
2
2434
5/3/2022
6/3/2022
3
234
3/3/2022
NULL
Sample expected Output
[[tId = 3, amount = 234, invoiceDate = 3/3/2022, tDate = NULL]
[tId = 1, amount = 1200, invoiceDate = 2/3/2022, tDate = 4/3/2022]
[tId = 2, amount = 2434, invoiceDate = 5/3/2022, tDate = 6/3/2022]]
Note : Highlighted dates above are the dates considered for sorting.
What I tried
I tried to use the combination of nullsLast(Comparator.naturalOrder()) and thenComparing() methods of Comparator.comparing() but it doesn't give the expected output. It sorts the entries withtDate and entries without tDate separately.
Thank you in advance for any help!!
Also, I'm using MongoRepository in repository layer, so I can use the Sort object as well.
Thank you!

Named Query with map values in Spring Data JPA

i have a hashmap like which has key value pair such as :
testMap = new HashMap(){{
put(iD, sID);
put(lEVEL, sLevel);
put(tYPE, sType);
put(vALUE, sValue);
Now i have my entity Class which has fields like
#Column(name = "ID")
private String id;
#Column(name = "LEVEL")
private String level;
#Column(name = "PROGRAM")
private String program;
#Column(name = "TYPE")
private String type;
#Column(name = "VALUE")
private String value;
#Column(name = "STARTDATE")
private Date start;
Now i need to form a named query where for each column i have to set values by extracting them from map key value pair (something like this :tesMap.get(iD) and setting in ID column) and also comparing the start date with the current date and setting the largest date in startdate column .
Tried the following using Named query but didn't work .
#Query(value = "SELECT * FROM OVERRIDES s " +
"WHERE s.ID =?1 AND s.LEVEL=?2 AND s.TYPE=?3 AND s.VALUE=?4", nativeQuery = true)
Also ,unable to decide how to compare dates in this select query .
Comparing the dates can be easily done with Date.after() method.
E.g.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse("2022-07-01");
Date date2 = sdf.parse("2022-08-31");
if(date1.after(date2)) {
//set largest date in date column
}
As for the rest question, please provide the whole Entity, or maybe more infos about the query
In SQL, you can compare dates/timestamps with relational operators >, <, >=, <= i.e.
#Query(value = "SELECT * FROM OVERRIDES s " +
"WHERE s.ID =?1 AND s.LEVEL=?2 AND s.TYPE=?3 AND s.VALUE>=?4", nativeQuery = true)

How to get TimeZone offset value in java

I have a date coming from a device and I want to do the following in Java:
I want to parse this date "2021-05-27T18:47:07+0530" to yyyy-mm-dd HH:MM:SS
Get the Date's offset value so that I can get the timezone offset as +05:30 or whatever timezone it comes from.
For the first one I have done this and looks like it works, but any better smaller approach will be handy as well:
String date = "2021-05-27T18:47:07+0530";
String inputPattern = "yyyy-MM-dd'T'HH:mm:ss+SSSS";
String outputPattern = "yyyy-MM-dd HH:mm:ss";
LocalDateTime inputDate = null;
String outputDate = null;
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(inputPattern, Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(outputPattern, Locale.ENGLISH);
inputDate = LocalDateTime.parse(date, inputFormatter);
outputDate = outputFormatter.format(inputDate);
System.out.println("inputDate: " + inputDate);
System.out.println("outputDate: " + outputDate);
The Ouput is:
inputDate: 2021-05-27T18:47:07.053
outputDate: 2021-05-27 18:47:07
I don't know how to get the offset value of timezone in this case.
There are many recommendations including using SimpleDateFormat and ZonedDateTime etc but should be the best answer for this considering the offset value can be dynamic i.e it can be +05:30,+09:00 etc.
Please help in this case.
Try it like this.
String dateTime = "2021-05-27T18:47:07+0530";
String inputPattern = "yyyy-MM-dd'T'HH:mm:ssZ";
String outputPattern = "yyyy-MM-dd HH:mm:ss";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ",
Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(dateTime, dtf);
ZoneOffset tz = zdt.getOffset();
System.out.println(tz);
System.out.println(zdt.format(DateTimeFormatter.ofPattern(outputPattern,
Locale.ENGLISH)));
Prints
+05:30
2021-05-27 18:47:07
The zoned date time could also be reprinted using the same format by which it was originally parsed.

Print ZonedDateTime exactly as it is parsed

I have a date string in a format:
String date = 2014-05-05T05:05:00.000
ZonedDateTime zoneDateTime = LocalDateTime.parse(date).atZone(ZoneId.of("UTC");
the above prints:
2014-05-05T05:05Z[UTC]
Is there any way we can print it in the following format ?
2014-05-05T05:05:00.000Z
In joda time, i can easily do this:
DateTime datetime= org.joda.time.LocalDateTime.parse(date).toDateTime(UTC)
Is there any way we can print it in the following format ?
String date = 2014-05-05T05:05:00.000
You can use java.time.format.DateTimeFormatter.ofPattern().
String date = "2014-05-05T05:05:00.000";
ZonedDateTime zoneDateTime = LocalDateTime.parse(date).atZone(ZoneId.of("UTC"));
System.out.println(zoneDateTime);
System.out.println(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX").format(zoneDateTime));
Refrence: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

What does Hibernate map a boolean datatype to when using an Oracle database by default?

By default if I create a field in an entity like:
#NotNull
boolean myBoolean;
And I let Hibernate auto-create my tables. What Oracle data type will this map to?
As #Arthur said it maps to Number(1) which would be the standard sql bit where 0 == false and 1 == true. As an alternative you can map char(1) to 'T' or 'F' like this
#org.hibernate.annotations.Type(type="true_false")
#NotNull
boolean myBoolean;
or map it to 'Y' or 'N'
#org.hibernate.annotations.Type(type="yes_no")
#NotNull
boolean myBoolean;
Simply Number(1)
If you want, use SchemaExport to generate a script to your target database. Something like
AnnotationConfiguration configuration = new AnnotationConfiguration();
configuration
.addAnnotatedClass(<TYPE_YOUR_CLASS>.class)
.setProperty(Environment.USER, <TYPE_YOUR_USER>)
.setProperty(Environment.PASS, <TYPE_YOUR_PASSWORD>)
.setProperty(Environment.URL, <TYPE_YOUR_URL>)
.setProperty(Environment.DIALECT, <TYPE_YOUR_DIALECT>)
.setProperty(Environment.DRIVER, <TYPE_YOUR_DRIVER>);
SchemaExport schema = new SchemaExport(configuration);
schema.setOutputFile("schema.sql");
schema.create(<DO_YOU_WANT_TO_PRINT_TO_THE_CONSOLE>, <DO_YOU_WANT_TO_EXPORT_THE_SCRIPT_TO_THE_DATABASE>);
This is what you really need
Java POJO:
//#Type(type="true_false") //not working for '1' and '0' in NUMERIC(1) field
#Type(type= "org.hibernate.type.NumericBooleanType")
#NotNull(message="NOT_NULL")
#Column(name = "IS_DELEGATION", nullable = false)
private Boolean isDelegation;
Oracle DDL
alter table agent add (is_delegation number(1) default 0 not null);
As stated in
Hibernate docu

Resources