I'm trying to setup hibernate in my new project and I have this problem. I'm using oracle database.
In some tables I have more than one column that are timestamp.
Hibernate maps this columns as Serializable.
I tried to change manually to LocalTime type but the project won't even run. I change both on Availability.java and Availability.hbm.xml.
Is it supposed to be Serializable? I would like to use LocalTime instead. Is there a way to do this?
I found this: How to map oracle timestamp to appropriate java type in hibernate?. But it was 5 years ago and it seems like a complicated solution..
public class Availability implements java.io.Serializable {
private int id;
private Teacher teacher;
private byte month;
private short year;
private Serializable initialhour;
private Serializable endhour;
private String weekday;
public void setInitialhour(Serializable initialhour) {
this.initialhour = initialhour;
}
public Serializable getEndhour() {
return this.endhour;
}
}
You can just use:
private Timestamp initialhour;
If you want to can add annotation, but it should work just fine without it:
#Temporal(TemporalType.TIMESTAMP)
private Timestamp initialhour;
If you want to use java 8 DateTime you can use the #Type annotation, something like that:
#Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime initialhour;
Try to add hibernate-java8 to your project. The issue is that LocalTime is a Java8 class which Hibernate does not support by default.
The same happened to me, also with "interval to day" datatype, the easiest way I found to manually solve this was replacing "Serializable" for "Timestamp", not so clean but works for me.
Related
Assume there is an entity like below:
#Entity
class MyEntity{
private Integer myValue;
private LocalDateTime time;
}
and the time is not exactly update time.
Sometime the record is handled like this:
myEntity.setMyValue(10);
myEntity.save();
and also this happens,
myEntity.setMyValue(11);
myEntity.setTime(LocalDateTime.now());
myEntity.save();
but I wonder if there is an alternative way to express the query like below
UPDATE my_entity SET time = now()
I know an annotation #LastModifiedDate but this time I can't use it..
You can use lifecycle events. You can add this method to your entity :
#PrePersist
#PreUpdate
public void saveTime() {
if(this.time == null) {
this.time = LocalDateTime.now();
}
}
You may place the #Column annotation over the time field in your entity and then specify a default value:
#Entity
class MyEntity {
private Integer myValue;
#Column(name="time", columnDefinition="DATETIME DEFAULT NOW()")
private LocalDateTime time;
}
Note that the above assumes that you are using MySQL which uses NOW() for the current datetime. This would have to change depending on your database, so this approach has some tight coupling between your application and the underlying database.
You could also define a default value directly on your database.
I have the following entity:
#Data
#Entity
public class DailyEntry {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private LocalDate date;
private LocalTime startTime;
private LocalTime endTime;
private Duration breaks;
private String performanceRecord;
private EntryStatus status;
#ManyToOne
private Project project;
#ManyToOne
private Employee employee;
}
In the RepositoryRestResource i have the following method defined:
#PostFilter("hasRole('ROLE_BACKOFFICE') or hasRole('ROLE_ADMIN')")
List<DailyEntry> findByProjectId(#Param("id") Long id);
Im able to call that API-method with the following URL for example:
http://localhost:8080/api/dailyEntries/search/findByProjectId?id=1005
This will return all dailyEntries whose project has the id 1005.
Thats how i call it on the client site:
projects.forEach(project => {
const httpParams = new HttpParams().set('id', project.id.toString());
const dailyEntriesObservable = this.dailyEntryService.search('findByProjectId', httpParams);
// the definition of the search method is not important
});
The problem is that in some cases i have around a hundret(and more) projects which resulsts in a hundret(and more) requests which slows things down. Instead of doing a request for every single project, i would like to do one single request for all projects. Should i just send the Ids of the project in the RequestBody? How would the URL look like? Would it be something like http://localhost:8080/api/dailyEntries/search/findByProjectIds with the Ids being in the RequestBody? Ive never seen such a GET-request, so im not sure how the standarts here are for the REST-URL-Design or whether im doing something wrong and theres actually a better way to do it.
Context
My objective is to change the status of myObject if the day's date is equal to the date stored in myObject entity.
So, can you tell me and explain me what is the best way to execute a function every day at a specific time with H2 database and Java?
My entity
#Entity
public MyObject {
#Id
private String id;
private LocalDate endDate;
private boolean status; // true: on going , false: ended
...
}
My idea
Used the annotation #Schedule like this
#Scheduled(cron = "0 0 0 * * ?")
public void checkMyObjectsEnd() {
...
}
Conclusion
Or maybe H2 has native functions to do this? Like CREATE EVENT on SQL.
Thanks for your advice.
I'm new on publishing something on Stackoverflow but I use it for along time and it was amazing helping me coding.
My problem was the follow:
I receive a object filled in a WebService by SOAP like:
#WebMethod(operationName = "DogUpdate")
public #WebResult(name = "resultId")
Long dogUpdate(
#WebParam(name = "DogDto", header = true, mode = Mode.IN) DogDto dog);
So now I need to update on DB using Hibernate 5.0.2.
The class DogDto is like this:
Entity
#Table(name="Dog", indexes={}, uniqueConstraints={})
class Dog implements Dog_i
{
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="DOG_SEQ")
#SequenceGenerator(name="DOG_SEQ", sequenceName="DOG_SEQ", allocationSize=1)
#Id
#Column(name="ID", unique=true, nullable=false)
private Long id;
#Column(name="Name", length=30)
private String name;
#Column(name="BirthDate")
private Date birthDate;
#Column(name="NumberDogSons")
private Long numberDogSons;
#Column(name="namesDogSons")
private List<String> namesDogSons;
}
So my problem is I doesnt know what is the values of the DogDto I receive in my WebService, so I doesnt know what I need to change.
I saw that's Reflection can helps but I have a complex object like (List inside the object dogs and like 'Owner' and others more)
What I can do update the object with info not lost? Because if a field cames null (when is a Long, Integer, int...) it shows like 0 and other relevant problems.
Do you have any suggestion?
Many thanks for everyone :)
So my problem is I doesnt know what is the values of the DogDto I receive in my WebService, so I doesnt know what I need to change.
From you code above, you seem to get a "DogDto dog".
You just have to make hibernate persist this dog object using saveOrUpdate method.
If your ID is well defined Hibernate will update the existing if it exists, otherwise it will insert a new one.
I use #Audited annotation in Spring to have auditing about my update, create etc. on my db.
But I obtain on my database, a date-time with 2 hour less than real time, for example, I created a object and the I saved it, I have as create date-time: 2014-08-04 12:0 but I created it at 14:00.
This is my Auditor class, that every class audited extend:
#SuppressWarnings("serial")
#MappedSuperclass
public abstract class AbstractAudit implements Auditable<String, Long>, Serializable {
#Version
private int version;
#JsonIgnore
#Column(updatable=false)
private String createdBy;
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
#DateTimeFormat(iso=ISO.DATE_TIME)
#JsonIgnore
#Column(updatable=false)
private DateTime createdDate;
#JsonIgnore
private String lastModifiedBy;
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
#DateTimeFormat(iso=ISO.DATE_TIME)
#JsonIgnore
private DateTime lastModifiedDate;
//getter and setter method
}
How can I fix it??
Have I add some configuration on my project or on my server (Tomcat 7) ?
Thanks
Try to set this property in your jpa provider settings:
<prop key="jadira.usertype.databaseZone">jvm</prop>
Hope this helps.
Regards