assign timestamp in jpa annotation - jpa

is there a way to automatically assing a timestamp value in a Date variable on a enity EJB?
here is how my enity looks like.
package com.jr.entities;
import java.util.Date;
import javax.persistence.Column;
public class TransactionDAO {
private String uid;
private ProductDAO product;
#Column(name="date")
private Date date;
private String customerId;
}
i could not find any examples how this is done or does this have to be done programatically?

What do you mean, have an initial value for new objects?
Just initialize it in the object's constructor, or in the field def.

Related

#JsonProperty annotation is getting ignored in mongodb collection

As I'm new to springboot and mongodb I've used https://start.spring.io/ and generated a demo project with following settings.
Then created a model as below:
package com.example.model;
import java.io.Serializable;
import java.time.LocalDate;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.mongodb.core.mapping.Document;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
#Getter
#Setter
#ToString
#Configuration
#Document(collection = "customer")
#JsonIgnoreProperties(ignoreUnknown = true)
public class Customer implements Serializable {
private static final long serialVersionUID = 6748432793461621268L;
#JsonProperty("customer_id")
private String customerId;
#JsonProperty(value= "external_customer_reference_id")
private String externalCustomerReferenceId;
#JsonProperty("title")
private String title;
#JsonProperty("first_name")
private String firstName;
#JsonProperty("middle_name")
private String middleName;
#JsonProperty("last_name")
private String lastName;
#JsonProperty("email")
private String email;
#JsonProperty("phone")
private String phone;
#JsonProperty("note")
private String note;
#JsonProperty("date_of_birth")
private String dateOfBirth;
#JsonProperty("sex")
private String sex;
#JsonProperty("contact_address")
private Address address;
#CreatedDate
#JsonProperty("create_timestamp")
private LocalDate createdDate;
#LastModifiedDate
#JsonProperty("modified_timestamp")
private LocalDate modifiedDate;
}
I'm able to save customer in mongodb collection customer. But the collection attribute names are not as same as #JsonProperty("modified_timestamp").
Why db collection attribute names are not as same as JsonProperty? How do I get db collection attribute names as same as JsonProperty?
In MongoDB you're saving an object with his properties names.
JsonProperty annotation mapping the deserialization and the serialization with given object.
Marker annotation that can be used to define a non-static method as a
"setter" or "getter" for a logical property (depending on its
signature), or non-static object field to be used (serialized,
deserialized) as a logical property. Default value ("") indicates that
the field name is used as the property name without any modifications,
but it can be specified to non-empty value to specify different name.
Property name refers to name used externally, as the field name in
JSON objects.
https://fasterxml.github.io/jackson-annotations/javadoc/2.8/com/fasterxml/jackson/annotation/JsonProperty.html
By using #Field property annotation you can save property in different name as in object.

JPA Audit Null CreatedBy

I am using spring MVC with mongodb and using auditing entities to save the creation and last edition user and time. So my AudtingEntity, from which all objects inherit from, is like this:
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.joda.time.DateTime;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.mongodb.core.mapping.Field;
/**
* Base abstract class for entities which will hold definitions for created, last modified by and created,
* last modified by date.
*/
public abstract class AbstractAuditingEntity {
#CreatedBy
#Field("created_by")
#JsonIgnore
private String createdBy;
#CreatedDate
#Field("created_date")
#JsonIgnore
private DateTime createdDate = DateTime.now();
#LastModifiedBy
#Field("last_modified_by")
#JsonProperty(access = JsonProperty.Access.READ_ONLY)
private String lastModifiedBy;
#LastModifiedDate
#Field("last_modified_date")
#JsonProperty(access = JsonProperty.Access.READ_ONLY)
private DateTime lastModifiedDate = DateTime.now();
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public DateTime getCreatedDate() {
return createdDate;
}
public void setCreatedDate(DateTime createdDate) {
this.createdDate = createdDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public DateTime getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(DateTime lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
}
It works perfectly when I first save an object, but when I edit it the createdBy becomes null and the createdDate is updated also with the updating date. It happens because I'm ignoring these properties on front end and they are null when I save. A possible solution is to find the object in DB before save, then copy the properties to the updated object and save. However I don't like this solution because is needed to write this specific code for any object. I think probably there is a smarter way to solve this, configuring somehow to never update these fields in database after creation.
I tried to use the following property on these 2 fields, but didn't work:
#Column(updatable = false)

FindBy method returnign all records in PagingAndSortingRepository

Im using a findBy method in a interface that extends PagingAndSortingRepository. This method is:
public List<MyType> findByClassification(String classification);
When I invoke this method (myObject.findByClassification("A")), it returns all values and not only records filtered by classification "A".
The class model:
package mypackage;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "mytype")
public class MyType implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private Integer id;
private String name;
private String classification;
//getters and setters
}
Other find methods work fine:
findByClassificationAndName_StartingWith
findByName
These methods return only filtered records and not all records in table.
Any idea?
Thanks!

Get Max value of a column from DB in Hal-Json using Spring Data REST

I have a Spring project where I access the database using Spring Data REST (using http://spring.io/guides/gs/accessing-data-rest/)
#RepositoryRestResource(collectionResourceRel = "test", path = "test")
public interface TestRepository extends PagingAndSortingRepository<Test, Long> {
#Query("SELECT max(p.lastUpdatedDate) FROM Test p")
Date findLastUpdatedDate();
}
When I try to access the above method to get the MAX date using the URL localhost:8080/test/search/findLastUpdatedDate, I get the error
{"cause":null,"message":"Cannot create self link for class java.sql.Timestamp! No persistent entity found!"}
Please suggest how can I get the max lastUpdatedDate from the Test table. Thanks!
Here is my Test class:
#Entity
#Table(name="test")
public class Test implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String col1;
private String col2;
private String status;
#Column(name = "last_updated_date")
private Date lastUpdatedDate;
// getters, setters, hashcode, equals, toString methods are written
}
You need to use the #Temporal annotation on dates.
You should also use java.util.Date or Joda time instead of java.sql.Timestamp
Spring Data JPA also has built-in created/modified timestamps, so you should look into that:
http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#auditing

playframework JPA Error and DB design issue

I get the following error:
JPA error
A JPA error occurred (Unable to build EntityManagerFactory): #OneToOne or #ManyToOne on models.Issue.project references an unknown entity: models.Project
Here you can see my entities:
package models;
import java.util.*;
import javax.persistence.*;
import play.db.jpa.*;
import models.Issue;
import models.Component;
public class Project extends Model{
public String self;
#Id
public String key;
#OneToMany (mappedBy="Project", cascade=CascadeType.ALL)
public List<Component> components;
#OneToMany (mappedBy="Project", cascade=CascadeType.ALL)
public List<Issue> issues;
public Project(String self, String key) {
this.self = self;
this.key = key;
this.components = new ArrayList<Component>();
this.issues = new ArrayList<Issue>();
}
public Project addComponent(String self, int component_id, String name, int issuecount) {
Component newComponent = new Component(self, component_id, name, issuecount, this);
this.components.add(newComponent);
return this;
}
public Project addIssue(Date created, Date updated, String self, String key,
String type, Status status) {
Issue newIssue = new Issue(created, updated, self, key, type, status, this);
this.issues.add(newIssue);
return this;
}
}
and this is the other
package models;
import java.util.*;
import javax.persistence.*;
import play.db.jpa.*;
import models.Project;
import models.Status;
import models.Component;
#Entity
public class Issue extends Model {
#Id
public String key;
public Date created;
public Date updated;
public String self;
public String type;
#ManyToOne
public Status status;
#ManyToOne
public Project project;
#OneToMany
public List<Component> components;
public Issue(Date created, Date updated, String self, String key,
String type, Status status, Project project ) {
this.created = created;
this.updated = updated;
this.self = self;
this.key = key;
this.status = status;
this.type = type;
this.project=project;
this.components=new ArrayList<Component>();
}
public Issue addComponent(Component component) {
this.components.add(component);
return this;
}
}
I'm using Play 1.2.4 and Eclipse. Now my db is in mem.
I have also a second question. Ideally I need a db for each user and I want to delete the content of the tables every time the user logs in ( or logs out ) and populate the table again when the user logs in (this is because the information stored in my db must be in synch with service I'm connecting to ). How should I do?
I totally have no clue. Please help me.
public class Project extends Model
is missing the #Entity annotation
The "mappedBy" should reference the property in the other entity which is "project" and not "Project".