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
Related
I have the query below:
#Query(value="select t.* from titulos t " +
"where (CAST(:modelosNota AS modelo_nota_fiscal) IS NULL OR t.modelo in (:modelosNota)) order by t.vencimento", nativeQuery = true)
List<Titulo> relatorioTitulosPagarReceber(#Param("modelosNota") String[] modelosNota);
But when it is executed I get the exception below:
org.postgresql.util.PSQLException: ERROR: operator does not exist: modelo_nota_fiscal = bytea
Dica: No operator matches the given name and argument type(s). You might need to add explicit type casts.
I think the message is not very accurate because I already have the type cast to modelo_nota_fiscal which is as custom domain type with a check constraint for some values.
When I run the query in PGAdmin it executes normally:
select t.* from titulos t where (CAST(null AS modelo_nota_fiscal) IS NULL OR t.modelo in (null)) order by t.vencimento;
Or this one that works just fine:
select t.* from titulos t where (CAST('NFe' AS modelo_nota_fiscal) IS NULL OR t.modelo in ('NFe')) order by t.vencimento;
My entity class as requested:
#Data
#EqualsAndHashCode(callSuper = false)
#AllArgsConstructor
#NoArgsConstructor
#Builder
#Entity
#Table(name = "titulos")
public class Titulo extends AbstractEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Column(length = 30)
private String numero;
#Basic(optional = false)
#Column(nullable = false)
private short natureza;
#Basic(optional = false)
#Column(nullable = false)
private short origem;
#Basic(optional = false)
#Column(nullable = false, precision = 20, scale = 4)
private BigDecimal valor;
#Transient
#Column(name = "valorbaixado")
private BigDecimal valorBaixado;
#Transient
#Column(name = "saldoliquidotitulo")
private BigDecimal saldoLiquidoTitulo;
#Transient
#Column(name = "saldobrutotitulo")
private BigDecimal saldoBrutoTitulo;
#Basic(optional = false)
#Column(nullable = false, precision = 20, scale = 4)
private BigDecimal acrescimo;
#Basic(optional = false)
#Column(nullable = false, precision = 20, scale = 4)
private BigDecimal desconto;
#Basic(optional = false)
#Column(nullable = false, precision = 20, scale = 4)
private BigDecimal juros;
#Basic(optional = false)
#Column(nullable = false, precision = 20, scale = 4)
private BigDecimal multa;
#Basic(optional = false)
#Column(nullable = false)
private LocalDate emissao;
#Basic(optional = false)
#Column(nullable = false)
private LocalDate vencimento;
#Basic(optional = false)
#Column(name = "datamulta")
private LocalDate dataMulta;
#Basic(optional = false)
#Column(nullable = false)
private short situacao;
#Column(length = 2147483647)
private String observacao;
#Column(length = 2147483647)
private String historico;
#Column(length = 20, name = "documentovinculado")
private String documentoVinculado;
#Column(name = "parcela")
private Integer parcela;
#Column(name = "totalparcelas")
private Integer totalParcelas;
#Column(name = "modelo")
private String modelo;
#Column(name = "numerodocumentofiscal")
private String numeroDocumentoFiscal;
#Column(name = "seriedocumentofiscal")
private String serieDocumentoFiscal;
#Column(name = "subseriedocumentofiscal")
private String subserieDocumentoFiscal;
#Column(name = "cfop_codigo")
private String cfopCodigo;
#Column(name = "pis_retido", precision = 20, scale = 2)
private BigDecimal pisRetido;
#Column(name = "cofins_retido ", precision = 20, scale = 2)
private BigDecimal cofinsRetido;
#Column(name = "csll_retido ", precision = 20, scale = 2)
private BigDecimal csllRetido;
#Column(name = "irrf_retido ", precision = 20, scale = 2)
private BigDecimal irrfRetido;
#Column(name = "inss_retido ", precision = 20, scale = 2)
private BigDecimal inssRetido;
#Column(name = "iss_retido ", precision = 20, scale = 2)
private BigDecimal issRetido;
#Column(name = "valor_base ", precision = 20, scale = 2)
private BigDecimal valorBase;
#Column(name = "competencia")
private LocalDate competencia;
#Column(name = "linhadigitavelboleto", length = 44)
private String linhaDigitavelBoleto;
}
Here's my Postgre custom domain type:
CREATE DOMAIN public.modelo_nota_fiscal
AS character varying(3)
COLLATE pg_catalog."default"
CONSTRAINT check_modelo_nota_fiscal CHECK (VALUE::text = 'NFs'::text OR VALUE::text = 'NFe'::text OR VALUE::text = 'CEE'::text OR VALUE::text = 'CFG'::text OR VALUE::text = 'CFA'::text);
ALTER DOMAIN public.modelo_nota_fiscal
OWNER TO postgres;
COMMENT ON DOMAIN public.modelo_nota_fiscal
IS 'MODELO NOTA FISCAL: (NFs) Nota Fiscal de Serviço, (NFe) Nota Fiscal Eletrônica, (CEE) Conta de Energia Elétrica, (CFG) Conta de Fornecimento de Gás, (CFA) Conta de Fornecimento de Água.';
Does anyone know how am I supposed to cast to a custom Postgres domain using Spring Data 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
Below is my entity
#Entity
#Table(name = "xxxxx")
public class xxxx implements Serializable {
private static final long serialVersionUID = -1935611638367876605L;
#Column(name = "PHONE1")
private long phone1;
#Column(name = "PHONE2")
private long phone2;
#Column(name = "SSN")
private String ssn;
}
My requirement is a combination of SSN && (phone1 || phone2)
is this a valid query creation using the keywords(And ,Or)
findBySSNAndPhone1Orphone2?
#Query("select x from Xxx x where x.ssn = ?1 and (x.phone1 = ?2 or x.phone2 = ?3)")
List<Xxx> findBySsnAndPhone1OrPhone2(String ssn, String phone1, String phone2);
I am pretty new to java and data entities and I am getting the, "Exception Description: An incompatible mapping has been encountered between [class com.store.Product] and [class com.store.Cart]." error and not sure why (obviously).
My mappings are as follows:
Product.java
#Basic(optional = false)
#NotNull
#Column(name = "P_QTY")
private Integer pQty;
#Column(name = "P_PRICE")
private BigDecimal pPrice;
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "P_ID")
private String pId;
#Size(max = 10)
#Column(name = "P_NAME")
private String pName;
#Size(max = 20)
#Column(name = "P_DESC")
private String pDesc;
#OneToMany(mappedBy = "pId")
Cart.java
#Id
#Basic(optional = false)
#NotNull
#Column(name = "C_ID")
private String cId;
#Basic(optional = false)
#NotNull
#Column(name = "C_QTY")
private Integer cQty;
#Column(name = "C_PRICE")
private Double cPrice;
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 10)
#JoinColumn(name = "P_ID", referencedColumnName = "P_ID")
#ManyToOne
private String pId;
Any ideas? Like I said, I'm new to data entities and have done enough reading to confuse myself at this point so I apologize for any and all idiocy on my part.
Thanks in advance.
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