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.
Related
So I was trying to insert a boarding pass item (BoardingPassSessionBean) into a database and it came out with this exception. I did try to figure out what was wrong but I am so confused. I didn't even set the boarding pass id to have ticket flight in the (BoardingPassSessionBean) but somehow the Exceptions show cant set flight id to ticketflight. Any help or advice would be greatly appreciated. Through debug mode i know that the exception happen while persisting the item
TicketFlight
#Entity
#Table(name = "ticket_flights", schema = "bookings")
public class TicketFlight {
#EmbeddedId
private TicketFlightId id;
#MapsId("flightId")
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
#JoinColumn(name = "flight_id")
private Flight flight;
#Column(name = "fare_conditions", nullable = false, length = 10)
private String fareConditions;
#Column(name = "amount", nullable = false, precision = 10, scale = 2)
private BigDecimal amount;
#OneToOne(fetch = FetchType.LAZY, mappedBy = "ticketFlights", cascade = { CascadeType.MERGE, CascadeType.REMOVE })
private BoardingPass boardingPasses;
#MapsId("ticketNo")
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
#JoinColumn(name = "ticket_no")
private Ticket ticket;
public TicketFlight() {}
public TicketFlight(TicketFlightId id) {
this.id = id;
}
public Ticket getTicket() {
return ticket;
}
public void setTicket(Ticket ticket) {
this.ticket = ticket;
}
public BoardingPass getBoardingPasses() {
return boardingPasses;
}
public void setBoardingPasses(BoardingPass boardingPasses) {
this.boardingPasses = boardingPasses;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public String getFareConditions() {
return fareConditions;
}
public void setFareConditions(String fareConditions) {
this.fareConditions = fareConditions;
}
public Flight getFlight() {
return flight;
}
public void setFlight(Flight flight) {
this.flight = flight;
}
public TicketFlightId getId() {
return id;
}
public void setId(TicketFlightId id) {
this.id = id;
}
}
BoardingPassSessionBean
#Stateless
public class BoardingPassSessionBean implements BoardingPassSessionBeanLocal{
#PersistenceContext(unitName = "flightApp")
EntityManager em;
#Override
public void addBoardingPass(TicketDTO ticketDTO, TicketFlight ticketFlight) throws EJBException {
BoardingPass boardingPass = new BoardingPass();
setBoardingPassDetail(boardingPass, ticketFlight, ticketDTO);
em.persist(boardingPass);
}
private void setBoardingPassDetail(BoardingPass boardingPass, TicketFlight ticketFlight, TicketDTO ticketDTO) {
Random rand = new Random();
boardingPass.setBoardingNo(rand.nextInt());
boardingPass.setId(new BoardingPassId(ticketFlight.getId().getTicketNo(), ticketFlight.getId().getFlightId()));
boardingPass.setSeatNo(ticketDTO.getSeatNo());
boardingPass.setTicketFlights(ticketFlight);
}
}
BoardingPass
#Entity
#Table(name = "boarding_passes", schema = "bookings")
public class BoardingPass {
#EmbeddedId
private BoardingPassId id;
#MapsId
#OneToOne(fetch = FetchType.LAZY, optional = false, cascade = CascadeType.REMOVE)
#JoinColumns({
#JoinColumn(name = "ticket_no", referencedColumnName = "ticket_no", nullable = false),
#JoinColumn(name = "flight_id", referencedColumnName = "flight_id", nullable = false)
})
private TicketFlight ticketFlights;
#Column(name = "boarding_no", nullable = false)
private Integer boardingNo;
#Column(name = "seat_no", nullable = false, length = 4)
private String seatNo;
public BoardingPass() {}
public String getSeatNo() {
return seatNo;
}
public void setSeatNo(String seatNo) {
this.seatNo = seatNo;
}
public Integer getBoardingNo() {
return boardingNo;
}
public void setBoardingNo(Integer boardingNo) {
this.boardingNo = boardingNo;
}
public TicketFlight getTicketFlights() {
return ticketFlights;
}
public void setTicketFlights(TicketFlight ticketFlights) {
this.ticketFlights = ticketFlights;
}
public BoardingPassId getId() {
return id;
}
public void setId(BoardingPassId id) {
this.id = id;
}
}
BoardingPassId
#Embeddable
public class BoardingPassId implements Serializable {
private static final long serialVersionUID = -4075241131735714893L;
#Column(name = "ticket_no", nullable = false, length = 13)
private String ticketNo;
#Column(name = "flight_id", nullable = false)
private Integer flightId;
public BoardingPassId() {}
public Integer getFlightId() {
return flightId;
}
public void setFlightId(Integer flightId) {
this.flightId = flightId;
}
public String getTicketNo() {
return ticketNo;
}
public void setTicketNo(String ticketNo) {
this.ticketNo = ticketNo;
}
#Override
public int hashCode() {
return Objects.hash(ticketNo, flightId);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
BoardingPassId entity = (BoardingPassId) o;
return Objects.equals(this.ticketNo, entity.ticketNo) &&
Objects.equals(this.flightId, entity.flightId);
}
public BoardingPassId(String ticketNo, Integer flightId) {
this.ticketNo = ticketNo;
this.flightId = flightId;
}
}
I'd tried to execute the code below:
criteria.createAlias("veiculosCredencial", "veiculoCredencialAlias");
criteria.add(Restrictions.isNull("cancelamentoCredencial"));
DetachedCriteria subcriteria = DetachedCriteria.forClass(CredencialXVeiculo.class, "cv");
subcriteria.add(Restrictions.eq("cv.credencialXVeiculoPK.credencialCttuPK.modal", filtro.getModalEquals()));
subcriteria.add(Restrictions.isNull("cv.fimVinculo"));
subcriteria.add(Property.forName("cv.credencialXVeiculoPK.CredencialCttuPK.id").eqProperty("veiculoCredencialAlias.credencialAlias.credencialXVeiculoPK.CredencialCttuPK.id") );
subcriteria.setProjection(Projections.property("cv.credencialXVeiculoPK.credencialCttuPK"));
criteria.add(Subqueries.notExists(subcriteria));
So, i have the following error:
org.hibernate.HibernateException: Unknown entity: null
This problem happens because I want it to recognize the alias created in the criteria within the subcriteria:
subcriteria.add(Property.forName("cv.credencialXVeiculoPK.CredencialCttuPK.id").eqProperty("veiculoCredencialAlias.credencialAlias.credencialXVeiculoPK.CredencialCttuPK.id") );
How can I do this correctly?
main entity
#Audited
#AuditTable(value = "TBCREDENCIALCTTUHIST")
#Table(name = "SCTR.TBCREDENCIALCTTU")
#Entity
public class CredencialCttu implements Serializable {
private static final long serialVersionUID = -8315891299493474295L;
#EmbeddedId
private CredencialCttuPK credencialCttuPK;
#NotNull
#Column(name = "DCREDEDTCR")
private Date criacaoCredencial;
#Column(name = "DCREDEDTCN")
private Date cancelamentoCredencial;
#Column(name = "XCREDEOBSE")
private String observacaoCredencial;
#Column(name = "CTPTXIORIG")
private String placaVeiculo;
#Column(name = "CTPTXITIPO")
private String tipoTaxi;
#NotNull
#Column(name = "TCREDEULAT")
private Date ultimaAtualizacao;
#ManyToOne
#Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED)
#JoinColumn(name = "CTPCRDCODG")
private TipoCredencial tipoCredencial;
#OneToOne
#JoinColumn(name = "CMDALCCODG", insertable = false, updatable = false)
#NotAudited
private Modal modal;
// #OneToOne
// #JoinColumn(name = "CCREDECODG", insertable = false, updatable = false)
// #NotAudited
// private long sequencialCredencial;
#Transient
private List<PessoaWS> pessoasWs;
#OrderBy(clause = "fimVinculo DESC")
#OneToMany(mappedBy = "credencialXVeiculoPK.credencialCttuPK", cascade = CascadeType.ALL, orphanRemoval = true)
#NotAudited
private List<CredencialXVeiculo> veiculosCredencial;
#OneToMany(mappedBy = "credencialXPessoaPK.credencialCttuPK", cascade = CascadeType.ALL, orphanRemoval = true)
#NotAudited
private List<CredencialXPessoa> pessoasCredencial;
#OneToMany(mappedBy = "capXLinhaPK.credencialCttuPK", cascade = CascadeType.ALL, orphanRemoval = true)
#NotAudited
private List<CapXLinha> linhasCredencial;
#OneToMany(mappedBy = "credencialXLocalAtendimentoPK.credencialCttuPK", cascade = CascadeType.ALL, orphanRemoval = true)
#NotAudited
private List<CredencialXLocalAtendimento> locaisCredencial;
#OneToMany(mappedBy = "corridasCredencialPK.credencialCttuPK", cascade = CascadeType.ALL, orphanRemoval = true)
#NotAudited
private List<CorridasCredencial> corridasCredencial;
#OneToMany(mappedBy = "credencial")
#NotAudited
private List<Anexo> anexos;
#OneToMany(mappedBy = "credencialCttu", cascade = CascadeType.ALL, orphanRemoval = true)
#NotAudited
private List<Cobranca> cobrancas;
// #NotAudited
// #Formula("(SELECT * FROM SCTR.TBCREDENCIALXVEICULO AS c WHERE c.CCREDECODG = CCREDECODG AND c.CMDALCCODG = CMDALCCODG AND c.DCREVCDTFV IS NULL )")
// private CredencialXVeiculo veiculoAtivoDaCredencial; // Isso é um CredencialXVeiculo, não é Veiculo
// public CredencialXVeiculo getVeiculoAtivoDaCredencial() {
// return veiculoAtivoDaCredencial;
// }
//
// public void setVeiculoAtivoDaCredencial(CredencialXVeiculo veiculoAtivoDaCredencial) {
// this.veiculoAtivoDaCredencial = veiculoAtivoDaCredencial;
// }
//Guarda a ultima data de entrada de permissionario ou autorizatário na credencial
#NotAudited
#Formula("(SELECT MAX(t.TCREPSDTIN) FROM SCTR.TBCREDENCIALXPESSOA t WHERE t.CCREDECODG = CCREDECODG AND t.CMDALCCODG = CMDALCCODG AND t.ATPPSSSEQU IN (1,2))")
private Date LastDtEntradaPermoOuAutor;
public List<PessoaWS> getPessoasWs() {
if (pessoasWs == null) {
pessoasWs = new ArrayList<>();
}
return pessoasWs;
}
public void setPessoasWs(List<PessoaWS> pessoasWs) {
this.pessoasWs = pessoasWs;
}
public CredencialCttu() {
this.credencialCttuPK = new CredencialCttuPK();
}
public CredencialCttu(Long id) {
super();
this.credencialCttuPK.setId(id);
}
public Long getId() {
return this.credencialCttuPK.getId();
}
public void setId(Long id) {
this.credencialCttuPK.setId(id);
}
public Modal getModal() {
return credencialCttuPK.getModal();
}
public void setModal(Modal modal) {
this.credencialCttuPK.setModal(modal);
}
public CredencialCttuPK getCredencialCttuPK() {
return credencialCttuPK;
}
public void setCredencialCttuPK(CredencialCttuPK credencialCttuPK) {
this.credencialCttuPK = credencialCttuPK;
}
public Date getCriacaoCredencial() {
return criacaoCredencial;
}
public void setCriacaoCredencial(Date criacaoCredencial) {
this.criacaoCredencial = criacaoCredencial;
}
public Date getCancelamentoCredencial() {
return cancelamentoCredencial;
}
public void setCancelamentoCredencial(Date cancelamentoCredencial) {
this.cancelamentoCredencial = cancelamentoCredencial;
}
public String getObservacaoCredencial() {
return observacaoCredencial;
}
public void setObservacaoCredencial(String observacaoCredencial) {
this.observacaoCredencial = observacaoCredencial;
}
public String getPlacaVeiculo() {
if (placaVeiculo != null) {
return placaVeiculo;
}
return "NÃO INFORMADO";
}
public void setPlacaVeiculo(String placaVeiculo) {
this.placaVeiculo = placaVeiculo;
}
public String getTipoTaxi() {
return tipoTaxi;
}
public void setTipoTaxi(String tipoTaxi) {
this.tipoTaxi = tipoTaxi;
}
public List<CredencialXPessoa> getPessoasCredencial() {
return pessoasCredencial;
}
public void setPessoasCredencial(List<CredencialXPessoa> pessoasCredencial) {
this.pessoasCredencial = pessoasCredencial;
}
public List<CredencialXVeiculo> getVeiculosCredencial() {
return veiculosCredencial;
}
public void setVeiculosCredencial(List<CredencialXVeiculo> veiculosCredencial) {
this.veiculosCredencial = veiculosCredencial;
}
public List<CorridasCredencial> getCorridasCredencial() {
return corridasCredencial;
}
public List<Anexo> getAnexos() {
return anexos;
}
public void setAnexos(List<Anexo> anexos) {
this.anexos = anexos;
}
public List<Cobranca> getCobrancas() {
return cobrancas;
}
public void setCobrancas(List<Cobranca> cobrancas) {
this.cobrancas = cobrancas;
}
public void setCorridasCredencial(List<CorridasCredencial> corridasCredencial) {
this.corridasCredencial = corridasCredencial;
}
public List<CapXLinha> getLinhasCredencial() {
return linhasCredencial;
}
public void setLinhasCredencial(List<CapXLinha> linhasCredencial) {
this.linhasCredencial = linhasCredencial;
}
public List<CredencialXLocalAtendimento> getLocaisCredencial() {
return locaisCredencial;
}
public void setLocaisCredencial(List<CredencialXLocalAtendimento> locaisCredencial) {
this.locaisCredencial = locaisCredencial;
}
public Date getUltimaAtualizacao() {
return ultimaAtualizacao;
}
public void setUltimaAtualizacao(Date ultimaAtualizacao) {
this.ultimaAtualizacao = ultimaAtualizacao;
}
public TipoCredencial getTipoCredencial() {
return tipoCredencial;
}
public void setTipoCredencial(TipoCredencial tipoCredencial) {
this.tipoCredencial = tipoCredencial;
}
// public Integer getSequencial_veiculo_ativo() {
// return sequencial_veiculo_ativo;
// }
//
// public void setSequencial_veiculo_ativo(Integer sequencial_veiculo_ativo) {
// this.sequencial_veiculo_ativo = sequencial_veiculo_ativo;
// }
public Date getLastDtEntradaPermoOuAutor() {
return LastDtEntradaPermoOuAutor;
}
public void setLastDtEntradaPermoOuAutor(Date lastDtEntradaPermoOuAutor) {
LastDtEntradaPermoOuAutor = lastDtEntradaPermoOuAutor;
}
Ps:
For knowledge, my intention is to do this query with hibernate features
SELECT c.CMDALCCODG, c.CCREDECODG, c.DCREDEDTCR, c.DCREDEDTCN, c.CTPTXIORIG, c.CTPTXITIPO,c.XCREDEOBSE
FROM SCTR.TBCREDENCIALCTTU c, SCTR.TBCREDENCIALXVEICULO cv1
WHERE c.CMDALCCODG = cv1.CMDALCCODG AND
c.CCREDECODG = cv1.CCREDECODG AND
cv1.CMDALCCODG = 2 AND
c.DCREDEDTCN IS NULL AND
NOT EXISTS (SELECT cv2.AVECLOSEQU
FROM SCTR.TBCREDENCIALXVEICULO cv2
WHERE cv2.DCREVCDTFV IS NULL AND
cv2.CMDALCCODG = 2 AND
cv2.CCREDECODG = cv1.CCREDECODG)
ORDER BY 2
the above java code does this,but not completely because of the error mentioned.
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));
I'm using netbeans and generate entity class from database. All of my merge calls to insert and update entities are working perfectly, but when I try to remove an entity, it doesn't delete it from the database, and no exception is thrown. Can someone help me solved. My code below:
AbstractFacade.java
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0]);
q.setFirstResult(range[0]);
return q.getResultList();
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
AccountEntity.java
#Entity
#Table(name = "Account")
public class AccountEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "account_id")
private Long accountId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "account_user", nullable = false, length = 100)
private String accountUser;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "account_pass", nullable = false, length = 100)
private String accountPass;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "account_fullname", nullable = false, length = 100)
private String accountFullName;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "account_email", nullable = false, length = 100)
private String accountEmail;
#Basic(optional = false)
#Size(min = 1, max = 100)
#Column(name = "account_phone", nullable = true, length = 100)
private String accountPhone;
#Basic(optional = false)
#Size(min = 1, max = 100)
#Column(name = "account_address", nullable = true, length = 100)
private String accountAddress;
#JoinColumn(name = "role_id", referencedColumnName = "role_id")
#ManyToOne(optional = false)
private RoleEntity roleId;
#JoinColumn(name = "dealer_id", referencedColumnName = "dealer_id")
#ManyToOne(optional = false)
private DealerEntity dealerId;
#Basic(optional = false)
#NotNull
#Column(name = "isAvailable", nullable = false)
private boolean available;
public AccountEntity() {
}
public AccountEntity(Long accountId) {
this.accountId = accountId;
}
public AccountEntity(Long accountId, String accountUser, String accountPass) {
this.accountId = accountId;
this.accountUser = accountUser;
this.accountPass = accountPass;
}
public Long getAccountId() {
return accountId;
}
public void setAccountId(Long accountId) {
this.accountId = accountId;
}
public String getAccountUser() {
return accountUser;
}
public void setAccountUser(String accountUser) {
this.accountUser = accountUser;
}
public String getAccountPass() {
return accountPass;
}
public void setAccountPass(String accountPass) {
this.accountPass = accountPass;
}
public String getAccountFullName() {
return accountFullName;
}
public void setAccountFullName(String accountFullName) {
this.accountFullName = accountFullName;
}
public String getAccountEmail() {
return accountEmail;
}
public void setAccountEmail(String accountEmail) {
this.accountEmail = accountEmail;
}
public String getAccountPhone() {
return accountPhone;
}
public void setAccountPhone(String accountPhone) {
this.accountPhone = accountPhone;
}
public String getAccountAddress() {
return accountAddress;
}
public void setAccountAddress(String accountAddress) {
this.accountAddress = accountAddress;
}
public RoleEntity getRoleId() {
return roleId;
}
public void setRoleId(RoleEntity roleId) {
this.roleId = roleId;
}
public DealerEntity getDealerId() {
return dealerId;
}
public void setDealerId(DealerEntity dealerId) {
this.dealerId = dealerId;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
#Override
public int hashCode() {
int hash = 0;
hash += (accountId != null ? accountId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
if (!(object instanceof AccountEntity)) {
return false;
}
AccountEntity other = (AccountEntity) object;
if ((this.accountId == null && other.accountId != null) || (this.accountId != null && !this.accountId.equals(other.accountId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entities.AccountEntity[ accountId=" + accountId + " ]";
}
}
DealerEntity.java
#Entity
#Table(name = "Dealer")
public class DealerEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "dealer_id")
private Long dealerId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "dealer_name", nullable = false, length = 100)
private String dealerName;
#Size(max = 100)
#Column(name = "dealer_phone", length = 100)
private String dealerPhone;
#Size(max = 100)
#Column(name = "dealer_fax", length = 100)
private String dealerFax;
#Size(max = 100)
#Column(name = "dealer_address", length = 100)
private String dealerAddress;
#Size(max = 100)
#Column(name = "dealer_coordinate", length = 100)
private String dealerCoordinate;
#Size(max = 100)
#Column(name = "state_name", length = 100)
private String stateName;
#Basic(optional = false)
#NotNull
#Column(name = "isRoot", nullable = false)
private boolean isRoot;
#Basic(optional = false)
#NotNull
#Column(name = "isAvailable", nullable = false)
private boolean isAvailable;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "dealerId")
private List<CustomerEntity> customerEntityList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "dealerId")
private List<ServiceEntity> serviceEntityList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "dealerId")
private List<AccountEntity> accountEntityList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "dealerId")
private List<PurchaseOrderEntity> purchaseOrderEntityList;
#JoinColumn(name = "country_id", referencedColumnName = "country_id", nullable = false)
#ManyToOne(optional = false)
private CountryEntity countryId;
public DealerEntity() {
}
public DealerEntity(Long dealerId) {
this.dealerId = dealerId;
}
public DealerEntity(Long dealerId, String dealerName, boolean isRoot, boolean isAvailable) {
this.dealerId = dealerId;
this.dealerName = dealerName;
this.isRoot = isRoot;
this.isAvailable = isAvailable;
}
public Long getDealerId() {
return dealerId;
}
public void setDealerId(Long dealerId) {
this.dealerId = dealerId;
}
public String getDealerName() {
return dealerName;
}
public void setDealerName(String dealerName) {
this.dealerName = dealerName;
}
public String getDealerPhone() {
return dealerPhone;
}
public void setDealerPhone(String dealerPhone) {
this.dealerPhone = dealerPhone;
}
public String getDealerFax() {
return dealerFax;
}
public void setDealerFax(String dealerFax) {
this.dealerFax = dealerFax;
}
public String getDealerAddress() {
return dealerAddress;
}
public void setDealerAddress(String dealerAddress) {
this.dealerAddress = dealerAddress;
}
public String getDealerCoordinate() {
return dealerCoordinate;
}
public void setDealerCoordinate(String dealerCoordinate) {
this.dealerCoordinate = dealerCoordinate;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public boolean getIsRoot() {
return isRoot;
}
public void setIsRoot(boolean isRoot) {
this.isRoot = isRoot;
}
public boolean getIsAvailable() {
return isAvailable;
}
public void setIsAvailable(boolean isAvailable) {
this.isAvailable = isAvailable;
}
#XmlTransient
public List<CustomerEntity> getCustomerEntityList() {
return customerEntityList;
}
public void setCustomerEntityList(List<CustomerEntity> customerEntityList) {
this.customerEntityList = customerEntityList;
}
#XmlTransient
public List<ServiceEntity> getServiceEntityList() {
return serviceEntityList;
}
public void setServiceEntityList(List<ServiceEntity> serviceEntityList) {
this.serviceEntityList = serviceEntityList;
}
#XmlTransient
public List<AccountEntity> getAccountEntityList() {
return accountEntityList;
}
public void setAccountEntityList(List<AccountEntity> accountEntityList) {
this.accountEntityList = accountEntityList;
}
#XmlTransient
public List<PurchaseOrderEntity> getPurchaseOrderEntityList() {
return purchaseOrderEntityList;
}
public void setPurchaseOrderEntityList(List<PurchaseOrderEntity> purchaseOrderEntityList) {
this.purchaseOrderEntityList = purchaseOrderEntityList;
}
public CountryEntity getCountryId() {
return countryId;
}
public void setCountryId(CountryEntity countryId) {
this.countryId = countryId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (dealerId != null ? dealerId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof DealerEntity)) {
return false;
}
DealerEntity other = (DealerEntity) object;
if ((this.dealerId == null && other.dealerId != null) || (this.dealerId != null && !this.dealerId.equals(other.dealerId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entities.DealerEntity[ dealerId=" + dealerId + " ]";
}
}
It would appear that your persistence context is not in synch with the underlying database.
Try the following:
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
getEntityManager().flush();
}
I got the above error though i have set the ID manually, Im not using auto generated key here.
when i set the key and pass the object to
entityManager.persist(obj);
it gives the above error.
any help... plz
thanks
This is the InstallationInfo class, and I got the above error when persisting the installationInfo object. The complete error is
org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): se.cambio.cimonitor.jpa.table.ModuleInfo
so I have attached the ModuleInfo class as well
package se.cambio.cimonitor.jpa.table;
#Entity
#Table(name = "InstallationInfo", catalog="CI_Monitor", schema="dbo")
public class InstallationInfo implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String installationId;
private String timestamp;
private Module moduleByParentId;
private Environment environmentByEnvironmentClientId;
private Environment environmentByEnvironmentServerId;
private Module moduleByBaseLineId;
private String machineName;
private String status;
private String teamName;
private Set<ModuleInfo> moduleInfos = new HashSet<ModuleInfo>(0);
public InstallationInfo() {
}
public InstallationInfo(String installationId) {
this.installationId = installationId;
}
public InstallationInfo(String installationId,
Module moduleByParentId,
Environment environmentByEnvironmentClientId,
Environment environmentByEnvironmentServerId,
Module moduleByBaseLineId, String machineName,
String status, String teamName,
Set<ModuleInfo> moduleInfos) {
this.installationId = installationId;
this.moduleByParentId = moduleByParentId;
this.environmentByEnvironmentClientId = environmentByEnvironmentClientId;
this.environmentByEnvironmentServerId = environmentByEnvironmentServerId;
this.moduleByBaseLineId = moduleByBaseLineId;
this.machineName = machineName;
this.status = status;
this.teamName = teamName;
this.moduleInfos = moduleInfos;
}
/*#TableGenerator(name="InstlIds", table="InstlPkTb", pkColumnName="InstlId", pkColumnValue="InstlIdVal", allocationSize=1, catalog="CI_Monitor", schema="dbo")
#GeneratedValue(strategy=GenerationType.TABLE, generator="InstlIds")*/
#Id
#Column(name = "InstallationId", unique = true, nullable = false, insertable = true, updatable = true)
public String getInstallationId() {
return this.installationId;
}
public void setInstallationId(String installationId) {
this.installationId = installationId;
}
//#Version This is a bug
#Column(name = "Timestamp")
public String getTimestamp() {
return this.timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ParentId")
public Module getModuleByParentId() {
return this.moduleByParentId;
}
public void setModuleByParentId(Module moduleByParentId) {
this.moduleByParentId = moduleByParentId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "EnvironmentClientId")
public Environment getEnvironmentByEnvironmentClientId() {
return this.environmentByEnvironmentClientId;
}
public void setEnvironmentByEnvironmentClientId(
Environment environmentByEnvironmentClientId) {
this.environmentByEnvironmentClientId = environmentByEnvironmentClientId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "EnvironmentServerId")
public Environment getEnvironmentByEnvironmentServerId() {
return this.environmentByEnvironmentServerId;
}
public void setEnvironmentByEnvironmentServerId(
Environment environmentByEnvironmentServerId) {
this.environmentByEnvironmentServerId = environmentByEnvironmentServerId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "BaseLineId")
public Module getModuleByBaseLineId() {
return this.moduleByBaseLineId;
}
public void setModuleByBaseLineId(Module moduleByBaseLineId) {
this.moduleByBaseLineId = moduleByBaseLineId;
}
#Column(name = "MachineName")
public String getMachineName() {
return this.machineName;
}
public void setMachineName(String machineName) {
this.machineName = machineName;
}
#Column(name = "Status")
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
#Column(name = "TeamName")
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "installationInfo", targetEntity=ModuleInfo.class, cascade={CascadeType.ALL}) //targerEntity is added by Isuru
public Set<ModuleInfo> getModuleInfos() {
return this.moduleInfos;
}
public void setModuleInfos(Set<ModuleInfo> moduleInfos) {
this.moduleInfos = moduleInfos;
}
}
package se.cambio.cimonitor.jpa.table;
#Entity
#Table(name = "ModuleInfo", catalog="CI_Monitor", schema="dbo")
public class ModuleInfo implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private ModuleInfoId id;
private InstallationInfo installationInfo;
private Module moduleByModuleId;
private Module moduleByParentId;
private Module moduleByBaseLineId;
private String buildNo;
private String svnRevision;
public ModuleInfo() {
}
public ModuleInfo(ModuleInfoId id, InstallationInfo installationInfo,
Module moduleByModuleId) {
this.id = id;
this.installationInfo = installationInfo;
this.moduleByModuleId = moduleByModuleId;
}
public ModuleInfo(ModuleInfoId id, InstallationInfo installationInfo,
Module moduleByModuleId, Module moduleByParentId,
Module moduleByBaseLineId, String buildNo,
String svnRevision) {
this.id = id;
this.installationInfo = installationInfo;
this.moduleByModuleId = moduleByModuleId;
this.moduleByParentId = moduleByParentId;
this.moduleByBaseLineId = moduleByBaseLineId;
this.buildNo = buildNo;
this.svnRevision = svnRevision;
}
#EmbeddedId
#AttributeOverrides({
#AttributeOverride(name = "moduleId", column = #Column(name = "ModuleId", nullable = false)),
#AttributeOverride(name = "installationId", column = #Column(name = "InstallationId", nullable = false)) })
public ModuleInfoId getId() {
return this.id;
}
public void setId(ModuleInfoId id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "InstallationId", nullable = false, insertable = false, updatable = false, unique = true)
public InstallationInfo getInstallationInfo() {
return this.installationInfo;
}
public void setInstallationInfo(InstallationInfo installationInfo) {
this.installationInfo = installationInfo;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ModuleId", nullable = false, insertable = false, updatable = false)
public Module getModuleByModuleId() {
return this.moduleByModuleId;
}
public void setModuleByModuleId(Module moduleByModuleId) {
this.moduleByModuleId = moduleByModuleId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ParentId")
public Module getModuleByParentId() {
return this.moduleByParentId;
}
public void setModuleByParentId(Module moduleByParentId) {
this.moduleByParentId = moduleByParentId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "BaseLineId")
public Module getModuleByBaseLineId() {
return this.moduleByBaseLineId;
}
public void setModuleByBaseLineId(Module moduleByBaseLineId) {
this.moduleByBaseLineId = moduleByBaseLineId;
}
#Column(name = "BuildNo")
public String getBuildNo() {
return this.buildNo;
}
public void setBuildNo(String buildNo) {
this.buildNo = buildNo;
}
#Column(name = "SvnRevision")
public String getSvnRevision() {
return this.svnRevision;
}
public void setSvnRevision(String svnRevision) {
this.svnRevision = svnRevision;
}
}
You have a cascade all on ModuleInfos collection, so when you save InstallationInfo it will try to save all the associated ModuleInfos. You need to make sure that the ids of the ModuleInfos are set before saving the InstallationInfo object.
#OneToMany(fetch = FetchType.EAGER, mappedBy = "installationInfo",
targetEntity=ModuleInfo.class, cascade={CascadeType.ALL}) //targerEntity is added by Isuru
public Set<ModuleInfo> getModuleInfos() {
return this.moduleInfos;
}