How to get hibernate to store a date? - mysql

I have a Spring / Hibernate project and I am trying to store a date into the database but it's not working. It must be something stupid but I have no idea what I am doing wrong.
Here is my code:
user.setFailedPasswordAnswerAttemptCount(0);
user.setLastLoginDate(new Date());
user.setIsOnline(true);
The other two variables (failedPasswordAnswerAttemptCount and isOnline) are getting written to the database without issue. I have also tried it with just passing a java.util.Date instead of a java.sql.Timestamp...same result. Here is how the property is defined on the user object:
private Date lastLoginDate;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="last_login_date")
public Date getLastLoginDate() {
return this.lastLoginDate;
}
public void setLastLoginDate(Date lastLoginDate) {
this.lastLoginDate = lastLoginDate;
}
Here is the column definition:
`last_login_date` datetime DEFAULT NULL
Any help? I don't even know what else to look for as this should be working.
Some more detail about the error: No errors or strange messages in the hibernate log. The hibernate log is showing a parameterized query but it isn't telling me what it is actually writing. It looks like it's not updating the column at all. In other words, if there is already a date there it doesn't change, or if it is null it doesn't change.
Update: I have looked at the logs and it looks like hibernate does write the proper data, but then immediately writes the incorrect data again. I see the following entry in the log:
11:15:12.280 [http-bio-8080-exec-26] TRACE o.h.e.def.AbstractSaveEventListener - detached instance of: com.hi.model.User
11:15:12.280 [http-bio-8080-exec-26] TRACE o.h.e.def.DefaultMergeEventListener - merging detached instance
And right after that I see it putting the old value back in for the lastLoginDate.

Why are you using
Date date = new Date();
user.setLastLoginDate(new Timestamp(date.getTime()));
and not just this?
user.setLastLoginDate(new Date());
First - You may not want to use Date and Timestamp at the same time.(e.g. for collections, etc)
There are some classes in the Java platform libraries that do extend an instantiable
class and add a value component. For example, java.sql.Timestamp
extends java.util.Date and adds a nanoseconds field. The equals implementation
for Timestamp does violate symmetry and can cause erratic behavior if
Timestamp and Date objects are used in the same collection or are otherwise intermixed.
The Timestamp class has a disclaimer cautioning programmers against
mixing dates and timestamps. While you won’t get into trouble as long as you
keep them separate, there’s nothing to prevent you from mixing them, and the
resulting errors can be hard to debug. This behavior of the Timestamp class was a
mistake and should not be emulated. (Bloch, Effective Java, 2nd Ed.)
Second - I checked your examples, and it works fine for me on mysql-connector(5.1.21) / hibernate (4.0.1)
I prepared simple test project with arquillian integration test(You need to prepare jboss before running it):
https://github.com/rchukh/StackOverflowTests/tree/master/13803848
If you can provide some more information it might help - hibernate version, mysql version, mysql engine(MyISAM, InnoDB, etc.)
Otherwise it is possible that this is just a misconfiguration.

I found the problem. I am refactoring some code and it looks like I was doing this:
//get user object
User user = getUser();
//call a function which modifies user
functionModifiesUser();
//modify user
user.blah = blah;
entityManager.merge(user);
So the parent function had a stale copy of the user object when I tried to save it. Actually, removing the merge statement was enough to fix it. But I have refactored the code to put all this in one place.

Setting the column last_login_date as timestamp should work, at least works for me.

Related

osisoft updating values ​with python

I want to get the data from Excel and update the values ​​of the data between certain dates in the osisoft system. But I don't know how to code AfTimeRange.
I get the error "value cannot be converted to OSIsoft.AF.Time.AFTime".
enter image description here
Good news: You've constructed your [AFTimeRange] correctly!
Notice that the error being thrown is not by the [AFTimeRange] constructor, but from something else.
The issue is that you are trying to set the 'Timestamp' attribute [OSIsoft.AF.Time.AFTime] to a value of type [OSIsoft.AF.Time.AFTimeRange], and so it's failing. A PI event has a single timestamp, not a time range.
I'm not familiar with Python, but it should work if you input the value as an AFTime object using its string constructor, assuming you're intending to use yesterday midnight as your timestamp:
val.timestamp = AFTime("y")
See the documentation on AFTime for more detail.

What could lead to JPA entity state discrepancy within single thread?

I am experiencing a strange intermittent issue with JPA/Hibernate and MySQL 5.7. I'm looking for suggestions.
My entity is defined with:
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created_at", nullable = false)
protected Date createdAt;
which translates to the following SQL table definition:
`created_at` DATETIME NOT NULL
and the timestamp is set upon entity creation using
#PrePersist
protected void onCreate() {
updatedAt = createdAt = new Date();
}
JPA save operation sometimes leads to SQL error due to null value being supposedly sent in UPDATE query via Spring CRUD rest repository.
I have verified the post request includes the created_at field, but more importantly, the following screenshot of my log feed confirms that the created_at value is present. However subsequent save blows out. (There is only one "createdAt" field if anyone wondered):
Note: The AOP advices are used for spring-acl integration and don't manipulate entity data (they do provide a convenient interception for logging purposes as seen in the screenshot above).
I can't reliably replicate the error. What could be the reason behind this strange behaviour? I thought second level caching - tried disabling #Cacheable on the entity, but to no avail. Enabling detailed logging with SQL binding is not practical due to irregular nature of the issue.

How to work with input dates in a MySql / Laravel (5.6) / AngularJs application?

In my application, a user can specify a date in a form, via a datepicker. Doing so, the date has this format : "2018-05-16T12:45:30Z".
Then, I want to store it in a MySql database, in a TIMESTAMP column.
Later, the user can edit his data. Consequently, the datepicker has to be initialized with the date coming from the server, previously saved.
To manage this, I created an accessor and a mutator :
public function setDateNameInputAttribute($value)
{
$this->attributes['date_name_input'] = Carbon::createFromFormat('Y-m-d\TH:i:s\Z', $value);
}
public function getDateNameInputAttribute($value)
{
return Carbon::parse($value)->format('Y-m-d\TH:i:s\Z');
}
This code works fine : my front-end reads UTC (Zulu) dates and I can insert timestamps in my database.
However, it's not perfect.
Let's say I need for whatever reason to add one hour to a stored date
$myObject = MyClass::find(1);
$theDate = $myObject->dateNameInput;
Now $theDate is a "T Z format" string, because of the accessor. I could recreate a Carbon object to do my addition, but I think this Carbon -> string -> Carbon transition would be ugly. How can I make a nice operation ?
If my applications contains a lot of input dates, with many different model names, is there a way to generalize my accessor and my mutator ?
Actually, is my first approach good ?
Thanks for reading !

Correct timezone handling with TYPO3 and Fluid

Its confusing me. I've a property in my Model which is annotated with DateTime. In my Database its stored as timestamp. In Frontend I use the f:format.date viewhelper to output this property.
When I create a new record, and add f.e. 01.06.2017 10:00 in this field, in my database is stored the timestamp for 01.06.2017 08:00. In Frontend the output is correct. Until here everything is fine.
The last timechange in March lead to a + of two hours in output. I assume in October that will change again and the output will be than this: 01.06.2017 08:00.
How can I prevent this. Its definitely a problem when these dates change, because its important for the business.
How can I test what will happen in October?
The Problem occurs as TYPO3 saves times normalized as UTC. for normalization (and afterwards denormalization) it respects the timezone-settings of the server. Or settings given in LocalConfiguration.php.
Up to 6.2 there were two settings [SYS][serverTimeZone] and [SYS][phpTimeZone].
With 7.6 it is only [SYS][phpTimeZone] as the servertimezone is detected from php itself.
You now have the option to fake the timezone of your server to "UTC" by setting [SYS][phpTimeZone] to the string "UTC". In this way no times should be changed any more.
TYPO3 9.5 and newer
Use the environment (documentation)
// use TYPO3\CMS\Core\Utility\GeneralUtility;
// use TYPO3\CMS\Core\Context\Context;
$context = GeneralUtility::makeInstance(Context::class);
// Reading the current data instead of $GLOBALS
$currentTimezone = $context->getPropertyFromAspect('date', 'timezone');
$currentTstamp = $context->getPropertyFromAspect('date', 'timestamp');
$current = new DateTime('#'.$currentTstamp);
$current->setTimezone(new DateTimeZone($currentTimezone) );
In Fluid you may use a DateTime-Object:
// in PHP-ode of Viewhelper
//...
$this->registerArgument('date', 'mixed', 'Either an object implementing DateTimeInterface or a string that is accepted by DateTime constructor');
// ...
In HTML
{dateTimeObject -> f:format.date()}
<f:format.date format="d.m.Y">{dateTimeObject}</f:format.date>

Linq to SQL "Cannot insert the value NULL" when NOT NULL!

I am massively in need to help. I have spent an entire day when I do not have even an hour to waste on a project. I have a Linq to SQL data layer and am doing a simple insert into the DB using the following code:
using (var odc = new OrdersDataContext())
{
try
{
var id = GetNextOrderId(odc);
order.ID = id;
odc.tblOrders.InsertOnSubmit(order);
odc.SubmitChanges();
}
catch (Exception ex)
{
Logger.LogException(ex);
}
}
Due to other legacy code and this being a database that is running on SQL 2000 I cannot make database alterations, but this code was working fine at one point and then simply stopped working. It is saying that :
Cannot insert the value NULL into column 'ID', table 'Order'; column does not allow nulls. INSERT fails.
But as you can see from the code and what I can CLEARLY see as I step through the code, the ID column is getting a valid ID number. For some reason even though I am setting the ID field it is attempting to insert it as a null even though this code was working fine before. I've gone so far as to completely restore the database and rebuilt the data layer, but to no avail.
I'm so stumped on this and out of time that I'm beside myself.
So, the answer to this is very strange and I'm not 100% certain of why. Essentially what I did was completely rebuild the LINQ to SQL data layer (merely dragging and dropping the same tables in the designer) and then completely cleaning and rebuilding the entire solution. After that the code magically worked again. No code change required.
For some reason the code was improperly cached and that caused it to not be able to transfer the object to the data layer (is my guess). It seems like a strange error to get back in that case.