How to persist parent and childs in JPA? - java

I have a table called conclusion and it has a relationship with table comments.
When i am adding conclusion and comments at the same time, Conclusion is being inserted but child getting conclusion id as null by which i'm getting violation of not null constraint.
My transaction roll backs conclusion also not inserted.
So please tell me how to insert parent and child at once.
my entities are
Conclusion Entity
#Entity
#Table(name="olm_anlys_cncln")
public class OlmAnalysisConclusion implements Serializable {
private static final long serialVersionUID = 1L;
private Long conclusionId;
private String concludedBy;
private Timestamp concludedTime;
private String conclusion;
private Timestamp discussionEndTime;
private String discussionActive;
private Timestamp discussionStartTime;
private Integer tntId;
private OlmAnalysis olmAnly;
private OlmAnalysisCategory olmAnlysCatgMstr;
private OlmAnalysisCause olmAnlysCauseMstr;
private List<OlmInvsgDiscussionComment> olmInvsgDiscnCmnts;
public OlmAnalysisConclusion() {
}
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="olm_anlys_cncln_id")
public Long getConclusionId() {
return this.conclusionId;
}
public void setConclusionId(Long conclusionId) {
this.conclusionId = conclusionId;
}
#Column(name="cncld_by")
public String getConcludedBy() {
return this.concludedBy;
}
public void setConcludedBy(String concludedBy) {
this.concludedBy = concludedBy;
}
#Column(name="cncld_time")
public Timestamp getConcludedTime() {
return this.concludedTime;
}
public void setConcludedTime(Timestamp concludedTime) {
this.concludedTime = concludedTime;
}
#Column(name="cncln")
public String getConclusion() {
return this.conclusion;
}
public void setConclusion(String conclusion) {
this.conclusion = conclusion;
}
#Column(name="discn_end_time")
public Timestamp getDiscussionEndTime() {
return this.discussionEndTime;
}
public void setDiscussionEndTime(Timestamp discussionEndTime) {
this.discussionEndTime = discussionEndTime;
}
#Column(name="discn_flag")
public String getDiscussionActive() {
return this.discussionActive;
}
public void setDiscussionActive(String discussionActive) {
this.discussionActive = discussionActive;
}
#Column(name="discn_strt_time")
public Timestamp getDiscussionStartTime() {
return this.discussionStartTime;
}
public void setDiscussionStartTime(Timestamp discussionStartTime) {
this.discussionStartTime = discussionStartTime;
}
#Column(name="tnt_id")
public Integer getTntId() {
return this.tntId;
}
public void setTntId(Integer tntId) {
this.tntId = tntId;
}
//bi-directional many-to-one association to OlmAnalysis
#ManyToOne
#JoinColumn(name="anlys_id")
public OlmAnalysis getOlmAnly() {
return this.olmAnly;
}
public void setOlmAnly(OlmAnalysis olmAnly) {
this.olmAnly = olmAnly;
}
//bi-directional many-to-one association to OlmAnalysisCategory
#ManyToOne
#JoinColumn(name="catg_id")
public OlmAnalysisCategory getOlmAnlysCatgMstr() {
return this.olmAnlysCatgMstr;
}
public void setOlmAnlysCatgMstr(OlmAnalysisCategory olmAnlysCatgMstr) {
this.olmAnlysCatgMstr = olmAnlysCatgMstr;
}
//bi-directional many-to-one association to OlmAnalysisCause
#ManyToOne
#JoinColumn(name="cause_id")
public OlmAnalysisCause getOlmAnlysCauseMstr() {
return this.olmAnlysCauseMstr;
}
public void setOlmAnlysCauseMstr(OlmAnalysisCause olmAnlysCauseMstr) {
this.olmAnlysCauseMstr = olmAnlysCauseMstr;
}
//bi-directional many-to-one association to OlmInvsgDiscussionComment
#OneToMany(fetch=FetchType.EAGER,mappedBy="olmAnlysCncln",cascade=CascadeType.ALL)
public List<OlmInvsgDiscussionComment> getOlmInvsgDiscnCmnts() {
return this.olmInvsgDiscnCmnts;
}
public void setOlmInvsgDiscnCmnts(List<OlmInvsgDiscussionComment> olmInvsgDiscnCmnts) {
this.olmInvsgDiscnCmnts = olmInvsgDiscnCmnts;
}
public OlmInvsgDiscussionComment addOlmInvsgDiscnCmnt(OlmInvsgDiscussionComment olmInvsgDiscnCmnt) {
getOlmInvsgDiscnCmnts().add(olmInvsgDiscnCmnt);
olmInvsgDiscnCmnt.setOlmAnlysCncln(this);
return olmInvsgDiscnCmnt;
}
public OlmInvsgDiscussionComment removeOlmInvsgDiscnCmnt(OlmInvsgDiscussionComment olmInvsgDiscnCmnt) {
getOlmInvsgDiscnCmnts().remove(olmInvsgDiscnCmnt);
olmInvsgDiscnCmnt.setOlmAnlysCncln(null);
return olmInvsgDiscnCmnt;
}
}
Comment Entity
#Entity
#Table(name="olm_invsg_discn_cmnt")
public class OlmInvsgDiscussionComment implements Serializable {
private static final long serialVersionUID = 1L;
private Long commentId;
private String comment;
private Timestamp commentTime;
private String commentedBy;
private Integer tenentId;
private OlmAnalysisConclusion olmAnlysCncln;
private Set<OlmInvsgCommentAttachment> olmInvsgDiscnCmntAtmnts;
public OlmInvsgDiscussionComment() {
}
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="olm_invsg_discn_cmnt_id")
public Long getCommentId() {
return this.commentId;
}
public void setCommentId(Long commentId) {
this.commentId = commentId;
}
#Column(name="cmnt")
public String getComment() {
return this.comment;
}
public void setComment(String comment) {
this.comment = comment;
}
#Column(name="cmnt_time")
public Timestamp getCommentTime() {
return this.commentTime;
}
public void setCommentTime(Timestamp commentTime) {
this.commentTime = commentTime;
}
#Column(name="cmntd_by")
public String getCommentedBy() {
return this.commentedBy;
}
public void setCommentedBy(String commentedBy) {
this.commentedBy = commentedBy;
}
#Column(name="tnt_id")
public Integer getTenentId() {
return this.tenentId;
}
public void setTenentId(Integer tenentId) {
this.tenentId = tenentId;
}
//bi-directional many-to-one association to OlmAnalysisConclusion
#ManyToOne(fetch=FetchType.EAGER, optional=false)
#JoinColumn(name="cncln_id")
public OlmAnalysisConclusion getOlmAnlysCncln() {
return this.olmAnlysCncln;
}
public void setOlmAnlysCncln(OlmAnalysisConclusion olmAnlysCncln) {
this.olmAnlysCncln = olmAnlysCncln;
}
//bi-directional many-to-one association to OlmInvsgCommentAttachment
#OneToMany(fetch=FetchType.EAGER,mappedBy="olmInvsgDiscnCmnt",cascade=CascadeType.ALL)
public Set<OlmInvsgCommentAttachment> getOlmInvsgDiscnCmntAtmnts() {
return this.olmInvsgDiscnCmntAtmnts;
}
public void setOlmInvsgDiscnCmntAtmnts(Set<OlmInvsgCommentAttachment> olmInvsgDiscnCmntAtmnts) {
this.olmInvsgDiscnCmntAtmnts = olmInvsgDiscnCmntAtmnts;
}
public OlmInvsgCommentAttachment addOlmInvsgDiscnCmntAtmnt(OlmInvsgCommentAttachment olmInvsgDiscnCmntAtmnt) {
getOlmInvsgDiscnCmntAtmnts().add(olmInvsgDiscnCmntAtmnt);
olmInvsgDiscnCmntAtmnt.setOlmInvsgDiscnCmnt(this);
return olmInvsgDiscnCmntAtmnt;
}
public OlmInvsgCommentAttachment removeOlmInvsgDiscnCmntAtmnt(OlmInvsgCommentAttachment olmInvsgDiscnCmntAtmnt) {
getOlmInvsgDiscnCmntAtmnts().remove(olmInvsgDiscnCmntAtmnt);
olmInvsgDiscnCmntAtmnt.setOlmInvsgDiscnCmnt(null);
return olmInvsgDiscnCmntAtmnt;
}
}

The most probable reason for the join column being null in your table is that the olmAnlysCncln field is null in the OlmInvsgDiscussionComment entity you're trying to persist. That's the owner side of the bidirectional association. You MUST initialize it if you want Hibernate to set something in the corresponding column. Adding the comment to the conclusion is not sufficient.
Side note: vowels are accepted, and even recommented, in property names. You should be able to pronounce a property name. olmInvsgDiscnCmntAtmnts is unpronouceable and unreadable. Use proper English names.

Related

How to use detailed SQL query on Srpingboot using #Query?

I'm having some trouble to find out how to use an specific query on Springboot
SELECT tb_excursao.fk_cliente, tb_cliente.nome, tb_cliente.documento, tb_cliente.org_emissor, tb_cliente.data_nascimento, tb_excursao.fk_viagem, tb_viagens.destino, tb_viagens.data_viagem
FROM ((tb_excursao
INNER JOIN tb_cliente ON fk_cliente = tb_cliente.id_cliente)
INNER JOIN tb_viagens ON fk_viagem = tb_viagens.id_viagem))
This works fine on MySQL, but the examples that I saw it's always something like "SELECT u FROM User u", and as a beginner I can't relate using columns from different tables using #Query.
The models are below:
Cliente.java
#Entity
#Table(name = "tb_cliente")
public class Cliente {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long idCliente;
#NotBlank
#Size(min = 3)
private String nome;
#NotNull
private String documento;
#NotNull
private String orgEmissor;
#NotBlank
#JsonFormat(pattern = "dd/MM/yyyy")
private Date dataNascimento;
#Temporal(TemporalType.TIMESTAMP)
private Date dataCadastro = new java.sql.Date(System.currentTimeMillis());
#OneToMany(mappedBy = "fkCliente")
Set<Excursao> excursao;
public long getIdCliente() {
return idCliente;
}
public void setIdCliente(long idCliente) {
this.idCliente = idCliente;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getDocumento() {
return documento;
}
public void setDocumento(String documento) {
this.documento = documento;
}
public String getOrgEmissor() {
return orgEmissor;
}
public void setOrgEmissor(String orgEmissor) {
this.orgEmissor = orgEmissor;
}
public Date getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(Date dataNascimento) {
this.dataNascimento = dataNascimento;
}
public Date getDataCadastro() {
return dataCadastro;
}
public void setDataCadastro(Date dataCadastro) {
this.dataCadastro = dataCadastro;
}
}
Viagem.java
#Entity
#Table(name = "tb_viagens")
public class Viagem {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long idViagem;
#NotBlank
private String destino;
#NotBlank
#JsonFormat(pattern = "dd/MM/yyyy")
private Date dataViagem;
#NotBlank
private int quantidadeMaxPessoas;
#OneToMany(mappedBy = "fkViagem")
private Set<Excursao> excursao;
public long getIdViagem() {
return idViagem;
}
public void setIdViagem(long idViagem) {
this.idViagem = idViagem;
}
public String getDestino() {
return destino;
}
public void setDestino(String destino) {
this.destino = destino;
}
public Date getDataViagem() {
return dataViagem;
}
public void setDataViagem(Date dataViagem) {
this.dataViagem = dataViagem;
}
public int getQuantidadeMaxPessoas() {
return quantidadeMaxPessoas;
}
public void setQuantidadeMaxPessoas(int quantidadeMaxPessoas) {
this.quantidadeMaxPessoas = quantidadeMaxPessoas;
}
}
ExcursaoEmbeddable.java
#Embeddable
public class ExcursaoEmb implements Serializable {
#Column(name = "fkCliente")
private Long fkCliente;
#Column(name = "fkViagem")
private Long fkViagem;
public Long getFkCliente() {
return this.fkCliente;
}
public void setFkCliente(Long fkCliente) {
this.fkCliente = fkCliente;
}
public Long getFkViagem() {
return this.fkViagem;
}
public void setFkViagem(Long fkViagem) {
this.fkViagem = fkViagem;
}
}
Excursao.java This is the table that the query in the beginning of the post goes
#Entity
#Table(name = "tb_excursao")
public class Excursao {
#EmbeddedId
ExcursaoEmb idExcursao;
#ManyToOne
#JoinColumn(name = "id_cliente")
private Cliente fkCliente;
#ManyToOne
#JoinColumn(name = "id_viagem")
private Viagem fkViagem;
#NotNull
private boolean primeiraParcela;
#NotNull
private boolean segundaParcela;
private boolean terceiraParcela;
public ExcursaoEmb getIdExcursao() {
return this.idExcursao;
}
public void setIdExcursao(ExcursaoEmb idExcursao) {
this.idExcursao = idExcursao;
}
public Cliente getFkCliente() {
return this.fkCliente;
}
public void setFkCliente(Cliente fkCliente) {
this.fkCliente = fkCliente;
}
public Viagem getFkViagem() {
return this.fkViagem;
}
public void setFkViagem(Viagem fkViagem) {
this.fkViagem = fkViagem;
}
public boolean isPrimeiraParcela() {
return this.primeiraParcela;
}
public boolean getPrimeiraParcela() {
return this.primeiraParcela;
}
public void setPrimeiraParcela(boolean primeiraParcela) {
this.primeiraParcela = primeiraParcela;
}
public boolean isSegundaParcela() {
return this.segundaParcela;
}
public boolean getSegundaParcela() {
return this.segundaParcela;
}
public void setSegundaParcela(boolean segundaParcela) {
this.segundaParcela = segundaParcela;
}
public boolean isTerceiraParcela() {
return this.terceiraParcela;
}
public boolean getTerceiraParcela() {
return this.terceiraParcela;
}
public void setTerceiraParcela(boolean terceiraParcela) {
this.terceiraParcela = terceiraParcela;
}
}

I have multiple OneToMany mappings in a entity. Hibernate loads the first one even without me requesting that object. Is that the expected behaviour?

MedicalEntity:
#Entity
#Table(name="t_med_area")
public class MedicalEntity {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="med_area_id")
private Integer med_area_id;
#Column(name="med_area_cd")
private String area_code;
#Column(name="area_nm")
private String area_description;
#OneToMany(fetch = FetchType.LAZY,mappedBy="medical_area_id")
private List<ProviderEntity> resources;
#OneToMany(fetch = FetchType.LAZY,mappedBy="medAreaId")
private List<FacilityEntity> facility;
public List<ProviderEntity> getResources() {
return resources;
}
public void setResources(List<ProviderEntity> resources) {
this.resources = resources;
}
public List<FacilityEntity> getFacility() {
return facility;
}
public void setFacility(List<FacilityEntity> facility) {
this.facility = facility;
}
public Integer getMed_area_id() {
return med_area_id;
}
public void setMed_area_id(Integer med_area_id) {
this.med_area_id = med_area_id;
}
public String getArea_code() {
return area_code;
}
public void setArea_code(String area_code) {
this.area_code = area_code;
}
public String getArea_description() {
return area_description;
}
public void setArea_description(String area_description) {
this.area_description = area_description;
}
FacilityEntity:
#Entity
#Table(name="t_facility")
public class FacilityEntity implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private Integer id;
#Column(name="facility_id")
private int facilityId;
#Column(name="facility_nm")
private String facilityName;
#Column(name="facility_code")
private String facilityCode;
#OneToMany(fetch = FetchType.LAZY,mappedBy="facility_id")
private List<ProviderEntity> resources;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="med_area_id")
private MedicalEntity medAreaId;
#Column(name="insert_dt")
private Date insertDt;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public int getFacilityId() {
return facilityId;
}
public void setFacilityId(int facilityId) {
this.facilityId = facilityId;
}
public String getFacilityName() {
return facilityName;
}
public void setFacilityName(String facilityName) {
this.facilityName = facilityName;
}
public String getFacilityCode() {
return facilityCode;
}
public void setFacilityCode(String facilityCode) {
this.facilityCode = facilityCode;
}
public List<ProviderEntity> getResources() {
return resources;
}
public void setResources(List<ProviderEntity> resources) {
this.resources = resources;
}
public MedicalEntity getMedAreaId() {
return medAreaId;
}
public void setMedAreaId(MedicalEntity medAreaId) {
this.medAreaId = medAreaId;
}
public Date getInsertDt() {
return insertDt;
}
public void setInsertDt(Date insertDt) {
this.insertDt = insertDt;
}
public FacilityEntity(Integer id, String facility_name, String facility_code) {
super();
this.id = id;
this.facilityName = facility_name;
this.facilityCode = facility_code;
}
public FacilityEntity() {
super();
}
}
Provider Entity:
#Entity
#Table(name="t_provider")
public class ProviderEntity implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="provider_id")
private Integer provider_id;
#Column(name="resource_cd")
private String resource_code;
#Column(name="first_nm")
private String first_name;
#Column(name="last_nm")
private String last_name;
#Column(name="middle_nm")
private String middle_name;
#Column(name="title_nm")
private String title;
#Column(name="department_nm")
private String department_name;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="home_med_area_id")
private MedicalEntity medical_area_id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="home_facility_id")
private FacilityEntity facility_id;
public Integer getProvider_id() {
return provider_id;
}
public void setProvider_id(Integer provider_id) {
this.provider_id = provider_id;
}
public String getResource_code() {
return resource_code;
}
public void setResource_code(String resource_code) {
this.resource_code = resource_code;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getMiddle_name() {
return middle_name;
}
public void setMiddle_name(String middle_name) {
this.middle_name = middle_name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDepartment_name() {
return department_name;
}
public void setDepartment_name(String department_name) {
this.department_name = department_name;
}
public MedicalEntity getMedical_area_id() {
return medical_area_id;
}
public void setMedical_area_id(MedicalEntity medical_area_id) {
this.medical_area_id = medical_area_id;
}
public FacilityEntity getFacility_id() {
return facility_id;
}
public void setFacility_id(FacilityEntity facility_id) {
this.facility_id = facility_id;
}
public ProviderEntity() {
super();
}
}
Service Layer:
List<MedicalEntity> result=medicalAreaRepository.findAll();
//transforming entity into DTO and setting properties based on UI requirements
for(MedicalEntity medicalEntity:result)
{
MedicalDTO medicalDTO=new MedicalDTO();
medicalDTO.setArea_code(medicalEntity.getArea_code());
medicalDTO.setArea_description(medicalEntity.getArea_description());
medicalDTO.setId(medicalEntity.getMed_area_id());
//System.out.println(medicalEntity.getResources());
medicalResponse.addElementsToList(medicalDTO);
}
When I call hover over my List result, it automatically fires the query to load the facilities.
Logs which are generated:
Hibernate: select medicalent0_.med_area_id as med_area1_1_, medicalent0_.med_area_cd as med_area2_1_, medicalent0_.area_nm as area_nm3_1_ from t_med_area medicalent0_
2020-02-11 15:26:01.377 TRACE 39096 --- [nio-8080-exec-2] o.s.t.i.TransactionInterceptor : Completing transaction for [org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll]
2020-02-11 15:26:01.383 TRACE 39096 --- [nio-8080-exec-2] .s.t.s.TransactionSynchronizationManager : Removed value [org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$DefaultCrudMethodMetadata#2930e0de] for key [public abstract java.util.List org.springframework.data.jpa.repository.JpaRepository.findAll()] from thread [http-nio-8080-exec-2]
Hibernate: select z0_.med_area_id as med_area6_0_0_, z0_.id as id1_0_0_, z0_.id as id1_0_1_, z0_.facility_code as facility2_0_1_, z0_.facility_id as facility3_0_1_, z0_.facility_nm as facility4_0_1_, z0_.insert_dt as insert_d5_0_1_, z0_.med_area_id as med_area6_0_1_ from t_facility z0_ where z0_.med_area_id=?
Hibernate: select z0_.med_area_id as med_area6_0_0_, z0_.id as id1_0_0_, z0_.id as id1_0_1_, z0_.facility_code as facility2_0_1_, z0_.facility_id as facility3_0_1_, z0_.facility_nm as facility4_0_1_, z0_.insert_dt as insert_d5_0_1_, z0_.med_area_id as med_area6_0_1_ from t_facility z0_ where z0_.med_area_id=?
Hibernate: select z0_.med_area_id as med_area6_0_0_, z0_.id as id1_0_0_, z0_.id as id1_0_1_, z0_.facility_code as facility2_0_1_, z0_.facility_id as facility3_0_1_, z0_.facility_nm as facility4_0_1_, z0_.insert_dt as insert_d5_0_1_, z0_.med_area_id as med_area6_0_1_ from t_facility z0_ where z0_.med_area_id=?.
My question is: Why is it fetching the details of FacilityEntity?I am not explicitly making any calls to get the properties of FacilityEntity.
When you say 'hover' do you mean while debugging? If you inspect any of the lazy elements its akin to accessing them, so hibernate will attempt to lazy load the entity.

unique constraint Exception (SQLIntegrityConstraintViolationException)

I am trying to insert data in oracle DB using spring JPA repositories
I have a hash map which contains all the values which needs to be populated into DB,I am Iterating each value and setting into my Entity class
Basically I have a table which has a composite primary key(NotifiedToId).when I am setting the values ints throwing constraint violation exception.In my logs it is printing all correct values but its not getting inserted,
My Entity class:
#Embeddable
public class TbBamiNotifUserLogPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
#Column(name="NOTIF_REF_NO")
private String notifRefNo;
#Column(name="NOTIFIED_TO_ID")
private String notifiedToId;
public TbBamiNotifUserLogPK() {
}
public String getNotifRefNo() {
return this.notifRefNo;
}
public void setNotifRefNo(String notifRefNo) {
this.notifRefNo = notifRefNo;
}
public String getNotifiedToId() {
return this.notifiedToId;
}
public void setNotifiedToId(String notifiedToId) {
this.notifiedToId = notifiedToId;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof TbBamiNotifUserLogPK)) {
return false;
}
TbBamiNotifUserLogPK castOther = (TbBamiNotifUserLogPK)other;
return
this.notifRefNo.equals(castOther.notifRefNo)
&& this.notifiedToId.equals(castOther.notifiedToId);
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + this.notifRefNo.hashCode();
hash = hash * prime + this.notifiedToId.hashCode();
return hash;
}
}
import java.io.Serializable;
import javax.persistence.*;
#Entity
#Table(name="TB_BAMI_NOTIF_USER_LOG")
#NamedQuery(name="TbBamiNotifUserLog.findAll", query="SELECT t FROM TbBamiNotifUserLog t")
public class TbBamiNotifUserLog implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private TbBamiNotifUserLogPK id;
#Column(name="NOTIF_CAT")
private String notifCat;
#Column(name="NOTIFIED_TO_NAME")
private String notifiedToName;
#Column(name="NOTIFIED_TO_ROLE")
private String notifiedToRole;
public TbBamiNotifUserLog() {
}
public TbBamiNotifUserLogPK getId() {
return this.id;
}
public void setId(TbBamiNotifUserLogPK id) {
this.id = id;
}
public String getNotifCat() {
return this.notifCat;
}
public void setNotifCat(String notifCat) {
this.notifCat = notifCat;
}
public String getNotifiedToName() {
return this.notifiedToName;
}
public void setNotifiedToName(String notifiedToName) {
this.notifiedToName = notifiedToName;
}
public String getNotifiedToRole() {
return this.notifiedToRole;
}
public void setNotifiedToRole(String notifiedToRole) {
this.notifiedToRole = notifiedToRole;
}
}
#Entity
#Table(name="TB_BAMI_NOTIFICATION_LOG")
#NamedQuery(name="TbBamiNotificationLog.findAll", query="SELECT t FROM TbBamiNotificationLog t")
public class TbBamiNotificationLog implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="NOTIF_REF_NO")
private String notifRefNo;
#Column(name="\"ACTION\"")
private String action;
#Column(name="NOTIF_CONTENT")
private String notifContent;
#Column(name="NOTIF_TYPE")
private String notifType;
#Column(name="NOTIFIED_DATE_TIME")
private Timestamp notifiedDateTime;
private String refno;
#Column(name="\"VERSION\"")
private BigDecimal version;
public TbBamiNotificationLog() {
}
public String getNotifRefNo() {
return this.notifRefNo;
}
public void setNotifRefNo(String notifRefNo) {
this.notifRefNo = notifRefNo;
}
public String getAction() {
return this.action;
}
public void setAction(String action) {
this.action = action;
}
public String getNotifContent() {
return this.notifContent;
}
public void setNotifContent(String notifContent) {
this.notifContent = notifContent;
}
public String getNotifType() {
return this.notifType;
}
public void setNotifType(String notifType) {
this.notifType = notifType;
}
public Timestamp getNotifiedDateTime() {
return this.notifiedDateTime;
}
public void setNotifiedDateTime(Timestamp notifiedDateTime) {
this.notifiedDateTime = notifiedDateTime;
}
public String getRefno() {
return this.refno;
}
public void setRefno(String refno) {
this.refno = refno;
}
public BigDecimal getVersion() {
return this.version;
}
public void setVersion(BigDecimal version) {
this.version = version;
}
}
Business Logic:
for (Entry<String, PushNotificationDetails> entry : finalTemplate.entrySet()){
try{
notificationlog.setNotifRefNo("121323");
notificationlog.setRefno(refNum);
notificationlog.setVersion(new BigDecimal(1));
notificationlog.setAction(action);
LOGGER.debug("TEMPLATE TYPE"+entry.getValue().getTemplate_type());
LOGGER.debug("TEMPLATE"+entry.getValue().getTemplate());
notificationlog.setNotifType(entry.getValue().getTemplate_type());
notificationlog.setNotifContent(entry.getValue().getTemplate());
notificationlog.setNotifiedDateTime(notifiedDateTime);
tbBamiNotifyLogRepository.save(notificationlog);
LOGGER.debug("inside if block ::: ");
LOGGER.debug("USERID is: "+entry.getValue().getUserID());
LOGGER.debug("NOTIFCAT is: "+entry.getValue().getNotif_cat());
LOGGER.debug("NOTIFUSER is: "+entry.getValue().getUserName());
LOGGER.debug("NOTIFROLE is: "+entry.getKey());
tbBamiNotifUserLogPK.setNotifiedToId(entry.getValue().getUserID());
tbBamiNotifUserLogPK.setNotifRefNo("121323");
tbBamiNotifUserLog.setId(tbBamiNotifUserLogPK);
LOGGER.debug("GET is: "+tbBamiNotifUserLog.getId().getNotifiedToId());
tbBamiNotifUserLog.setNotifCat(entry.getValue().getNotif_cat());
tbBamiNotifUserLog.setNotifiedToName(entry.getValue().getUserName());
tbBamiNotifUserLog.setNotifiedToRole(entry.getKey());
tbBamiNotifyUserLogRepository.save(tbBamiNotifUserLog);
}
Try to add notificationlog = new TbBamiNotificationLog() in the beginning of your saving for. It could be possible when you try to save the second row but the instance is the same (with id provided during the first save).

Spring Boot Autowiring Problems: Not An Managed Type

I have a repository class:
public interface WorkOrderRepository extends JpaRepository<WorkOrderDTO, Integer> {
#Query(value = "SELECT * FROM (SELECT * FROM workorder) Sub1 INNER JOIN (SELECT wo_number, GROUP_CONCAT(service_type SEPARATOR ', ') AS 'service_types' FROM service_type GROUP BY wo_number) Sub2 ON Sub1.wo_number=Sub2.wo_number WHERE fleet_company_id=?1 AND (order_status='On-Bidding' OR order_status='Draft')")
Collection<WorkOrderDTO> findWorkOrdersByFleet(Long fleetCompanyID);
#Query(value = "SELECT * FROM workorder WHERE fleet_company_id=?1")
Collection<WorkOrderDTO> findWorkOrdersByFleet1(Long fleetCompanyID);
}
And an entity class:
#Entity
#Table(name="workorder")
public class WorkOrder implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="wo_number")
private Long woNumber;
#ManyToOne(optional=false, cascade=CascadeType.ALL)
#JoinColumn(name = "vehicle_id")
private Vehicle vehicle;
#ManyToOne(optional=false, cascade=CascadeType.ALL)
#JoinColumn(name = "fleet_company_id")
private FleetCompany fleetCompany;
#Column(name="order_title")
private String orderTitle;
#Column(name="order_date")
private String orderDate;
#Column(name="order_time")
private String orderTime;
#Column(name="order_status")
private String orderStatus;
#Column(name="ref_number")
private String refNumber;
#Column(name="proposals")
private int proposals;
#Transient
private String serviceTypes;
public WorkOrder() {
super();
}
public Long getWoNumber() {
return woNumber;
}
public void setWoNumber(Long woNumber) {
this.woNumber = woNumber;
}
public String getOrderTitle() {
return orderTitle;
}
public void setOrderTitle(String orderTitle) {
this.orderTitle = orderTitle;
}
public String getOrderDate() {
return orderDate;
}
public void setOrderDate(String orderDate) {
this.orderDate = orderDate;
}
public String getOrderTime() {
return orderTime;
}
public void setOrderTime(String orderTime) {
this.orderTime = orderTime;
}
public String getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
public String getRefNumber() {
return refNumber;
}
public void setRefNumber(String refNumber) {
this.refNumber = refNumber;
}
public int getProposals() {
return proposals;
}
public void setProposals(int proposals) {
this.proposals = proposals;
}
public Vehicle getVehicle() {
return vehicle;
}
public void setVehicle(Vehicle vehicle) {
this.vehicle = vehicle;
}
public FleetCompany getFleetCompany() {
return fleetCompany;
}
public void setFleetCompany(FleetCompany fleetCompany) {
this.fleetCompany = fleetCompany;
}
public String getServiceTypes() {
return serviceTypes;
}
public void setServiceTypes(String serviceTypes) {
this.serviceTypes = serviceTypes;
}
}
and I have a pojo that extends the entity class:
public class WorkOrderDTO extends WorkOrder {
private String service_types;
public WorkOrderDTO() {
super();
}
public WorkOrderDTO(String service_types) {
this.service_types = service_types;
}
public String getService_types() {
return service_types;
}
public void setService_types(String service_types) {
this.service_types = service_types;
}
}
I want to pass the POJO WorkOrderDTO to the JpaRepository instead of the entity for it to map column service_types which is not part of the entity class. But I have autowiring problems when I set WorkOrderDTO instead ofWorkOrder. Maybe, it is some annotations problem. I didn't put any annotations to the POJO.
You could use the "new" Operator. You must create a constructor in WorkOrderDTO with the values you need, e.g.
public WorkOrderDTO(String serviceTypes) {
this.service_types = serviceTypes;
}
then you can use it like that in a jpql - query:
#Query(value = "SELECT new your.package.WorkorderDTO(w.<select servicetypes somehow>) FROM workorder w WHERE fleet_company_id=?1")
However, I find your first query confusing, I think it is supposed to be a native query... There you can't use the "new" operator.
Maybe it is possible for you to map the ServiceType like Vehicle or FleetCompany as a List? Then you could concatenate just the values in the List for your DTO.
EDIT: You could use #OneToMany to map a List, as it is probably in your Vehicle class for WorkOrder, just to clarify my previous paragraph.

com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError)

I'm trying implement a rest service. I have created my entitys and daos, and when use this everthyng works fine.
But when I trye expose the information in rest json, the infinite recursion error occur.
I have read many topic about this error, but not is so clear for me.
I'm have tried so many alternatives that is hard talk about each.
When I debug my code, I see that the data from dao is correctly, the problem occur when I trie use json. Whe I use jsf page works fine.
I have tried use Gson and return String in my rest method, but stackoverflow error occur to.
Bellow I post my implememtation (all), because a dont have idea about the problem.
I using wildfly server...
Thanks in advance
Model's
#Entity
#Table(name="usertable")
#NamedQuery(name="UserModel.findAll", query="SELECT u FROM UserModel u")
#XmlRootElement
public class UserModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(unique=true, nullable=false)
private String USId;
#Temporal(TemporalType.DATE)
#Column(nullable=false)
private Date userNascimento;
#Column(nullable=false, length=45)
private String USMail;
#Column(nullable=false, length=150)
private String USName;
#Column(nullable=false, length=45)
private String USNick;
#Column(nullable=false, length=45)
private String USPassword;
//bi-directional many-to-one association to UserAddressModel
#OneToMany(fetch = FetchType.EAGER, mappedBy="usertable")
private List<UserAddressModel> listAddressModel;
//bi-directional many-to-one association to UserFoneModel
#OneToMany(fetch = FetchType.EAGER, mappedBy="usertable")
private List<UserFoneModel> listFoneModel;
public UserModel() {
}
public String getUSId() {
return this.USId;
}
public void setUSId(String USId) {
this.USId = USId;
}
public Date getUserNascimento() {
return this.userNascimento;
}
public void setUserNascimento(Date userNascimento) {
this.userNascimento = userNascimento;
}
public String getUSMail() {
return this.USMail;
}
public void setUSMail(String USMail) {
this.USMail = USMail;
}
public String getUSName() {
return this.USName;
}
public void setUSName(String USName) {
this.USName = USName;
}
public String getUSNick() {
return this.USNick;
}
public void setUSNick(String USNick) {
this.USNick = USNick;
}
public String getUSPassword() {
return this.USPassword;
}
public void setUSPassword(String USPassword) {
this.USPassword = USPassword;
}
public List<UserAddressModel> getUseraddresstables() {
return this.listAddressModel;
}
public void setUseraddresstables(List<UserAddressModel> useraddresstables) {
this.listAddressModel = useraddresstables;
}
public UserAddressModel addUseraddresstable(UserAddressModel useraddresstable) {
getUseraddresstables().add(useraddresstable);
useraddresstable.setUsertable(this);
return useraddresstable;
}
public UserAddressModel removeUseraddresstable(UserAddressModel useraddresstable) {
getUseraddresstables().remove(useraddresstable);
useraddresstable.setUsertable(null);
return useraddresstable;
}
public List<UserFoneModel> getUserfonetables() {
return this.listFoneModel;
}
public void setUserfonetables(List<UserFoneModel> userfonetables) {
this.listFoneModel = userfonetables;
}
public UserFoneModel addUserfonetable(UserFoneModel userfonetable) {
getUserfonetables().add(userfonetable);
userfonetable.setUsertable(this);
return userfonetable;
}
public UserFoneModel removeUserfonetable(UserFoneModel userfonetable) {
getUserfonetables().remove(userfonetable);
userfonetable.setUsertable(null);
return userfonetable;
}
}
#Entity
#Table(name="userfonetable")
#NamedQuery(name="UserFoneModel.findAll", query="SELECT u FROM UserFoneModel u")
public class UserFoneModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(unique=true, nullable=false)
private String UFId;
#Column(nullable=false)
private short UFDdd;
#Column(nullable=false)
private int UFFone;
//bi-directional many-to-one association to UserModel
#ManyToOne
#JoinColumn(name="UFUserID", nullable=false)
private UserModel usertable;
//bi-directional many-to-one association to OperadorasModel
#ManyToOne
#JoinColumn(name="UFOperadoraID", nullable=false)
private OperadorasModel operadorastable;
//bi-directional many-to-one association to TiposFoneModel
#ManyToOne
#JoinColumn(name="UFTipoTelefone", nullable=false)
private TiposFoneModel tbTipostelefone;
public UserFoneModel() {
}
public String getUFId() {
return this.UFId;
}
public void setUFId(String UFId) {
this.UFId = UFId;
}
public short getUFDdd() {
return this.UFDdd;
}
public void setUFDdd(short UFDdd) {
this.UFDdd = UFDdd;
}
public int getUFFone() {
return this.UFFone;
}
public void setUFFone(int UFFone) {
this.UFFone = UFFone;
}
public UserModel getUsertable() {
return this.usertable;
}
public void setUsertable(UserModel usertable) {
this.usertable = usertable;
}
public OperadorasModel getOperadorastable() {
return this.operadorastable;
}
public void setOperadorastable(OperadorasModel operadorastable) {
this.operadorastable = operadorastable;
}
public TiposFoneModel getTbTipostelefone() {
return this.tbTipostelefone;
}
public void setTbTipostelefone(TiposFoneModel tbTipostelefone) {
this.tbTipostelefone = tbTipostelefone;
}
}
#Entity
#Table(name="useraddresstable")
#NamedQuery(name="UserAddressModel.findAll", query="SELECT u FROM UserAddressModel u")
public class UserAddressModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(unique=true, nullable=false)
private String UAId;
#Column(nullable=false, length=100)
private String UABairro;
#Column(nullable=false, length=100)
private String UACidade;
#Column(length=45)
private String UAComplemento;
#Column(nullable=false, length=2)
private String UAEstado;
#Column(nullable=false)
private int UANumero;
#Column(length=100)
private String UARua;
//bi-directional many-to-one association to UserModel
#ManyToOne
#JoinColumn(name="UAUserID", nullable=false)
private UserModel usertable;
public UserAddressModel() {
}
public String getUAId() {
return this.UAId;
}
public void setUAId(String UAId) {
this.UAId = UAId;
}
public String getUABairro() {
return this.UABairro;
}
public void setUABairro(String UABairro) {
this.UABairro = UABairro;
}
public String getUACidade() {
return this.UACidade;
}
public void setUACidade(String UACidade) {
this.UACidade = UACidade;
}
public String getUAComplemento() {
return this.UAComplemento;
}
public void setUAComplemento(String UAComplemento) {
this.UAComplemento = UAComplemento;
}
public String getUAEstado() {
return this.UAEstado;
}
public void setUAEstado(String UAEstado) {
this.UAEstado = UAEstado;
}
public int getUANumero() {
return this.UANumero;
}
public void setUANumero(int UANumero) {
this.UANumero = UANumero;
}
public String getUARua() {
return this.UARua;
}
public void setUARua(String UARua) {
this.UARua = UARua;
}
public UserModel getUsertable() {
return this.usertable;
}
public void setUsertable(UserModel usertable) {
this.usertable = usertable;
}
}
#Entity
#Table(name="tb_tipostelefone")
#NamedQuery(name="TiposFoneModel.findAll", query="SELECT t FROM TiposFoneModel t")
public class TiposFoneModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(unique=true, nullable=false)
private short TFId;
#Column(nullable=false, length=45)
private String TFDescricao;
//bi-directional many-to-one association to UserFoneModel
#OneToMany(fetch = FetchType.EAGER, mappedBy="tbTipostelefone")
private List<UserFoneModel> listFoneModel;
public TiposFoneModel() {
}
public short getTFId() {
return this.TFId;
}
public void setTFId(short TFId) {
this.TFId = TFId;
}
public String getTFDescricao() {
return this.TFDescricao;
}
public void setTFDescricao(String TFDescricao) {
this.TFDescricao = TFDescricao;
}
public List<UserFoneModel> getUserfonetables() {
return this.listFoneModel;
}
public void setUserfonetables(List<UserFoneModel> userfonetables) {
this.listFoneModel = userfonetables;
}
public UserFoneModel addUserfonetable(UserFoneModel userfonetable) {
getUserfonetables().add(userfonetable);
userfonetable.setTbTipostelefone(this);
return userfonetable;
}
public UserFoneModel removeUserfonetable(UserFoneModel userfonetable) {
getUserfonetables().remove(userfonetable);
userfonetable.setTbTipostelefone(null);
return userfonetable;
}
}
#Entity
#Table(name="operadorastable")
#NamedQuery(name="OperadorasModel.findAll", query="SELECT o FROM OperadorasModel o")
public class OperadorasModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(unique=true, nullable=false)
private short OPCodigo;
#Column(nullable=false, length=100)
private String opNome;
//bi-directional many-to-one association to UserFoneModel
#OneToMany(fetch = FetchType.EAGER, mappedBy="operadorastable")
private List<UserFoneModel> listFoneModel;
public OperadorasModel() {
}
public short getOPCodigo() {
return this.OPCodigo;
}
public void setOPCodigo(short OPCodigo) {
this.OPCodigo = OPCodigo;
}
public String getOpNome() {
return this.opNome;
}
public void setOpNome(String opNome) {
this.opNome = opNome;
}
public List<UserFoneModel> getUserfonetables() {
return this.listFoneModel;
}
public void setUserfonetables(List<UserFoneModel> userfonetables) {
this.listFoneModel = userfonetables;
}
public UserFoneModel addUserfonetable(UserFoneModel userfonetable) {
getUserfonetables().add(userfonetable);
userfonetable.setOperadorastable(this);
return userfonetable;
}
public UserFoneModel removeUserfonetable(UserFoneModel userfonetable) {
getUserfonetables().remove(userfonetable);
userfonetable.setOperadorastable(null);
return userfonetable;
}
}
DAO
#Stateless
#LocalBean
public class UserDao {
/**
* Default constructor.
*/
#PersistenceContext
EntityManager em;
public UserDao() {
// TODO Auto-generated constructor stub
}
public List<UserModel> listAll()
{
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<UserModel> cq = cb.createQuery(UserModel.class);
Root<UserModel> rootEntry = cq.from(UserModel.class);
CriteriaQuery<UserModel> all = cq.select(rootEntry);
TypedQuery<UserModel> allQuery = em.createQuery(all);
List<UserModel> listU = allQuery.getResultList();
return listU;
/*
Query query = em.createQuery("SELECT u FROM UserModel u");
return query.getResultList();
*/
}
}
My Rest
import java.util.List;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import br.com.avera.dao.UserDao;
import br.com.avera.model.UserAddressModel;
import br.com.avera.model.UserFoneModel;
import br.com.avera.model.UserModel;
#Path("/users")
public class UserRest {
#Inject
UserDao userDao;
#GET
#Produces(MediaType.APPLICATION_JSON)
public UserModel getUser()
{
List<UserModel> userModelList = userDao.listAll();
UserModel userModel = userModelList.get(0);
List<UserFoneModel> lFone = userModel.getUserfonetables();
for (UserFoneModel userFoneModel : lFone) {
System.out.println(userFoneModel.getUFDdd());
System.out.println(userFoneModel.getUFFone());
}
System.out.println("OOOOOO");
List<UserAddressModel> lAddressModels = userModel.getUseraddresstables();
for (UserAddressModel userAddressModel : lAddressModels) {
System.out.println(userAddressModel.getUACidade());
System.out.println(userAddressModel.getUAEstado());
}
return userModel;
}
}

Categories

Resources