JPA is not creating TIME part of TIMESTAMP - jpa

I have an entity like below
#Entity
#Table(name="PRODUCTS")
public class Feed implements Serializable{
private static final long serialVersionUID = -1732936132016478456L;
#Id
#GeneratedValue( strategy = GenerationType.AUTO)
#Column(name = "ID")
private int id;
#Column(name = "IMAGE_PATH")
private String imagePath;
#Column(name = "DESCRIPTION")
private String description;
#ManyToOne
#JoinColumn(name="UPLOADER", nullable = false)
private User uploader;
#Column(name = "TAGS")
private String tags;
#Column(name = "DATE", columnDefinition="")
private Date date;
#Column(name = "LINK")
private String link;
}
I'm using below code to create entity
#Transactional
#Override
public Feed createFeed(Feed feed) {
this.entityManager.persist(feed);
this.entityManager.flush();
}
Everything is working perfectly but DATE column which is of type timestamp and set to CURRENT_TIMESTAMP as default is only populating Date part not time part.
I tried firing manual query and that populated timestamp properly.
Am I missing anything there?

If the Date is of type java.sql.Date JPA will only store the Date part in the database field.
If it's java.util.Date you must add #Temporal(TemporalType.TIMESTAMP) to also store the time part.
The TemporalType defines the precision of the date.
https://docs.oracle.com/javaee/6/api/javax/persistence/TemporalType.html

I got the solution.
I still don't know the reason and that is why i am not marking this as answer.
I annotated my date variable with #Temporal(TemporalType.DATE) and just that did the trick.
One thing to note: I had used java.util.Date

Related

How can ı get just specific variables in spring?

For example, when I want to get properties of them but not all of them. For example, when I use findAll(); function - it displays everything but I wanna for example just id and name there is any special function or anything for doing this?
Think that ı have an entity class like that.
#Id
private int api_id;
#Column(name = "id")
private int id;
#Column(name = "name")
private String name;
#Column(name = "city")
private String city;
#Column(name = "founded_at")
private int founded_at; //I declare as a integer because the variable consists of 4 integers.
#Column(name = "web_page")
private String web_page;
You can use spring-data's interface based projections to select particular fields from DB:
interface NameAndIdOnly {
int getId();
String getName();
}
and in your repository:
...
List<NameAndIdOnly> findAllWithNameAndId();
...
This will do select id, name from <table>.
Please read Projections for more info.

JPA : query is not cached because it generates multiple SQL statements

I am getting so many warning message log.
Query is not cached because it generates multiple SQL statements. A query can be cached only when it corresponds to a single SQL statement
Runtime W CWWJP9991W: openjpa.Runtime: Warn: Query "SELECT ent FROM Event ent ORDER BY ent.name" is removed from cache excluded permanently.
Query "SELECT ent FROM Event ent ORDER BY ent.name" is not cached because it generates multiple SQL statements.
A query can be cached only when it corresponds to a single SQL statement. .
#Entity
#Table(name="EVENT")
public class Event {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="GEN_ID")
private Long genId;
#Column(name="NAME")
private String name;
#Column(name="LOCATION")
private String location;
#Column(name="EVENT_ID")
private String eventID;
#Temporal(TemporalType.TIMESTAMP)
#Column(name ="CREATION_DATE",nullable=false)
private Date creationDate;
#Temporal(TemporalType.TIMESTAMP)
#Column(name ="START_DATE")
private Date startDate;
#Temporal(TemporalType.TIMESTAMP)
#Column(name ="END_DATE")
private Date endDate;
#Column(name="STATUS")
private String status;
#Column(name="LANGUAGE")
private String language;
#Column(name="ACTIVE")
private Boolean active;
#Column(name="ACCESS_CONTROL")
private Boolean accessControl;
#Column(name="FILE_NAME")
private String fileName;
}

How to check the equality of Two dates in JPA

I am not able to check the equality of two dates in JPA. The comparison below works fine until I add the date of Birth. I am not sure if my JPQL is correct:
TypedQuery<Applicant> query = em.createQuery("select app "
+ "from Applicant app where "
+ "app.firstName = :firstName AND app.middleName = :middleName "
+ "AND app.lastName = :lastName"
+" AND app.dob = :dateOfBirth", Applicant.class);
query.setParameter("firstName", searchableApplicant.getFirstName().trim());
query.setParameter("middleName", searchableApplicant.getMiddleName().trim());
query.setParameter("lastName", searchableApplicant.getLastName().trim());
query.setParameter("dateOfBirth", searchableApplicant.getDob());
Applicant Object properties:
public class Applicant implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "applicant_id")
private Integer applicantId;
#Size(max = 45)
#Column(name = "first_name")
private String firstName;
#Size(max = 45)
#Column(name = "middle_name")
private String middleName;
#Size(max = 45)
#Column(name = "last_name")
private String lastName;
#Size(max = 45)
#Column(name = "maiden_name")
private String maidenName;
#Column(name = "dob")
#Temporal(TemporalType.DATE)
private Date dob;
The JSF date converters defaults to UTC timezone. When intepreting those dates using UTC timezone (as JSF by default does), you will get hours back in time and thus the previous day will be represented.
The solution is right here:
JSF page reflects Date incorrectly - 1 Day shifted

The abstract schema type is unknown

I'm using Spring 3.2.3, JPA 2.1, JUnit 4.11. I'm trying to run a junit test and I keep getting the abstract schema type is unknown error. Here is my entity (truncated for space, it has all the getters and setters):
#Entity
#Table(name = "WEB_PROFILES")
public class TestWebProfile implements Serializable {
private static final long serialVersionUID = 1L;
#Transient
private String forward;
#Column(name = "ACCESS_FLAG")
private String accessFlag;
#Temporal(TemporalType.DATE)
#Column(name = "ACCESS_FLAG_UPD_DATE")
private Date accessFlagUpdDate;
#Column(name = "ACCESS_RESET_INTERVAL")
private BigDecimal accessResetInterval;
#Column(name = "ACCOUNT_TYPE")
private String accountType;
#Column(name = "CREATED_BY")
private String createdBy;
#Column(name = "E_MAIL")
private String eMail;
#Column(name = "FAILED_LOGIN_ATTEMPTS")
private BigDecimal failedLoginAttempts;
#Column(name = "FIRST_NAME")
private String firstName;
#Temporal(TemporalType.DATE)
#Column(name = "FROI_ACCESS_APPROVE_DENY_DATE")
private Date froiAccessApproveDenyDate;
#Column(name = "FROI_ACCESS_APPROVED_FLAG")
private String froiAccessApprovedFlag;
#Column(name = "FROI_ACCESS_REQUESTED")
private String froiAccessRequested;
#Column(name = "FROI_APPROVED_BY")
private String froiApprovedBy;
#Temporal(TemporalType.DATE)
#Column(name = "FROI_CONFIRM_EMAIL_SENT_DATE")
private Date froiConfirmEmailSentDate;
#Temporal(TemporalType.DATE)
#Column(name = "FROI_LETTER_SENT_DATE")
private Date froiLetterSentDate;
#Column(name = "LAST_LOGON_ADDR")
private String lastLogonAddr;
#Temporal(TemporalType.DATE)
#Column(name = "LAST_LOGON_DATE")
private Date lastLogonDate;
#Column(name = "LAST_NAME")
private String lastName;
#Column(name = "LAST_UPDATED_BY")
private String lastUpdatedBy;
#Column(name = "LAST_UPDATED_BY_NAME")
private String lastUpdatedByName;
#Column(name = "LAST_UPDATED_BY_SU_ID")
private BigDecimal lastUpdatedBySuId;
#Temporal(TemporalType.DATE)
#Column(name = "MAIL_SENT_DATE")
private Date mailSentDate;
#Temporal(TemporalType.DATE)
#Column(name = "MAINT_DATE")
private Date maintDate;
#Temporal(TemporalType.DATE)
#Column(name = "NEW_PIN_REQ_DATE")
private Date newPinReqDate;
#Column(name = "PASSWORD")
private String password;
#Transient
private String newPassword;
#Temporal(TemporalType.DATE)
#Column(name = "PASSWORD_UPD_DATE")
private Date passwordUpdDate;
#Column(name = "PHONE")
private String phone;
#Column(name = "PIN")
private String pin;
#Column(name = "POLICY_NUM")
private BigDecimal policyNo;
#Column(name = "PROFILE_CLASS_CODE")
private String profileClassCode;
#Temporal(TemporalType.DATE)
#Column(name = "PROFILE_REQ_DATE")
private Date profileReqDate;
#Temporal(TemporalType.DATE)
#Column(name = "PROFILE_UPDATE_DATE")
private Date profileUpdateDate;
#Column(name = "REMOTE_ADDR")
private String remoteAddr;
#Column(name = "SESSIONID")
private String sessionid;
#Column(name = "SUBSCRIBER_FLAG")
private String subscriberFlag;
#Column(name = "USER_ID")
private BigDecimal userId;
#Id
#Column(name = "USER_NO")
private BigDecimal userNo;
#Column(name = "USERNAME")
private String username;
My JUnit test:
#Test
public void testGetWebProfileByUsername() {
TestWebProfile wp = sso.getWebProfile("MARLENE");
System.out.println("name :" + wp.getFirstName());
System.out.println("last name :" + wp.getLastName());
}
My DAO implementation:
#Override
public TestWebProfile getWebProfile(String username) {
String sqlString = "select w from TestWebProfile w where w.username =:username";
return (TestWebProfile) getEntityManager()
.createQuery(sqlString, TestWebProfile.class)
.setParameter("username", username).getSingleResult();
}
After Googling for the past hour, the only culprit I found that seem to make sense was not having the #Id and #Column annotations, but I have those on the userNo variable. Any help that can be provided would be greatly appreciated!
Have a look at this. It gives some suggesstion for the same case http://java.dzone.com/tips/the-nasty-jpa-unknown-abstract
If you are using Java SE you have to add the fully qualified name of your entity class in persistence.xml, like so
<persistence-unit ...>
<class>your.custom.package.TestWebProfile</class>
</persistence-unit>
Omitting the package part may lead to your error.
Try adding inside your persistence-unit tag as follows:
<exclude-unlisted-classes>false</exclude-unlisted-classes>
For some reason in my case although I was listing all the classes inside my persistence unit using fully qualified names, eclipseLink didn't recognize them. Once added that line, it just works.
I was using:
Java SE 8
Maven Project
EclipseLink (Local not an application server)
Netbeans

JPA Many to One relationship

I am bit beginner on JPA and need some help on fetching the Many to One relationship in JPA.
I have below entities.
User which stores all user information . User extends Audiatable abstract class which is for holding auidt paramters like last modified date, creation date etc.
I am trying to add another fields as lastUpdatedByUser which should get fetched from lastUpdatedBy for which I amtrying to add Many-One relationship.
But the relation is not working somehow, am I doing something wrong here?
AuditableEntity.java
public abstract class AuditableEntity<T extends Entity<T, ID>, ID> implements Auditable {
private static final long serialVersionUID = 1L;
#Column(name = "cruserid")
private Long createdBy;
#Column(name = "crdate")
#Type(type = JpaConstants.TYPE_LOCAL_DATE_TIME)
private LocalDateTime createdOn;
#Column(name = "chuserid")
private Long lastUpdatedBy;
#Column(name = "chdate")
#Type(type = JpaConstants.TYPE_LOCAL_DATE_TIME)
private LocalDateTime lastUpdatedOn;
#Transient
#ManyToOne(fetch = FetchType.LAZY, targetEntity = User.class)
#JoinColumn(name = "usrId", referencedColumnName = "chuserid")
private User lastUpdatedByUser;
User.java
public class User extends AuditableEntity<User, Long> {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "usrId")
private Long id;
#Column(name = "usrName")
private String name;
#Column(name = "loginame")
private String loginName;
}
Well, you marked the association with #Transient, which means that the field is not persistent and should be ignored by JPA.
And you also seem to have two different fields to store the same information: lastUpdatedBy and lastUpdateByUser. Remove the first one, and map the second one as
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "chuserid")
private User lastUpdatedByUser;
This tells that the association is a ManyToOne to the User entity (no need to specify the targetEntity since it's the type of the field), and that this association is materialized by the join column named "chuserid", in the auditable entity's table, and referencing the ID of the User entity (referencedColumnName is only useful when you use composite IDs, or when you reference an entity by a column which is the the ID)