Im having trouble making the datepicker( angularjs-datepicker 720kb.datepicker), it keeps returning dates 1 day before of what it should.
<div class="col-md-5">
<label>Fecha Disposicion</label>
<datepicker date-format="yyyy-MM-dd" date-year-title="selected year">
<input ng-model="vm.auto.fechaDisposicion" />
</datepicker>
</div>
Im using UTC time for the rest of my app, and the back end is springboot data rest and the database mysql (datetime).
Here's the suggested workaround in the git hub proyect, but I don't really get how to implement it.
Output before POST method: "2018-01-03"
Arrives at the DB like this: "2018-01-02 00:00:00"
MY java controller:
package ar.gob.snr.expediente.domain;
import java.io.Serializable;
import java.sql.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.springframework.data.rest.core.annotation.RestResource;
#Entity
#Table(name = "auto")
public class Auto implements Serializable {
private static final long serialVersionUID = -4601105083604023376L;
#Id
#GeneratedValue(strategy = javax.persistence.GenerationType.IDENTITY )
#Column(name = "id")
private Long id;
#Column(name = "expediente_1")
private String expediente1;
#Column(name = "expediente_2")
private String expediente2;
#Column(name = "expediente_3")
private String expediente3;
#Column(name = "expediente_4")
private String expediente4;
#Column(name = "expediente_5")
private String expediente5;
#RestResource(exported = false)
#ManyToOne(cascade = CascadeType.MERGE, fetch= FetchType.EAGER)
#JoinColumn(name = "tipo_documento", referencedColumnName = "id")
private TipoDocumento tipoDocumento;
#Column(name = "numero_documento")
private Integer numeroDocumento;
#Column(name = "auto")
private String auto;
#Column(name = "patente")
private String patente;
#Column(name = "fecha_simbolo")
private Date fechaSimbolo;
#Column(name = "fecha_disposicion")
private Date fechaDisposicion;
#Column(name = "nro_disposicion")
private Integer nroDisposicion;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public TipoDocumento getTipoDocumento() {
return tipoDocumento;
}
public void setTipoDocumento(TipoDocumento tipoDocumento) {
this.tipoDocumento = tipoDocumento;
}
public Integer getNumeroDocumento() {
return numeroDocumento;
}
public void setNumeroDocumento(Integer numeroDocumento) {
this.numeroDocumento = numeroDocumento;
}
public String getExpediente1() {
return expediente1;
}
public void setExpediente1(String expediente1) {
this.expediente1 = expediente1;
}
public String getExpediente2() {
return expediente2;
}
public void setExpediente2(String expediente2) {
this.expediente2 = expediente2;
}
public String getExpediente3() {
return expediente3;
}
public void setExpediente3(String expediente3) {
this.expediente3 = expediente3;
}
public String getExpediente4() {
return expediente4;
}
public void setExpediente4(String expediente4) {
this.expediente4 = expediente4;
}
public String getExpediente5() {
return expediente5;
}
public void setExpediente5(String expediente5) {
this.expediente5 = expediente5;
}
public String getAuto() {
return auto;
}
public void setAuto(String auto) {
this.auto = auto;
}
public String getPatente() {
return patente;
}
public void setPatente(String patente) {
this.patente = patente;
}
public Date getFechaSimbolo() {
return fechaSimbolo;
}
public void setFechaSimbolo(Date fechaSimbolo) {
this.fechaSimbolo = fechaSimbolo;
}
public Date getFechaDisposicion() {
return fechaDisposicion;
}
public void setFechaDisposicion(Date fechaDisposicion) {
this.fechaDisposicion = fechaDisposicion;
}
public Integer getNroDisposicion() {
return nroDisposicion;
}
public void setNroDisposicion(Integer nroDisposicion) {
this.nroDisposicion = nroDisposicion;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Auto other = (Auto) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
Related
I have two tables device_data and device_connection. I want to join these two tables on basis of column customerId. Both the tables have customerId column.
DeviceData
import java.io.Serializable;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "device_data")
public class DeviceData implements Serializable,Cloneable {
#Id
#Column(name = "identifier")
private BigInteger identifier;
#Id
#Column(name = "device_time")
private Timestamp deviceTime;
#Column(name = "ctr_id")
private BigInteger customerId;
#Column(name = "signal_strength")
private Double signalStrength;
#OneToOne
#JoinColumn(name = "ctr_id", nullable = false, insertable = false, updatable = false, referencedColumnName = "ctr_id")
private DeviceConnection deviceConnection;
public BigInteger getIdentifier() {
return identifier;
}
public DeviceData setIdentifier(BigInteger identifier) {
this.identifier = identifier;
return this;
}
public Timestamp getDeviceTime() {
return deviceTime;
}
public DeviceData setDeviceTime(Timestamp deviceTime) {
this.deviceTime = deviceTime;
return this;
}
public BigInteger getCustomerId() {
return customerId;
}
public DeviceData setCustomerId(BigInteger customerId) {
this.customerId = customerId;
return this;
}
public DeviceConnection getDeviceConnection() {
return deviceConnection;
}
public DeviceData setDeviceConnection(
DeviceConnection deviceConnection) {
this.deviceConnection = deviceConnection;
return this;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DeviceData that = (DeviceData) o;
return identifier.equals(that.identifier) &&
deviceTime.equals(that.deviceTime);
}
#Override
public int hashCode() {
return Objects.hash(identifier, deviceTime);
}
}
DeviceConnection
import java.io.Serializable;
import java.math.BigInteger;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name = "device_connection")
public class DeviceConnection implements Serializable , Cloneable {
public DeviceConnection() {
}
#Column(name = "id")
private BigInteger id;
#Column(name = "ctr_id")
private BigInteger customerId;
#Column(name = "low_signal_strength_limit")
private Integer lowSignalStrengthLimit;
public BigInteger getCustomerId() {
return customerId;
}
public DeviceConnection setCustomerId(BigInteger customerId) {
this.customerId = customerId;
return this;
}
public Integer getLowSignalStrengthLimit() {
return lowSignalStrengthLimit;
}
public DeviceConnection setLowSignalStrengthLimit(
Integer lowSignalStrengthLimit) {
this.lowSignalStrengthLimit = lowSignalStrengthLimit;
return this;
}
public BigInteger getId() {
return id;
}
public DeviceConnection setId(BigInteger id) {
this.id = id;
return this;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DeviceConnection that = (DeviceConnection) o;
return Objects.equals(getId(), that.getId());
}
#Override
public int hashCode() {
return Objects.hash(getId());
}
}
I wrote a Query to get data from join of these two tables.
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<DeviceData> cq = cb.createQuery(DeviceData.class);
Root<DeviceData> root = cq.from(DeviceData.class);
Join<DeviceData, DeviceConnection> join = (Join<DeviceData, DeviceConnection>) root
.fetch(DeviceData_.deviceConnection);
List<Predicate> conditions = new ArrayList<>();
conditions.add(cb.equal(root.get(DeviceData_.CUSTOMER_ID), join.get(
DeviceConnection_.CUSTOMER_ID)));
conditions.add(cb.greaterThanOrEqualTo(root.get(DeviceData_.DEVICE_TIME),
config.getDataStartTime()));
if (isNotNull(config.getDataEndTime())) {
conditions.add(cb.lessThanOrEqualTo(root.get(DeviceData_.DEVICE_TIME),
config.getDataEndTime()));
}
cq.where(conditions.toArray(new Predicate[]{}))
.orderBy(cb.asc(root.get(DeviceData_.DEVICE_TIME)));
return session.createQuery(cq);
And I set the property SHOW_SQL to TRUE. So, here is the query which hibernate generate.
select
devicedata0_.occurrence_time as occurren1_3_0_, devicedata0_.identifier as identifier2_3_0_, connection1_.id as id1_0_1_, devicedata0_.ctr_id as ctr_id9_3_0_, devicedata0_.signal_strength as signal_15_3_0_, connection1_.ctr_id as ctr_id7_0_1_, connection1_.low_signal_strength_limit as low_sig14_0_1_
from
device_data devicedata0_
inner join device_connection connection1_ on
devicedata0_.ctr_id=connection1_.ctr_id
where
devicedata0_.ctr_id=connection1_.ctr_id and
devicedata0_.created_at>='2018-06-12 12:00:00'
order by
devicedata0_.created_at asc
limit 2000;
when i run this Query on My Sql workbench it will work expected and give me results. But hibernate constantly giving me exception i don't know why?
Exception
java.lang.ClassCastException: com.sbi.model.DeviceConnection cannot be cast to java.math.BigInteger
i have one issue in my code
#Override
public Turno getTurnoRechazado(Turno t) {
LOGGER.info("start here");
Session session = this.sessionManager.getSession();
Criteria criteria = session.createCriteria(Turno.class);
criteria.add(Restrictions.eq("asunto.id", t.getAsunto().getId()));
criteria.add(Restrictions.eq("unidadDestinatario.id", t.getUnidadDestinatario().getId()));
criteria.add(Restrictions.eq("baja", Boolean.TRUE));
LOGGER.info("stop here"); // stop here unique result is not reached in the execution
return (Turno) criteria.uniqueResult();
}
when this code try to be executed all the code is executed except in the last line
return (Turno) criteria.uniqueResult();
this code is on a DAO and this dao is used into a model this model is tagged with #Transactional
this is the function where this code is used
private boolean checaTurnoRechazado(Turno t, Unidad unidadRaiz) {
LOGGER.info("Entra al turno rechazado");
Turno tr = this.turnoDAO.getTurnoRechazado(t);
LOGGER.info("return getTurnoRechazado"); // this line is not executed
Constants.printObject(tr);
... // another code
return Boolean.FALSE;
}
return Boolean.TRUE;
}
this is my entity:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mx.gob.edomex.dgsei.gestion.data.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Temporal;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.NamedNativeQueries;
import org.hibernate.annotations.NamedNativeQuery;
import org.hibernate.annotations.Parameter;
import org.springframework.format.annotation.DateTimeFormat;
/**
*
* #author ivonne
*/
#NamedNativeQueries({
#NamedNativeQuery(
name = "callUpdateTurno",
query = "CALL UPDATE_TURNO(:turno)",
resultClass = Turno.class)
})
#Entity
#Table(name = "TURNO")
public class Turno implements java.io.Serializable {
private int id;
private Asunto asunto;
private Unidad unidadRemitente;
private Unidad unidadDestinatario;
private Unidad unidadDestinatarioPrincipal;
private Integer unidadRaiz;
private Servicio servicio;
private String proyecto;
private Date fechaRegistro;
private Date fechaVencimiento;
private Date fechaEnterado;
private Integer hijosTerminados;
private boolean vencido;
private Long avanceRelativo;
private boolean asignar;
private boolean autorizar;
private EstatusTurno estatusTurno;
private Instruccion instruccion;
private String requerimiento;
private Long avanceReal;
private boolean baja;
private boolean responsable;
private Integer hijosRechazados;
private boolean hermanosTerminados;
private Date fechaCierre;
private Date fechaVencimientoOriginal;
private TurnoSupervisor turnoSupervisor;
private List<Movimiento> movimientos = new ArrayList<>();
private List<Prorroga> prorrogas = new ArrayList<>();
public Turno() {
}
public Turno(int id, Asunto asunto, Unidad unidadRemitente, Unidad unidadDestinatario, Unidad unidadDestinatarioPrincipal, Integer unidadRaiz, Servicio servicio, String proyecto, Date fechaRegistro, Date fechaVencimiento, Date fechaEnterado, Integer hijosTerminados, boolean vencido, Long avanceRelativo, boolean asignar, boolean autorizar, EstatusTurno estatusTurno, boolean responsable) {
this.id = id;
this.asunto = asunto;
this.unidadRemitente = unidadRemitente;
this.unidadDestinatario = unidadDestinatario;
this.unidadDestinatarioPrincipal = unidadDestinatarioPrincipal;
this.unidadRaiz = unidadRaiz;
this.servicio = servicio;
this.proyecto = proyecto;
this.fechaRegistro = fechaRegistro;
this.fechaVencimiento = fechaVencimiento;
this.fechaEnterado = fechaEnterado;
this.hijosTerminados = hijosTerminados;
this.vencido = vencido;
this.avanceRelativo = avanceRelativo;
this.asignar = asignar;
this.autorizar = autorizar;
this.estatusTurno = estatusTurno;
this.responsable = responsable;
}
#Id
#GenericGenerator(name = "generator", strategy = "sequence-identity", parameters = #Parameter(name = "sequence", value = "TURNO_SEQ"))
#GeneratedValue(generator = "generator")
#Column(name = "ID", unique = true, nullable = false, precision = 8, scale = 0)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#Fetch(org.hibernate.annotations.FetchMode.SELECT)
#JoinColumn(name = "ASUNTO", nullable = false)
public Asunto getAsunto() {
return asunto;
}
public void setAsunto(Asunto asunto) {
this.asunto = asunto;
}
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "UNIDAD_REMITENTE", nullable = false)
public Unidad getUnidadRemitente() {
return unidadRemitente;
}
public void setUnidadRemitente(Unidad unidadRemitente) {
this.unidadRemitente = unidadRemitente;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "UNIDAD_DESTINATARIO", nullable = false)
public Unidad getUnidadDestinatario() {
return unidadDestinatario;
}
public void setUnidadDestinatario(Unidad unidadDestinatario) {
this.unidadDestinatario = unidadDestinatario;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "DESTINATARIO_PRINCIPAL", nullable = true)
public Unidad getUnidadDestinatarioPrincipal() {
return unidadDestinatarioPrincipal;
}
public void setUnidadDestinatarioPrincipal(Unidad unidadDestinatarioPrincipal) {
this.unidadDestinatarioPrincipal = unidadDestinatarioPrincipal;
}
#Column(name = "UNIDAD_RAIZ", precision = 22, scale = 0)
public Integer getUnidadRaiz() {
return unidadRaiz;
}
public void setUnidadRaiz(Integer unidadRaiz) {
this.unidadRaiz = unidadRaiz;
}
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "SERVICIO")
public Servicio getServicio() {
return servicio;
}
public void setServicio(Servicio servicio) {
this.servicio = servicio;
}
public String getProyecto() {
return proyecto;
}
public void setProyecto(String proyecto) {
this.proyecto = proyecto;
}
#DateTimeFormat(pattern = "dd/MM/yyyy")
#Column(name = "FECHA_REGISTRO", nullable = false)
#Temporal(javax.persistence.TemporalType.DATE)
public Date getFechaRegistro() {
return fechaRegistro;
}
public void setFechaRegistro(Date fechaRegistro) {
this.fechaRegistro = fechaRegistro;
}
#DateTimeFormat(pattern = "dd/MM/yyyy")
#Column(name = "FECHA_VENCIMIENTO", nullable = false)
#Temporal(javax.persistence.TemporalType.DATE)
public Date getFechaVencimiento() {
return fechaVencimiento;
}
public void setFechaVencimiento(Date fechaVencimiento) {
this.fechaVencimiento = fechaVencimiento;
}
#Column(name = "HIJOS_TERMINADOS")
public Integer getHijosTerminados() {
return hijosTerminados;
}
public void setHijosTerminados(Integer hijosTerminados) {
this.hijosTerminados = hijosTerminados;
}
#Column(name = "VENCIDO")
public boolean isVencido() {
return vencido;
}
public void setVencido(boolean vencido) {
this.vencido = vencido;
}
#DateTimeFormat(pattern = "dd/MM/yyyy")
#Column(name = "FECHA_ENTERADO", nullable = false)
#Temporal(javax.persistence.TemporalType.DATE)
public Date getFechaEnterado() {
return fechaEnterado;
}
public void setFechaEnterado(Date fechaEnterado) {
this.fechaEnterado = fechaEnterado;
}
#Column(name = "AVANCE_RELATIVO", precision = 8, scale = 0)
public Long getAvanceRelativo() {
return avanceRelativo;
}
public void setAvanceRelativo(Long avanceRelativo) {
this.avanceRelativo = avanceRelativo;
}
#Column(name = "ASIGNAR")
public boolean isAsignar() {
return asignar;
}
public void setAsignar(boolean asignar) {
this.asignar = asignar;
}
#Column(name = "AUTORIZAR")
public boolean isAutorizar() {
return autorizar;
}
public void setAutorizar(boolean autorizar) {
this.autorizar = autorizar;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "ESTATUS_TURNO", nullable = false)
public EstatusTurno getEstatusTurno() {
return estatusTurno;
}
public void setEstatusTurno(EstatusTurno estatusTurno) {
this.estatusTurno = estatusTurno;
}
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "INSTRUCCION")
public Instruccion getInstruccion() {
return instruccion;
}
public void setInstruccion(Instruccion instruccion) {
this.instruccion = instruccion;
}
#Column(name = "REQUERIMIENTO", nullable = true, length = 250)
public String getRequerimiento() {
return requerimiento;
}
public void setRequerimiento(String requerimiento) {
this.requerimiento = requerimiento;
}
#Column(name = "AVANCE_REAL", precision = 8, scale = 0)
public Long getAvanceReal() {
return avanceReal;
}
public void setAvanceReal(Long avanceReal) {
this.avanceReal = avanceReal;
}
#Column(name = "BAJA")
public boolean isBaja() {
return baja;
}
public void setBaja(boolean baja) {
this.baja = baja;
}
#Column(name = "HIJOS_RECHAZADOS")
public Integer getHijosRechazados() {
return hijosRechazados;
}
public void setHijosRechazados(Integer hijosRechazados) {
this.hijosRechazados = hijosRechazados;
}
#JsonIgnore
#Fetch(org.hibernate.annotations.FetchMode.SELECT)
#OneToMany(fetch = FetchType.LAZY, mappedBy = "turno", cascade = {CascadeType.ALL}, orphanRemoval = true)
public List<Movimiento> getMovimientos() {
return this.movimientos;
}
public void setMovimientos(List<Movimiento> movimientos) {
this.movimientos = movimientos;
}
#Column(name = "RESPONSABLE", nullable = true)
public boolean isResponsable() {
return responsable;
}
public void setResponsable(boolean responsable) {
this.responsable = responsable;
}
#Column(name = "HERMANOS_TERMINADOS")
public boolean isHermanosTerminados() {
return hermanosTerminados;
}
public void setHermanosTerminados(boolean hermanosTerminados) {
this.hermanosTerminados = hermanosTerminados;
}
#DateTimeFormat(pattern = "dd/MM/yyyy")
#Column(name = "FECHA_CIERRE", nullable = true)
#Temporal(javax.persistence.TemporalType.DATE)
public Date getFechaCierre() {
return fechaCierre;
}
public void setFechaCierre(Date fechaCierre) {
this.fechaCierre = fechaCierre;
}
#DateTimeFormat(pattern = "dd/MM/yyyy")
#Column(name = "FECHA_VENCIMIENTO_ORIGINAL", nullable = true)
#Temporal(javax.persistence.TemporalType.DATE)
public Date getFechaVencimientoOriginal() {
return fechaVencimientoOriginal;
}
public void setFechaVencimientoOriginal(Date fechaVencimientoOriginal) {
this.fechaVencimientoOriginal = fechaVencimientoOriginal;
}
#OneToOne(fetch = FetchType.LAZY, mappedBy = "turno", cascade = {CascadeType.ALL})
#PrimaryKeyJoinColumn(name="TURNO", referencedColumnName="ID")
public TurnoSupervisor getTurnoSupervisor() {
return turnoSupervisor;
}
public void setTurnoSupervisor(TurnoSupervisor turnoSupervisor) {
this.turnoSupervisor = turnoSupervisor;
}
#JsonIgnore
#Fetch(org.hibernate.annotations.FetchMode.SELECT)
#OneToMany(fetch = FetchType.LAZY, mappedBy = "turno", cascade = {CascadeType.ALL}, orphanRemoval = true)
public List<Prorroga> getProrrogas() {
return prorrogas;
}
public void setProrrogas(List<Prorroga> prorrogas) {
this.prorrogas = prorrogas;
}
#Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof Turno)) {
return false;
}
final Turno turno = (Turno) other;
return turno.getId() == this.getId();
}
#Override
public int hashCode() {
return new Integer(id).hashCode();
}
}
and this is the output:
14:17:04,120 INFO [stdout] (http--127.0.0.1-8080-6) 2015-10-05 14:17:04 INFO AutorizadorController:244 - entra
14:17:04,199 INFO [stdout] (http--127.0.0.1-8080-6) 2015-10-05 14:17:04 INFO AutorizadorModelImpl:467 - Entra al turno rechazado
14:17:04,199 INFO [mx.gob.edomex.dgsei.gestion.data.dao.impl.TurnoDAOImpl] (http--127.0.0.1-8080-6) start here
14:17:04,199 INFO [mx.gob.edomex.dgsei.gestion.data.dao.impl.TurnoDAOImpl] (http--127.0.0.1-8080-6) stop here
rest of the function is waiting for the execution of this line but never happend.
can somebody help or know how this issue is happend?
thanks in advance.
I have a JPA inheritance with a class ContactDTO that is extended by UserDTO with Single_Table strategy:
package ch.ffhs.cryptomess.server.dto;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.ManyToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.persistence.Version;
import org.springframework.transaction.annotation.Transactional;
#Transactional
#Entity(name = "ch.ffhs.cryptomess.server.dto.ContactDTO")
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "discriminator", discriminatorType = DiscriminatorType.STRING)
#DiscriminatorValue(value = "ContactDTO")
#Table(name = "user", uniqueConstraints = #UniqueConstraint(columnNames = {
"username", "discriminator" }))
public class ContactDTO implements Serializable {
private static final long serialVersionUID = 7706720499337697645L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "user_id_seq")
#SequenceGenerator(name = "user_id_seq", allocationSize = 1, initialValue = 10)
#Column(name = "id")
protected Long id;
#Version
protected Long version;
#Column(name = "public_key", length = 255)
protected String publicKey;
#Id
#Column(length = 50, updatable = false)
protected String username;
#ManyToMany(mappedBy = "contacts", targetEntity = CommunicationDTO.class)
protected Set<CommunicationDTO> communications = new HashSet<CommunicationDTO>(
0);
#Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final ContactDTO other = (ContactDTO) obj;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
public Set<CommunicationDTO> getCommunications() {
return communications;
}
public Long getId() {
return id;
}
public String getPublicKey() {
return publicKey;
}
public String getUsername() {
return username;
}
public Long getVersion() {
return version;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((username == null) ? 0 : username.hashCode());
return result;
}
public void setCommunications(final Set<CommunicationDTO> communications) {
this.communications = communications;
}
public void setId(final Long id) {
this.id = id;
}
public void setPublicKey(final String publicKey) {
this.publicKey = publicKey;
}
public void setUsername(final String username) {
this.username = username;
}
public void setVersion(final Long version) {
this.version = version;
}
}
and:
package ch.ffhs.cryptomess.shared.dto;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import org.springframework.transaction.annotation.Transactional;
import ch.ffhs.cryptomess.server.dto.ContactDTO;
import com.google.gwt.view.client.ProvidesKey;
#Transactional
#Entity
#DiscriminatorValue(value = "UserDTO")
public class UserDTO extends ContactDTO implements Serializable {
private static final long serialVersionUID = -3078472527069117428L;
#Column(length = 80)
protected String password;
#Column(name = "is_account_non_expired", columnDefinition = "BIT")
protected boolean isAccountNonExpired;
#Column(name = "is_account_locked", columnDefinition = "BIT")
protected boolean isAccountLocked;
#Column(name = "is_credentials_non_expired", columnDefinition = "BIT")
protected boolean isCredentialsNonExpired;
#Column(name = "is_disabled", columnDefinition = "BIT")
protected boolean isDisabled;
/**
* The key provider that provides the unique ID of a contact.
*/
public static final ProvidesKey<UserDTO> KEY_PROVIDER = new ProvidesKey<UserDTO>() {
#Override
public Object getKey(final UserDTO item) {
return item == null ? null : item.getId();
}
};
public String getPassword() {
return password;
}
public boolean isAccountLocked() {
return isAccountLocked;
}
public boolean isAccountNonExpired() {
return isAccountNonExpired;
}
public boolean isAccountNonLocked() {
return !isAccountLocked;
}
public boolean isCredentialsNonExpired() {
return isCredentialsNonExpired;
}
public boolean isDisabled() {
return isDisabled;
}
public boolean isEnabled() {
return !isDisabled;
}
public void setAccountLocked(final boolean isAccountLocked) {
this.isAccountLocked = isAccountLocked;
}
public void setAccountNonExpired(final boolean isAccountNonExpired) {
this.isAccountNonExpired = isAccountNonExpired;
}
public void setAccountNonLocked(final boolean isAccountNonLocked) {
this.isAccountLocked = !isAccountNonLocked;
}
public void setCredentialsNonExpired(final boolean isCredentialsNonExpired) {
this.isCredentialsNonExpired = isCredentialsNonExpired;
}
public void setDisabled(final boolean isDisabled) {
this.isDisabled = isDisabled;
}
public void setEnabled(final boolean isEnabled) {
this.isDisabled = !isEnabled;
}
public void setPassword(final String password) {
this.password = password;
}
}
If I do a merge or create on an UserDTO-enity, I want the ContactDTO-entity to be created/updated as well in the database. Is there any way to achieve this, without handling both entities seperately?
Thank you for helping!
My JAX-RS Resource is successfully getting a JPA/JAXB entity and a list of JPA/JAXB entities from a db.
One entity serves as a parent entity. The list of entities is a field in the parent entity. I can't set the parent entity's list to the returned list of entities. The parent entity is returned in a JAXB parent entity, but that doesn't affect the situation.
Here's the code:
#Inject
InventoryService inventoryService;
#Inject
HcUser user;
#Inject
InventoryResponse inventoryResponse;
#GET
#Produces(MediaType.APPLICATION_JSON)
public InventoryResponse getInventory(#Context HttpServletRequest request,
#HeaderParam(IDENTITY_URL) String identityURL,
#HeaderParam(ACCESS_TOKEN) String accessToken) {
String username = (String) request.getAttribute("username");
user = inventoryService.getUserById(username);
user.setHcCounts(inventoryService.getCountsForUserId(username));
inventoryResponse.setUser(user);
return inventoryResponse;
}
The returned JSON is only returning the user object. I've tried manually instantiating a user object and setting it to the return value of the getUserById method and then calling setHcCounts with the returned list. However, the setter is still ignored.
What am I doing wrong?
I'm using WAS v8.0.0.8. The stack is:
JAX-RS - Apache Wink v1.1.1 (supplied by WAS 8)
OpenJPA - Apache v2.1.2-SNAPSHOT (supplied by WAS 8)
JAXB - MOXy v2.7
CDI - Apache OpenWebBeans 1.0 (supplied by WAS 8)
EJB - Apache OpenEJB (supplied by WAS 8)
Update 1
Here's the InventoryResponse class as requested, however I don't think that it's necessary. Upon inspecting the user object, on the line before inventoryResonse.setUser(user), during debugging, hcCounts is null.
#Named
#RequestScoped
#XmlRootElement
public class InventoryResponse implements Serializable {
private static final long serialVersionUID = 1L;
#Inject
private HcUser user;
private List<HcLocation> locations;
public HcUser getUser() {
return user;
}
public void setUser(HcUser user) {
this.user = user;
}
public List<HcLocation> getLocations() {
return locations;
}
public void setLocations(List<HcLocation> locations) {
this.locations = locations;
}
}
Update 2
As requested, HcUser:
import java.io.Serializable;
import javax.inject.Named;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Date;
import java.util.List;
#Entity
#Table(schema="<ommitted>", name="<ommitted>")
#Named
#XmlRootElement
public class HcUser implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(unique=true, nullable=false, length=100)
private String id;
#Column(nullable=false, length=1)
private boolean active;
#Temporal(TemporalType.DATE)
#Column(name="CREATE_DATE")
private Date createDate;
#Column(name="FIRST_NAME", length=100)
private String firstName;
#Column(name="LAST_NAME", length=100)
private String lastName;
#Temporal(TemporalType.DATE)
#Column(name="UPDATE_DATE")
private Date updateDate;
//bi-directional many-to-one association to HcAssignment
#OneToMany(mappedBy="hcUser")
#XmlElement
private List<HcAssignment> hcAssignments;
//bi-directional many-to-one association to HcCount
#OneToMany(mappedBy="hcUser")
#XmlElement
private List<HcCount> hcCounts;
public HcUser() {
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public boolean getActive() {
return this.active;
}
public void setActive(boolean active) {
this.active = active;
}
public Date getCreateDate() {
return this.createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getUpdateDate() {
return this.updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public List<HcAssignment> getHcAssignments() {
return this.hcAssignments;
}
public void setHcAssignments(List<HcAssignment> hcAssignments) {
this.hcAssignments = hcAssignments;
}
public HcAssignment addHcAssignment(HcAssignment hcAssignment) {
getHcAssignments().add(hcAssignment);
hcAssignment.setHcUser(this);
return hcAssignment;
}
public HcAssignment removeHcAssignment(HcAssignment hcAssignment) {
getHcAssignments().remove(hcAssignment);
hcAssignment.setHcUser(null);
return hcAssignment;
}
public List<HcCount> getHcCounts() {
return this.hcCounts;
}
public void setHcCounts(List<HcCount> hcCounts) {
this.hcCounts = hcCounts;
}
public HcCount addHcCount(HcCount hcCount) {
getHcCounts().add(hcCount);
hcCount.setHcUser(this);
return hcCount;
}
public HcCount removeHcCount(HcCount hcCount) {
getHcCounts().remove(hcCount);
hcCount.setHcUser(null);
return hcCount;
}
/* (non-Javadoc)
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
/* (non-Javadoc)
* #see java.lang.Object#equals(java.lang.Object)
*/
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof HcUser)) {
return false;
}
HcUser other = (HcUser) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
return true;
}
}
Update 3
Here's the code for HcCount:
import java.io.Serializable;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.persistence.oxm.annotations.XmlInverseReference;
import java.math.BigDecimal;
import java.util.Date;
#Entity
#Table(schema="<omitted>", name="<omitted>")
#Named
#XmlRootElement
public class HcCount implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name="HC_COUNT_ID_GENERATOR", sequenceName="COUNT_SEQ")
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="HC_COUNT_ID_GENERATOR")
#Column(unique=true, nullable=false)
private long id;
#Column(name = "LOCATION_NUM", nullable = false, length = 100)
private String locationNum;
#Column(name = "PRODUCT_CODE", nullable = false, length = 100)
private String productCode;
#Column(name = "USER_ID", nullable = false, length = 100)
private String userId;
#Column(name = "LOT_CODE", nullable = false, length = 100)
private String lotCode;
#Column(name="\"COUNT\"")
private BigDecimal count;
#Temporal(TemporalType.DATE)
#Column(name="COUNT_DATE", unique=true, nullable=false)
private Date countDate;
#Temporal(TemporalType.DATE)
#Column(name="CREATE_DATE")
private Date createDate;
#Temporal(TemporalType.DATE)
#Column(name="UPDATE_DATE")
private Date updateDate;
//bi-directional many-to-one association to HcUser
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="USER_ID", unique=true, nullable=false)
#XmlElement
#XmlInverseReference(mappedBy="hcCounts")
#Inject private HcUser hcUser;
//bi-directional many-to-one association to HcLocation
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="LOCATION_NUM", referencedColumnName="NUM", unique=true, nullable=false)
#XmlElement
#XmlInverseReference(mappedBy="hcCounts")
#Inject private HcLocation hcLocation;
//bi-directional many-to-one association to HcProduct
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="PRODUCT_CODE", referencedColumnName="CODE_ID", unique=true, nullable=false)
#XmlElement
#XmlInverseReference(mappedBy="hcCounts")
#Inject private HcProduct hcProduct;
//bi-directional many-to-one association to HcLot
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="LOT_CODE", referencedColumnName="CODE_ID", unique=true, nullable=false)
#XmlElement
#XmlInverseReference(mappedBy="hcCounts")
#Inject private HcLot hcLot;
public HcCount() {
}
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public String getLocationNum() {
return locationNum;
}
public void setLocationNum(String locationNum) {
this.locationNum = locationNum;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getLotCode() {
return lotCode;
}
public void setLotCode(String lotCode) {
this.lotCode = lotCode;
}
public BigDecimal getCount() {
return this.count;
}
public void setCount(BigDecimal count) {
this.count = count;
}
public Date getCountDate() {
return this.countDate;
}
public void setCountDate(Date countDate) {
this.countDate = countDate;
}
public Date getCreateDate() {
return this.createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getUpdateDate() {
return this.updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public HcUser getHcUser() {
return this.hcUser;
}
public void setHcUser(HcUser hcUser) {
this.hcUser = hcUser;
}
public HcLocation getHcLocation() {
return this.hcLocation;
}
public void setHcLocation(HcLocation hcLocation) {
this.hcLocation = hcLocation;
}
public HcProduct getHcProduct() {
return this.hcProduct;
}
public void setHcProduct(HcProduct hcProduct) {
this.hcProduct = hcProduct;
}
public HcLot getHcLot() {
return this.hcLot;
}
public void setHcLot(HcLot hcLot) {
this.hcLot = hcLot;
}
/* (non-Javadoc)
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id ^ (id >>> 32));
return result;
}
/* (non-Javadoc)
* #see java.lang.Object#equals(java.lang.Object)
*/
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof HcCount)) {
return false;
}
HcCount other = (HcCount) obj;
if (id != other.id) {
return false;
}
return true;
}
}
Update 4
I've figured out a workaround...
public InventoryResponse getInventory(#Context HttpServletRequest request, #HeaderParam(IDENTITY_URL) String identityURL, #HeaderParam(ACCESS_TOKEN) String accessToken) {
String username = (String) request.getAttribute("username");
user = inventoryService.getUserById(username);
List<HcCount> counts = inventoryService.getCountsForUserId(username);
HcUser newUser = new HcUser();
newUser.setHcCounts(counts);
inventoryResponse.setUser(newUser);
return inventoryResponse;
}
I have two classes which has a relationship between them. These are
com.edfx.adb.persist.Activity:
package com.edfx.adb.persist.entity;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.NaturalId;
#javax.persistence.Entity
#Table(name = "ACTIVITY")
public class Activity extends Entity {
#Transient
private static final long serialVersionUID = 4741665931936809028L;
private String activityId;
private String activityName;
private String activityDescription;
private Customer customer;
private ActivityType activityType;
private boolean active;
private Double mandays;
private Double price;
private String manager;
private List<Participation> participations;
public Activity() {
super();
}
#NaturalId
#Column(name = "ACTIVITY_ID", nullable = false)
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
#Lob
#Column(name = "ACTIVITY_NAME", nullable = false)
public String getActivityName() {
return activityName;
}
public void setActivityName(String activityName) {
this.activityName = activityName;
}
#Lob
#Column(name = "ACTIVITY_DESCRIPTION", nullable = false)
public String getActivityDescription() {
return activityDescription;
}
public void setActivityDescription(String activityDescription) {
this.activityDescription = activityDescription;
}
#ManyToOne
#JoinColumn(name = "CUSTOMER_ID", nullable = false)
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
#ManyToOne
#JoinColumn(name = "ACTIVITY_TYPE_ID", nullable = false)
public ActivityType getActivityType() {
return activityType;
}
public void setActivityType(ActivityType activityType) {
this.activityType = activityType;
}
#Column(name = "ACTIVE", nullable = false)
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
#Column(name = "MANDAYS")
public Double getMandays() {
return mandays;
}
public void setMandays(Double mandays) {
this.mandays = mandays;
}
#Column(name = "PRICE")
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
#Column(name = "CUSTOMER_SIDE_MANAGER")
public String getManager() {
return manager;
}
public void setManager(String manager) {
this.manager = manager;
}
#OneToMany(mappedBy = "activity", fetch = FetchType.LAZY)
#Cascade(CascadeType.SAVE_UPDATE)
public List<Participation> getParticipations() {
return participations;
}
public void setParticipations(List<Participation> participations) {
this.participations = participations;
}
}
com.edfx.adb.persist.ActivityType:
package com.edfx.adb.persist.entity;
import javax.persistence.Column;
import javax.persistence.Table;
import javax.persistence.Transient;
#javax.persistence.Entity
#Table(name = "ACTIVITY_TYPE")
public class ActivityType extends Entity {
#Transient
private static final long serialVersionUID = 2322745769010162801L;
private String parent;
private String name;
private String activityId;
public ActivityType() {
}
#Column(name = "PARENT", nullable = false)
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
#Column(name = "NAME", nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "ACTIVITY_ID", nullable = false)
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
}
Both of them extends com.edfx.adb.persist.entity.Entity:
package com.edfx.adb.persist.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.persistence.Version;
import org.hibernate.proxy.HibernateProxyHelper;
#MappedSuperclass
public class Entity implements Serializable {
#Transient
private static final long serialVersionUID = 7470288121057059283L;
private Long id;
private Date createTimestamp;
private Date lastUpdateTimestamp;
private Long version;
public Entity() {
super();
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID", updatable = false, nullable = false, unique = true)
public Long getId() {
return id;
}
#SuppressWarnings("unused")
private void setId(Long id) {
this.id = id;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "CREATE_TIMESTAMP")
public Date getCreateTimestamp() {
return createTimestamp;
}
public void setCreateTimestamp(Date createTimestamp) {
this.createTimestamp = createTimestamp;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "LAST_UPDATE_TIMESTAMP")
public Date getLastUpdateTimestamp() {
return lastUpdateTimestamp;
}
public void setLastUpdateTimestamp(Date lastUpdateTimestamp) {
this.lastUpdateTimestamp = lastUpdateTimestamp;
}
#Version
#Column(name = "VERSION")
public Long getVersion() {
return version;
}
#SuppressWarnings("unused")
private void setVersion(Long version) {
this.version = version;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
return prime * result + ((getId() == null) ? super.hashCode() : getId().hashCode());
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!getClass().equals(HibernateProxyHelper.getClassWithoutInitializingProxy(obj))) {
return false;
}
final Entity other = (Entity) obj;
if (getId() != other.getId()) {
if (getId() == null) {
return false;
}
if (!getId().equals(other.getId())) {
return false;
}
}
return true;
}
}
Now I am using Primefaces datatable to show a List<Activity> in which I have filtering on the field name of ActivityType. ActivityType is associated with Activity by #ManyToOne relationship.
For filtering the List<Activity> I am using:
Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(Activity.class);
criteria.createCriteria("activityType").add(Restrictions.like("name", value.toString(), MatchMode.START));
I am getting:
null: org.hibernate.QueryException: duplicate association path: activityType
at org.hibernate.loader.criteria.CriteriaQueryTranslator.createAssociationPathCriteriaMap(CriteriaQueryTranslator.java:172) [hibernate-core-4.1.8.Final.jar:4.1.8.Final]
at org.hibernate.loader.criteria.CriteriaQueryTranslator.<init>(CriteriaQueryTranslator.java:111) [hibernate-core-4.1.8.Final.jar:4.1.8.Final]
at org.hibernate.loader.criteria.CriteriaLoader.<init>(CriteriaLoader.java:84) [hibernate-core-4.1.8.Final.jar:4.1.8.Final]
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1602) [hibernate-core-4.1.8.Final.jar:4.1.8.Final]
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:374) [hibernate-core-4.1.8.Final.jar:4.1.8.Final]
at com.edfx.adb.dao.ActivityDao.loadActivities(ActivityDao.java:54) [classes:]
at com.edfx.adb.service.ActivityService.loadActivities(ActivityService.java:101) [classes:]
This error is not showing always and never after the first load. After filtering the table for 5-6 time, I am having this error.
I am worried that if the mapping and the criteria is right or not. Any suggestion would be very helpful.
I think you need to provide an alias, so you should change your code this way:
Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(Activity.class);
criteria.createCriteria("activityType", "at")
.add(
Restrictions.like("at.name", value.toString(), MatchMode.START));