i am trying to map offsetDateTime to type SQL but i am not sure how to solve the 2 types.
inside my method i am updating the date with
List<Items> listItems = repository.fetchitemById(Ids);
OffsetDateTime date = OffsetDateTime.now();
if (listItems.size() > 0 && !isNull(listItems.get(0).getDate())) {
date = listItems.get(0).getDate();
}
the query is inside the repository a crudRepository with the date on it al already verified the order in the interface and the query they all match
when i evaluate the expression
listItems.get(0).getDate()
i get
Method threw 'java.lang.IllegalArgumentException' exception.
Projection type must be an interface!
java.lang.IllegalArgumentException: Projection type must be an interface!
Also inside the schema the date is a TIMESTAMP with NULL DEFAULT NULL
any thoughts
try this
List<Items> listItems = repository.fetchitemById(Ids);
OffsetDateTime date = OffsetDateTime.now();
if (listItems.size() > 0){
if(!isNull(listItems.get(0).getDate())) {
date =Timestamp.valueOf(listItems.get(0).getDate().toLocalDateTime);
}
}
Related
I try to save some data that it brings me from my view, which is a table, but I don't know why it throws me that error with the insert.
result of insert
this is my view:
table of view
this is my controller:
$checked_array = $_POST['id_version'];
foreach ($request['id_version'] as $key => $value) {
if (in_array($request['id_version'][$key], $checked_array))
{
$soft_instal = new Software_instalacion;
$soft_instal->id_instalacion = $instalaciones->id;
$soft_instal->id_historial = $historial->id;
$soft_instal->id_usuario = $request->id_usuario;
$soft_instal->id_version = $_POST['id_version'][$key];
$soft_instal->obs_software = $_POST['obs_software'][$key];
$soft_instal->id_tipo_venta = $_POST['id_tipo_venta'][$key];
$soft_instal->save();
}
}
id_tipo_venta seems to be an empty string which is apparently not valid.
You can try debugging what you get in :
var_dump($_POST['id_tipo_venta'][$key]);
die;
Your database field expects to receive an integer. Therefore, using the intval() function can solve your problem.
Indeed, I think your code returns an alphanumeric string.
Therefore, the code below will return 0 in all cases if no version is returned (not set, string or simply null):
$soft_instal->id_tipo_venta = intval($_POST['id_tipo_venta'][$key]);
On the other hand, intval() will always convert to int, so a decimal will be converted, example :
intval("1.1") // returns 1
intval("v1.1") // returns 0
If this is not the desired behavior, maybe you should think about changing your database type.
EDIT :
Of course, you can also set the value as null if you prefer to 0. You must allow nullable values in your database.
id_tipo_venta can not be empty, try with some number or change type column to varchar in the database
I am trying to map a LocalDate to a SQL Date, but am receiving this error:
java.lang.IllegalArgumentException: Undefined filter parameter
[afterDateLocal]
I can't provide a reproducible example, but here's the code of the ListingRepositoryImpl:
if (!queries.get("checkInDate").get(0).equals("undefined")) {
Filter afterDateFilter = session.enableFilter("afterDateFilter");
String afterDate = queries.get("checkInDate").get(0);
LocalDate afterDateLocal = LocalDate.parse(afterDate);
System.out.println("After date: " + afterDateLocal);
afterDateFilter.setParameter("afterDateLocal", afterDateLocal);
} else {
session.disableFilter("afterDateFilter");
}
And the filters defined on the entity listing:
#Entity
#Table(name="listing")
#FilterDefs({
#FilterDef(name="priceFilter", parameters=#ParamDef(name="priceComparison",type="double")),
#FilterDef(name="beforeDateFilter", parameters=#ParamDef(name="beforeDateLocal", type="date")),
#FilterDef(name="afterDateFilter", parameters=#ParamDef(name="afterDateLocal", type="date"))
})
#Filters({
#Filter(name="priceFilter", condition="price <= :priceComparison"),
#Filter(name="beforeDateFilter", condition=":beforeDateLocal <= date"),
#Filter(name="afterDateFilter", condition=":afterDateLocal >= date")
})
I am using Hibernate 5.5.7 so I expect LocalDate to work.
date was not defined in the database, which is why I received the error.
i had same problem ("Undefined filter parameter date value") with creating a filter with the LocalDate and i tried this at the type attribute (type = "java.time.LocalDate") and it worked for me.
I have a date value in format "2021-07-14T13:00:00.000+0300" (or similar). I want to convert it to Date. In this case I have to traverse a loop of different formats and check if they fail.
import java.text.*
import java.util.*
val formats = listOf(
"yyyy-MM-dd'T'HH:mm:ss.SSSZ",
"dd.MM.yyyy, EEEE, HH:mm" // And many others.
)
val date = "2021-07-14T13:00:00.000+0300"
val locale = Locale.getDefault()
for (format in formats) {
try {
return SimpleDateFormat(format, locale).parse(date)
} catch (e: ParseException) {
}
}
// If nothing found, return current date.
return Date()
How to convert this for-loop to something like map? So that we can get the first value without exception?
val result = formats.map { ... }
Another option, while still using firstNotNullOfOrNull(), is to use parse() with a ParsePosition object whose properties you can safely ignore when combined with setLenient(false)*.
The advantage of the parse(String, ParsePosition) version over parse(String) is that it returns null when it can't parse the date, instead of throwing an error, so the try-catch overhead per iteration can be avoided.
Along with that, since you're defaulting to the current date if all formats fail, you can avoid the nullable Date type result with an Elvis op at the very end.
val result: Date = formats.firstNotNullOfOrNull { format ->
with (SimpleDateFormat(format, locale)) {
setLenient(false) // may not be required, see below
parse(date, ParsePosition(0)) // is null or Date
}
} ?: Date()
Btw, setLenient(false) may not be required because on v15, there's no leniency for SimpleDateFormat.parse() in the docs...but it does behave leniently. Setting it to true above or leaving it out, and parsing a date of "2021-07-14T53:00:00.000+0300" (note the '53') produced Fri Jul 16 02:00:00 UTC 2021. With no leniency, it produces null. The leniency is mentioned on the abstract base class DateFormat.parse(String, ParsePosition) but not for SimpleDateFormat.parse(String, ParsePosition).
So if you're expecting non-pattern-matching dates rather than invalid-but-pattern-matching dates, the above loop could be reduced to:
val result: Date = formats.firstNotNullOfOrNull { format ->
SimpleDateFormat(format, locale).parse(date, ParsePosition(0))
} ?: Date()
Use firstNotNullOfOrNull().
val result: Date? = formats.firstNotNullOfOrNull { format ->
try {
SimpleDateFormat(format, locale).parse(date)
} catch (e: ParseException) {
null
}
}
I got a problem with iterating List which got prepared from HQL.
I am querying DB on a single table mapped to very simple class.
After iterating the same list and type casting to same class during iteration I am getting ClassCastException.
Code :
import HectorRequest;
import EDIMigrateData;
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.getCurrentSession();
Transaction tx = session.beginTransaction();
Query qry = session.createQuery("select hr from HectorRequest hr");
List result = qry.list();
for (Iterator it = result.iterator(); it.hasNext();) {
Object o = it.next();
if(o instanceof HectorRequest){
HectorRequest h = (HectorRequest) o;
System.out.println("ID: " + h.getId());
}
}
I wonder here If I am typecasting to the same class it is giving ClassCastException.
if(o instanceof HectorRequest) {
HectorRequest h = (HectorRequest) o;
System.out.println("ID: " + h.getId());
}
The control is not coming into the above if statement.
If I remove the above IF condition it is throwing
java.lang.ClassCastException: HectorRequest
Below is my hibernate mapping xml for HectorRequest class.
Below is my Hibernate.cfg.xml
?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property><property name="hibernate.connection.url">jdbc:oracle:thin:#//apludc01clu20-scan-oravip.dci.bt.com:61901/C2BM2_ANY</property><property name="hibernate.connection.username">s3</property><property name="hibernate.connection.password">**</property><property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property><property name="hibernate.default_schema">s3</property><property name="show_sql">true</property><property name="hibernate.current_session_context_class">thread</property><mapping resource="resources/config/hector_request.hbm.xml"></mapping></session-factory></hibernate-configuration>
Below is the output:
Hibernate: select hectorrequ0_.ID as ID0_, hectorrequ0_.ROUTER_TEL as ROUTER2_0_, hectorrequ0_.FLAGVALUE as FLAGVALUE0_, hectorrequ0_.FLAGPOS as FLAGPOS0_, hectorrequ0_.ACCOUNTNO as ACCOUNTNO0_, hectorrequ0_.CUSTOMERIDENTITY as CUSTOMER6_0_, hectorrequ0_.CRMSOURCE as CRMSOURCE0_, hectorrequ0_.DATASOURCE as DATASOURCE0_ from s3.hector_request hectorrequ0_
java.lang.ClassCastException: HectorRequest
at NotifyMain1.main(NotifyMain1.java:37)
Can someone help what is missing and wrong here.
It is because of the data returned by the query "select hr from HectorRequest hr" is not "HectorRequest". It probably is a database data type (string, number, date, time, etc). So you have to build your "HectorRequest" object using the data returned by the query and not directly assign to it with a cast.
I have a database with a date column, and when I perform a query I get each row as a Map of column names to column values. My problem is I do not know how to generically get the date column.
I am simply trying to cast it to a String at the moment, then parse it as java.util.Date, but this errors at the cast, and I am otherwise unsure as to how I can get the data?
This code is supposed to work with Sybase and Oracle databases too, so a generic answer would be greatly appreciated!
private static final String USER_QUERY = "SELECT USERNAME, PASSWORD, SUSPEND_START_DATE, SUSPEND_END_DATE FROM USERS";
public User readUsers(Subjects subjects) throws SubjectReaderException {
/* Perform the query */
List<User> users = new ArrayList<User>();
List<Map<String, Object>> rows = jdbcTemplate.queryForList(USER_QUERY);
/* Map the returned rows to our User objects */
for (Map<String, Object> row : rows) {
String username = (String) row.get("USERNAME");
/* Check if the user is suspended */
if(checkUserIsSuspended(row)){
continue;
}
User user = new User();
user.setUsername(username);
user.setPassword((String) row.get("PASSWORD"));
users.add(user);
}
return users;
}
private boolean checkUserIsSuspended(Map<String, Object> row) throws SubjectReaderException {
final String startDateString = (String) row.get("SUSPEND_START_DATE"); // this errors
if (startDateString != null) {
final String endDateString = (String) row.get("SUSPEND_END_DATE");
if (null != endDateString) {
return checkDate(startDateString, endDateString); // this just compares the current date etc
}
/* Return true if the Suspended start date is not null, and there is no end date column, or it is null */
return true;
}
/* Return false if the Suspended start date String is null - i.e. they have not been suspended */
return false;
}
The error:
java.lang.ClassCastException: com.sybase.jdbc3.tds.SybTimestamp cannot be cast to java.lang.String
It will always give this error because you are casting the Object com.sybase.jdbc3.tds.SybTimestamp to String.
Why don't you make this check directly in the SQL instead of creating a filter? Something like
SELECT USERNAME, PASSWORD, SUSPEND_START_DATE, SUSPEND_END_DATE
FROM USERS WHERE SUSPEND_START_DATE >= ?
and now you can use the queryForList passing as parameter the current time.
Another way for you to avoid this direct casts is using RowMapper. This way you can use ResultSet#getDate(String) and you won't be needing to cast anything as the JDBC driver will take care of the conversion for you :)