I very confused on how to save data in the database. I'll take the data from a table and then save.
A figure of my relationship is below
How i can save a list of Layoutsos into Ordemservico?
And here is my my class.
public class Ordemservico implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idordemservico")
private Integer idordemservico;
#Column(name = "identificadoros")
private Integer identificadoros;
#Column(name = "mes")
private Integer mes;
#Column(name = "ano")
private Integer ano;
#Column(name = "assunto")
private String assunto;
#Basic(optional = false)
#Column(name = "publicitario")
private String publicitario;
#Basic(optional = false)
#Column(name = "layoutos")
private String layoutos;
#Basic(optional = false)
#Column(name = "dataincio")
#Temporal(TemporalType.DATE)
private Date dataincio;
#Column(name = "datafim")
#Temporal(TemporalType.DATE)
private Date datafim;
#Column(name = "dataevento")
#Temporal(TemporalType.DATE)
private Date dataevento;
#Column(name = "producao")
private String producao;
#Lob
#Column(name = "discricao")
private String discricao;
#Column(name = "responsavelos")
private String responsavelos;
#Column(name = "materiajornal")
private String materiajornal;
#ManyToMany(mappedBy = "ordemservicoList")
private List<Ordemproducao> ordemproducaoList;
#ManyToMany(mappedBy = "ordemservicoList")
private List<Layoutsos> layoutsosList;
#JoinTable(name = "ordemservico_has_usuario", joinColumns = {
#JoinColumn(name = "ordemservico_idordemservico", referencedColumnName = ` ` "idordemservico")}, inverseJoinColumns = {
#JoinColumn(name = "usuario_idusuario", referencedColumnName = ` ` ` ` ` ` ` ` "idusuario")})
#ManyToMany
private List<Usuario> usuarioList;
#JoinColumn(name = "secretaria_idsecretaria", referencedColumnName = ` ` ` ` ` ` "idsecretaria")
#ManyToOne(optional = false)
private Secretaria secretariaIdsecretaria;
#OneToMany(cascade = CascadeType.ALL, mappedBy = ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` `"ordemservicoIdordemservico")
private List<Materiajornal> materiajornalList;
public Ordemservico() {
}
public Ordemservico(Integer idordemservico) {
this.idordemservico = idordemservico;
}
public Ordemservico(Integer idordemservico, String publicitario, String ` ` layoutos, Date dataincio) {
this.idordemservico = idordemservico;
this.publicitario = publicitario;
this.layoutos = layoutos;
this.dataincio = dataincio;
}
public Integer getIdordemservico() {
return idordemservico;
}
public void setIdordemservico(Integer idordemservico) {
this.idordemservico = idordemservico;
}
public Integer getIdentificadoros() {
return identificadoros;
}
public void setIdentificadoros(Integer identificadoros) {
this.identificadoros = identificadoros;
}
public Integer getMes() {
return mes;
}
public void setMes(Integer mes) {
this.mes = mes;
}
public Integer getAno() {
return ano;
}
public void setAno(Integer ano) {
this.ano = ano;
}
public String getAssunto() {
return assunto;
}
public void setAssunto(String assunto) {
this.assunto = assunto;
}
public String getPublicitario() {
return publicitario;
}
public void setPublicitario(String publicitario) {
this.publicitario = publicitario;
}
public String getLayoutos() {
return layoutos;
}
public void setLayoutos(String layoutos) {
this.layoutos = layoutos;
}
public Date getDataincio() {
return dataincio;
}
public void setDataincio(Date dataincio) {
this.dataincio = dataincio;
}
public Date getDatafim() {
return datafim;
}
public void setDatafim(Date datafim) {
this.datafim = datafim;
}
public Date getDataevento() {
return dataevento;
}
public void setDataevento(Date dataevento) {
this.dataevento = dataevento;
}
public String getProducao() {
return producao;
}
public void setProducao(String producao) {
this.producao = producao;
}
public String getDiscricao() {
return discricao;
}
public void setDiscricao(String discricao) {
this.discricao = discricao;
}
public String getResponsavelos() {
return responsavelos;
}
public void setResponsavelos(String responsavelos) {
this.responsavelos = responsavelos;
}
public String getMateriajornal() {
return materiajornal;
}
public void setMateriajornal(String materiajornal) {
this.materiajornal = materiajornal;
}
#XmlTransient
public List<Ordemproducao> getOrdemproducaoList() {
return ordemproducaoList;
}
public void setOrdemproducaoList(List<Ordemproducao> ordemproducaoList) {
this.ordemproducaoList = ordemproducaoList;
}
#XmlTransient
public List<Layoutsos> getLayoutsosList() {
return layoutsosList;
}
public void setLayoutsosList(List<Layoutsos> layoutsosList) {
this.layoutsosList = layoutsosList;
}
#XmlTransient
public List<Usuario> getUsuarioList() {
return usuarioList;
}
public void setUsuarioList(List<Usuario> usuarioList) {
this.usuarioList = usuarioList;
}
public Secretaria getSecretariaIdsecretaria() {
return secretariaIdsecretaria;
}
public void setSecretariaIdsecretaria(Secretaria secretariaIdsecretaria) {
this.secretariaIdsecretaria = secretariaIdsecretaria;
}
#XmlTransient
public List<Materiajornal> getMateriajornalList() {
return materiajornalList;
}
public void setMateriajornalList(List<Materiajornal> materiajornalList) {
this.materiajornalList = materiajornalList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idordemservico != null ? idordemservico.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
if (!(object instanceof Ordemservico)) {
return false;
}
Ordemservico other = (Ordemservico) object;
if ((this.idordemservico == null && other.idordemservico != null) || ` ` ` ` (this.idordemservico != null && ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` `enter code here`!this.idordemservico.equals(other.idordemservico))) {
return false;
}
return true;
}
#Override
public String toString() {
return assunto ;
}
}
Code of the other entity
But how do I grab the list of items that I select from Jtable and save. That table has all the Layouts, and now I want to save some layouts into the ordemserviço
public class Layoutsos implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idlayoutsos")
private Integer idlayoutsos;
#Column(name = "nome")
private String nome;
#Column(name = "medidas")
private String medidas;
#JoinTable(name = "ordemservico_has_layoutsos", joinColumns = {
#JoinColumn(name = "layoutsos_idlayoutsos", referencedColumnName = "idlayoutsos")}, inverseJoinColumns = {
#JoinColumn(name = "ordemservico_idordemservico", referencedColumnName = "idordemservico")})
#ManyToMany
private List<Ordemservico> ordemservicoList;
public Layoutsos() {
}
public Layoutsos(Integer idlayoutsos) {
this.idlayoutsos = idlayoutsos;
}
public Integer getIdlayoutsos() {
return idlayoutsos;
}
public void setIdlayoutsos(Integer idlayoutsos) {
this.idlayoutsos = idlayoutsos;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getMedidas() {
return medidas;
}
public void setMedidas(String medidas) {
this.medidas = medidas;
}
#XmlTransient
public List<Ordemservico> getOrdemservicoList() {
return ordemservicoList;
}
public void setOrdemservicoList(List<Ordemservico> ordemservicoList) {
this.ordemservicoList = ordemservicoList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idlayoutsos != null ? idlayoutsos.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 Layoutsos)) {
return false;
}
Layoutsos other = (Layoutsos) object;
if ((this.idlayoutsos == null && other.idlayoutsos != null) || (this.idlayoutsos != null && !this.idlayoutsos.equals(other.idlayoutsos))) {
return false;
}
return true;
}
#Override
public String toString() {
return "br.app.com.classes.Layoutsos[ idlayoutsos=" + idlayoutsos + " ]";
}
}
Assuming you have an object variable layoutsos of type Layoutsos that has been persisted to the DB or retrieved from the DB. Here's how your code should look like when persisting the Ordemservico entity.
Ordemservico o = new Ordemservico();
o.getOrdemproducaoList().add(layoutsos);
em.persist(o);
If this is a bi-directional relationship, you should set both side of the relationship before persisting.
Layoutsos layoutsos = new Layoutsos();
Ordemservico o = new Ordemservico();
o.getOrdemproducaoList().add(layoutsos);
layoutsos.getOrdermserviceoList().add(o);
em.persist(layoutsos);
em.persist(o);
Related
I am trying to prepate a list of maps, where each map represents a row of table data having keys as column names and values are column values i.e., Map. I could able to prepare the list of maps, but except Id column all other column values are returning as null. could you please help on this. Whats wrong with my code. There are no NullPointer exception for sessionfactory access with below code
Criteria crt = session.createCriteria(SampleCsv.class)
.add( Restrictions.between("Id", 3, 6) )
.setResultTransformer(new BasicTransformerAdapter() {
#SuppressWarnings("deprecation")
#Override
public Object transformTuple(Object[] tuple, String[] aliases) {
PassThroughResultTransformer rt = PassThroughResultTransformer.INSTANCE;
final Object o = rt.transformTuple(tuple, aliases);
ClassMetadata cm = getSessionFactory().getClassMetadata(o.getClass());
List<String> pns = new ArrayList<String>(Arrays.asList(cm.getPropertyNames()));
Map<String, Object> m = new HashMap<String, Object>();
for(String pn : pns) {
m.put(pn, cm.getPropertyValue(o, pn));
}
m.put(cm.getIdentifierPropertyName(), cm.getIdentifier(o));
return m;
}
});
List<Map<String,Object>> aliasToValueMap = (List<Map<String, Object>>)crt.list();
and my pojo class is
#Entity
#Table(name="SAMPLE_CSV")
public class SampleCsv {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="ID", nullable = false)
private int Id;
#Column(name = "Type", nullable = true)
private String Type;
#Column(name = "NomMedia")
private String NomMedia;
#Column(name = "sRep")
private String sRep;
#Column(name = "UrlMedia")
private String UrlMedia;
#Column(name = "Indice")
private String Indice;
#Column(name = "CodeFourSAP")
private String CodeFourSAP;
#Column(name = "NomDepositaire")
private String NomDepositaire;
#Column(name = "PrenomDepositaire")
private String PrenomDepositaire;
#Column(name = "EMailDepositaire")
private String EMailDepositaire;
#Column(name = "DateDepot")
private String DateDepot;
#Column(name = "PhotoPrincipale")
private String PhotoPrincipale;
#Column(name = "NomPhotographe")
private String NomPhotographe;
#Column(name = "PrenomPhotographe")
private String PrenomPhotographe;
#Column(name = "SocieteProprietaireDesDroits")
private String SocieteProprietaireDesDroits;
#Column(name = "DateCreationOuModificationMediaH")
private String DateCreationOuModificationMediaH;
#Column(name = "Commentaire")
private String Commentaire;
#Column(name = "WEB_Valide")
private String WEB_Valide;
#Column(name = "WEB_DateValidation")
private String WEB_DateValidation;
#Column(name = "WEB_ValidePar")
private String WEB_ValidePar;
#Column(name = "WEB_Classement")
private String WEB_Classement;
#Column(name = "CreditPhoto")
private String CreditPhoto;
#Column(name = "WEB_Commentaire")
private String WEB_Commentaire;
#Column(name = "NB_IMAGES")
private String NB_IMAGES;
#Column(name = "Watermark")
private String Watermark;
#Column(name = "Zoom")
private String Zoom;
#Column(name = "Traite")
private String Traite;
#Column(name = "TailleX")
private String TailleX;
#Column(name = "TailleY")
private String TailleY;
#Column(name = "MediaH_CodeArtSAP")
private String MediaH_CodeArtSAP;
#Column(name = "RefLoueur")
private String RefLoueur;
#Column(name = "Extension")
private String Extension;
#Column(name = "MediaP_CodeArtSAP")
private String MediaP_CodeArtSAP;
#Column(name = "DateDebutDroit")
private String DateDebutDroit;
#Column(name = "DateFinDroit")
private String DateFinDroit;
#Column(name = "DateCreationOuModificationCopyright")
private String DateCreationOuModificationCopyright;
public int getId() {
return Id;
}
public void setId(int id) {
this.Id = id;
}
public String getType() {
return Type;
}
public void setType(String type) {
Type = type;
}
public String getNomMedia() {
return NomMedia;
}
public void setNomMedia(String nomMedia) {
NomMedia = nomMedia;
}
public String getsRep() {
return sRep;
}
public void setsRep(String sRep) {
this.sRep = sRep;
}
public String getUrlMedia() {
return UrlMedia;
}
public void setUrlMedia(String urlMedia) {
UrlMedia = urlMedia;
}
public String getIndice() {
return Indice;
}
public void setIndice(String indice) {
Indice = indice;
}
public String getCodeFourSAP() {
return CodeFourSAP;
}
public void setCodeFourSAP(String codeFourSAP) {
CodeFourSAP = codeFourSAP;
}
public String getNomDepositaire() {
return NomDepositaire;
}
public void setNomDepositaire(String nomDepositaire) {
NomDepositaire = nomDepositaire;
}
public String getPrenomDepositaire() {
return PrenomDepositaire;
}
public void setPrenomDepositaire(String prenomDepositaire) {
PrenomDepositaire = prenomDepositaire;
}
public String getEMailDepositaire() {
return EMailDepositaire;
}
public void setEMailDepositaire(String eMailDepositaire) {
EMailDepositaire = eMailDepositaire;
}
public String getDateDepot() {
return DateDepot;
}
public void setDateDepot(String dateDepot) {
DateDepot = dateDepot;
}
public String getPhotoPrincipale() {
return PhotoPrincipale;
}
public void setPhotoPrincipale(String photoPrincipale) {
PhotoPrincipale = photoPrincipale;
}
public String getNomPhotographe() {
return NomPhotographe;
}
public void setNomPhotographe(String nomPhotographe) {
NomPhotographe = nomPhotographe;
}
public String getPrenomPhotographe() {
return PrenomPhotographe;
}
public void setPrenomPhotographe(String prenomPhotographe) {
PrenomPhotographe = prenomPhotographe;
}
public String getSocieteProprietaireDesDroits() {
return SocieteProprietaireDesDroits;
}
public void setSocieteProprietaireDesDroits(String societeProprietaireDesDroits) {
SocieteProprietaireDesDroits = societeProprietaireDesDroits;
}
public String getDateCreationOuModificationMediaH() {
return DateCreationOuModificationMediaH;
}
public void setDateCreationOuModificationMediaH(
String dateCreationOuModificationMediaH) {
DateCreationOuModificationMediaH = dateCreationOuModificationMediaH;
}
public String getCommentaire() {
return Commentaire;
}
public void setCommentaire(String commentaire) {
Commentaire = commentaire;
}
public String getWEB_Valide() {
return WEB_Valide;
}
public void setWEB_Valide(String wEB_Valide) {
WEB_Valide = wEB_Valide;
}
public String getWEB_DateValidation() {
return WEB_DateValidation;
}
public void setWEB_DateValidation(String wEB_DateValidation) {
WEB_DateValidation = wEB_DateValidation;
}
public String getWEB_ValidePar() {
return WEB_ValidePar;
}
public void setWEB_ValidePar(String wEB_ValidePar) {
WEB_ValidePar = wEB_ValidePar;
}
public String getWEB_Classement() {
return WEB_Classement;
}
public void setWEB_Classement(String wEB_Classement) {
WEB_Classement = wEB_Classement;
}
public String getCreditPhoto() {
return CreditPhoto;
}
public void setCreditPhoto(String creditPhoto) {
CreditPhoto = creditPhoto;
}
public String getWEB_Commentaire() {
return WEB_Commentaire;
}
public void setWEB_Commentaire(String wEB_Commentaire) {
WEB_Commentaire = wEB_Commentaire;
}
public String getNB_IMAGES() {
return NB_IMAGES;
}
public void setNB_IMAGES(String nB_IMAGES) {
NB_IMAGES = nB_IMAGES;
}
public String getWatermark() {
return Watermark;
}
public void setWatermark(String watermark) {
Watermark = watermark;
}
public String getZoom() {
return Zoom;
}
public void setZoom(String zoom) {
Zoom = zoom;
}
public String getTraite() {
return Traite;
}
public void setTraite(String traite) {
Traite = traite;
}
public String getTailleX() {
return TailleX;
}
public void setTailleX(String tailleX) {
TailleX = tailleX;
}
public String getTailleY() {
return TailleY;
}
public void setTailleY(String tailleY) {
TailleY = tailleY;
}
public String getMediaH_CodeArtSAP() {
return MediaH_CodeArtSAP;
}
public void setMediaH_CodeArtSAP(String mediaH_CodeArtSAP) {
MediaH_CodeArtSAP = mediaH_CodeArtSAP;
}
public String getRefLoueur() {
return RefLoueur;
}
public void setRefLoueur(String refLoueur) {
RefLoueur = refLoueur;
}
public String getExtension() {
return Extension;
}
public void setExtension(String extension) {
Extension = extension;
}
public String getMediaP_CodeArtSAP() {
return MediaP_CodeArtSAP;
}
public void setMediaP_CodeArtSAP(String mediaP_CodeArtSAP) {
MediaP_CodeArtSAP = mediaP_CodeArtSAP;
}
public String getDateDebutDroit() {
return DateDebutDroit;
}
public void setDateDebutDroit(String dateDebutDroit) {
DateDebutDroit = dateDebutDroit;
}
public String getDateFinDroit() {
return DateFinDroit;
}
public void setDateFinDroit(String dateFinDroit) {
DateFinDroit = dateFinDroit;
}
public String getDateCreationOuModificationCopyright() {
return DateCreationOuModificationCopyright;
}
public void setDateCreationOuModificationCopyright(
String dateCreationOuModificationCopyright) {
DateCreationOuModificationCopyright = dateCreationOuModificationCopyright;
}
}
I am posting the out put of final list with two maps as below
[{Id=3,PrenomDepositaire=null, RefLoueur=null, DateCreationOuModificationCopyright=null, EMailDepositaire=null, SocieteProprietaireDesDroits=null, NomMedia=null, TailleX=null, CodeFourSAP=null, PrenomPhotographe=null, Commentaire=null, MediaP_CodeArtSAP=null, NomDepositaire=null, WEB_Commentaire=null, UrlMedia=null, Zoom=null, TailleY=null, WEB_Valide=null, DateDepot=null, sRep=null, WEB_ValidePar=null, Indice=null, CreditPhoto=null, DateCreationOuModificationMediaH=null, MediaH_CodeArtSAP=null, DateDebutDroit=null, WEB_Classement=null, DateFinDroit=null, NB_IMAGES=null, NomPhotographe=null, PhotoPrincipale=null, Extension=null, Type=null, WEB_DateValidation=null, Traite=null, Watermark=null},
{ Id=4,PrenomDepositaire=null, RefLoueur=null, DateCreationOuModificationCopyright=null, EMailDepositaire=null, SocieteProprietaireDesDroits=null, NomMedia=null, TailleX=null, CodeFourSAP=null, PrenomPhotographe=null, Commentaire=null, MediaP_CodeArtSAP=null, NomDepositaire=null, WEB_Commentaire=null, UrlMedia=null, Zoom=null, TailleY=null, WEB_Valide=null, DateDepot=null, sRep=null, WEB_ValidePar=null, Indice=null, CreditPhoto=null, DateCreationOuModificationMediaH=null, MediaH_CodeArtSAP=null, DateDebutDroit=null, WEB_Classement=null, DateFinDroit=null, NB_IMAGES=null, NomPhotographe=null, PhotoPrincipale=null, Extension=null, Type=null, WEB_DateValidation=null, Traite=null, Watermark=null}
]
But table data having non null data as well..
I am new to JavaEE and I am having a problem with persisting a table that has foreign keys pointing to the primary key of another table using entity classes and ejb's entity manager. I am using Netbeans.
I have an entity called 'property' and have another entity called 'offer' which holds the foreign key pointing to the primary key of the property. So basically, the logic is that one property can have many offers. Therefore, I am trying to add new offers in the 'offer' table using the entity manager but I am not being able to do it. You can look at the code and see what I maybe missing.
Property entity:
#Entity
#Table(name = "PROPERTY")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Property.findAll", query = "SELECT p FROM Property p")})
public class Property implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "PROPERTYID")
private Integer propertyid;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 500)
#Column(name = "DESCRIPTION")
private String description;
#Size(max = 50)
#Column(name = "TYPE")
private String type;
#Column(name = "NUMBEROFBEDROOM")
private Integer numberofbedroom;
#Column(name = "NUMBEROFBATHROOM")
private Integer numberofbathroom;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 10)
#Column(name = "ISFURNISHED")
private String isfurnished;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 10)
#Column(name = "HASGARDEN")
private String hasgarden;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 20)
#Column(name = "SIZE")
private String size;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "PRICE")
private String price;
#Basic(optional = false)
#NotNull
#Column(name = "ENTEREDDATE")
#Temporal(TemporalType.DATE)
private Date entereddate;
#Basic(optional = false)
#NotNull
#Column(name = "ENTEREDTIME")
#Temporal(TemporalType.TIME)
private Date enteredtime;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "property")
private Paddress paddress;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "propertyid")
private Collection<Offer> offerCollection;
#JoinColumn(name = "PROPERTYOWNERID", referencedColumnName = "PROPERTYOWNERID")
#ManyToOne(optional = false)
private Propertyowner propertyownerid;
#JoinColumn(name = "REALESTATEAGENTID", referencedColumnName = "REALESTATEAGENTID")
#ManyToOne(optional = false)
private Realestateagent realestateagentid;
public Property() {
}
public Property(Integer propertyid) {
this.propertyid = propertyid;
}
public Property(Integer propertyid, String description, String isfurnished, String hasgarden, String size, String price, Date entereddate, Date enteredtime) {
this.propertyid = propertyid;
this.description = description;
this.isfurnished = isfurnished;
this.hasgarden = hasgarden;
this.size = size;
this.price = price;
this.entereddate = entereddate;
this.enteredtime = enteredtime;
}
public Integer getPropertyid() {
return propertyid;
}
public void setPropertyid(Integer propertyid) {
this.propertyid = propertyid;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getNumberofbedroom() {
return numberofbedroom;
}
public void setNumberofbedroom(Integer numberofbedroom) {
this.numberofbedroom = numberofbedroom;
}
public Integer getNumberofbathroom() {
return numberofbathroom;
}
public void setNumberofbathroom(Integer numberofbathroom) {
this.numberofbathroom = numberofbathroom;
}
public String getIsfurnished() {
return isfurnished;
}
public void setIsfurnished(String isfurnished) {
this.isfurnished = isfurnished;
}
public String getHasgarden() {
return hasgarden;
}
public void setHasgarden(String hasgarden) {
this.hasgarden = hasgarden;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public Date getEntereddate() {
return entereddate;
}
public void setEntereddate(Date entereddate) {
this.entereddate = entereddate;
}
public Date getEnteredtime() {
return enteredtime;
}
public void setEnteredtime(Date enteredtime) {
this.enteredtime = enteredtime;
}
public Paddress getPaddress() {
return paddress;
}
public void setPaddress(Paddress paddress) {
this.paddress = paddress;
}
#XmlTransient
public Collection<Offer> getOfferCollection() {
return offerCollection;
}
public void setOfferCollection(Collection<Offer> offerCollection) {
this.offerCollection = offerCollection;
}
public Propertyowner getPropertyownerid() {
return propertyownerid;
}
public void setPropertyownerid(Propertyowner propertyownerid) {
this.propertyownerid = propertyownerid;
}
public Realestateagent getRealestateagentid() {
return realestateagentid;
}
public void setRealestateagentid(Realestateagent realestateagentid) {
this.realestateagentid = realestateagentid;
}
public String dateToString()
{
DateFormat df = new SimpleDateFormat("dd/MM/yy");
return df.format(entereddate);
}
public String timeToString()
{
DateFormat df = new SimpleDateFormat("HH:mm:ss");
return df.format(enteredtime);
}
#Override
public int hashCode() {
int hash = 0;
hash += (propertyid != null ? propertyid.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 Property)) {
return false;
}
Property other = (Property) object;
if ((this.propertyid == null && other.propertyid != null) || (this.propertyid != null && !this.propertyid.equals(other.propertyid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.sushan.model.Property[ propertyid=" + propertyid + " ]";
}
}
EJB PropertyDAO:
#Stateless
public class PropertyDAO implements PropertyDAOLocal {
#PersistenceContext(unitName="RealEstateWebsite-ejbPU")
private EntityManager em;
#Override
public void AddProperty(Property property) {
em.persist(property);
}
#Override
public void EditProperty(Property property) {
em.merge(property);
}
#Override
public void DeleteProperty(int propertyId) {
em.remove(GetProperty(propertyId));
}
#Override
public List<Property> GetAllProperty() {
return em.createNamedQuery("Property.findAll").getResultList();
}
#Override
public Property GetProperty(int propertyId) {
return em.find(Property.class, propertyId);
}
#Override
public void EditPropertyAddress(Paddress propertyAddress) {
em.merge(propertyAddress);
}
}
Offer entity:
#Entity
#Table(name = "OFFER")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Offer.findAll", query = "SELECT o FROM Offer o")})
public class Offer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "OFFERID")
private Integer offerid;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "OFFERSTATUS")
private String offerstatus;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "ORIGINALOFFER")
private String originaloffer;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "OFFERINGBP")
private String offeringbp;
#Basic(optional = false)
#NotNull
#Column(name = "OFFEREDDATE")
#Temporal(TemporalType.DATE)
private Date offereddate;
#Basic(optional = false)
#NotNull
#Column(name = "OFFEREDTIME")
#Temporal(TemporalType.TIME)
private Date offeredtime;
#JoinColumn(name = "BUYERID", referencedColumnName = "BUYERID")
#ManyToOne(optional = false)
private Buyer buyerid;
#JoinColumn(name = "PROPERTYID", referencedColumnName = "PROPERTYID")
#ManyToOne(optional = false)
private Property propertyid;
public Offer() {
}
public Offer(Integer offerid) {
this.offerid = offerid;
}
public Offer(String offerstatus, String originaloffer, String offeringbp, Date offereddate, Date offeredtime, Buyer buyerid, Property propertyid) {
this.offerstatus = offerstatus;
this.originaloffer = originaloffer;
this.offeringbp = offeringbp;
this.offereddate = offereddate;
this.offeredtime = offeredtime;
this.buyerid = buyerid;
this.propertyid = propertyid;
}
public Integer getOfferid() {
return offerid;
}
public void setOfferid(Integer offerid) {
this.offerid = offerid;
}
public String getOfferstatus() {
return offerstatus;
}
public void setOfferstatus(String offerstatus) {
this.offerstatus = offerstatus;
}
public String getOriginaloffer() {
return originaloffer;
}
public void setOriginaloffer(String originaloffer) {
this.originaloffer = originaloffer;
}
public String getOfferingbp() {
return offeringbp;
}
public void setOfferingbp(String offeringbp) {
this.offeringbp = offeringbp;
}
public Date getOffereddate() {
return offereddate;
}
public void setOffereddate(Date offereddate) {
this.offereddate = offereddate;
}
public Date getOfferedtime() {
return offeredtime;
}
public void setOfferedtime(Date offeredtime) {
this.offeredtime = offeredtime;
}
public Buyer getBuyerid() {
return buyerid;
}
public void setBuyerid(Buyer buyerid) {
this.buyerid = buyerid;
}
public Property getPropertyid() {
return propertyid;
}
public void setPropertyid(Property propertyid) {
this.propertyid = propertyid;
}
#Override
public int hashCode() {
int hash = 0;
hash += (offerid != null ? offerid.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 Offer)) {
return false;
}
Offer other = (Offer) object;
if ((this.offerid == null && other.offerid != null) || (this.offerid != null && !this.offerid.equals(other.offerid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.sushan.model.Offer[ offerid=" + offerid + " ]";
}
EJB OfferDAO:
#Stateless
public class OfferDAO implements OfferDAOLocal {
#PersistenceContext(unitName="RealEstateWebsite-ejbPU")
EntityManager em;
#Override
public void EditOffer(Offer offer) {
em.merge(offer);
}
#Override
public List<Offer> GetAllOffer(int propertyId) {
return em.createNamedQuery("Offer.findByPropertyID").setParameter("propertyID", propertyId).getResultList();
}
#Override
public List<Offer> GetAllOffer() {
return em.createNamedQuery("Offer.findAll").getResultList();
}
#Override
public void Add(Offer offer) {
em.persist(offer);
}
}
Servlet that connects the JSP with the EJB:
String action = request.getParameter("action");
String currencyType = request.getParameter("ddlCurrencyType");
String amount = request.getParameter("offerAmount");
String propertyIdStr = request.getParameter("hdnbt");
if ("Offer".equalsIgnoreCase(action))
{
if ("".equals(action) & !"".equals(currencyType) & !"".equals(amount) & !"".equals(propertyIdStr))
{
DateFormat df = new SimpleDateFormat("dd/MM/yy");
DateFormat df1 = new SimpleDateFormat("HH:mm:ss");
Date currentDate = new Date();
Date currentTime = new Date();
int propertyId = Integer.parseInt(propertyIdStr);
try {
currentDate = df.parse(df.format(currentDate));
currentTime = df1.parse(df1.format(currentTime));
} catch (ParseException e) {
}
Buyer buyer = buyerDAO.GetBuyer(1);
Property property = propertyDAO.GetProperty(propertyId);
Offer offer = new Offer("Pending", amount, amount, currentDate, currentTime, buyer, property);
offerDAO.Add(offer);
}
else
{
}
}
request.setAttribute("allProperty", propertyDAO.GetAllProperty());
request.getRequestDispatcher("AdministerProperty.jsp").forward(request, response);
Am I missing something here? I have followed a tutorial which didn't have a foreign key guidance but tried to use my own logic to go around it but it didn't work. I cannot find a reliable source that uses the method similar to me. Most of the resources I find are for Hibernate but I am using EJB.
It seems that the method which retrieves the Property and the method that persists the Offer are run in a separate transactions (DAOs being the Stateless session beans).
That would mean that the Offer is populated and persisted with a detached Property, so the persistence provider is not aware of it.
Not sure why an exception is not raised but you would have to merge the Property first or do the query in the same transaction as you persist the Offer:
#Override
public void Add(Offer offer, int peropertyId) {
Property property = em.find(Property.class, propertyId);
offer.setPeropertyId(property);
em.persist(offer);
}
or
#Override
public void Add(Offer offer, Property peroperty) {
Property managedProperty = em.merge(property);
offer.setPeropertyId(managedProperty);
em.persist(offer);
}
I fixed it. If you look at the code for servlet, it was the problem with my if condition that checks the action parameter. It was meant to be if action is not empty but it checks if action is empty. I found this issue by creating an integer that increments itself when it reaches certain stages within the code.
I think you were right on the fact that I had to do the getting property id and buyer id on the same transaction. Otherwise that would have been the next issue for me. Thank you.
i have a servlet in that i add all data relted to child and parent table like
public net.sf.json.JSONArray saveQuery(QueryBuilderRequestHelper helper){
logger.log(Level.INFO," ############### Save Query ############### ");
HttpSession session = null;
session = helper.getHttpServletRequest().getSession();
int physicianId=Integer.parseInt(helper.getPhysicianId());
String title=helper.getTitle();
String discription=helper.getDiscription();
String condition=helper.getcondition();
String rules=helper.getRules();
String fields=helper.getFields();
String query = (String) session.getAttribute("query");
List<QueryBuilderCondition> conditionList = new ArrayList<QueryBuilderCondition>();
net.sf.json.JSONObject jObject=new net.sf.json.JSONObject();
net.sf.json.JSONArray jArray = new net.sf.json.JSONArray();
String result="";
try {
JSONArray jsonArr = new JSONArray(rules);
QueryBuilder builder =new QueryBuilder();
builder.setCondition(condition);
builder.setCreationTime(new Date());
builder.setDiscription(discription);
builder.setOutputFields(fields);
builder.setPhysician(new PhysicianJpaController().findPhysician(physicianId));
builder.setQueryTitle(title);
builder.setSqlQuery(query);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
QueryBuilderCondition qbCondition=new QueryBuilderCondition();
qbCondition.setFieldId(jsonObj.getString("id"));
qbCondition.setOperator(jsonObj.getString("operator"));
qbCondition.setValue(jsonObj.getString("value"));
qbCondition.setQuerybuilderId(builder);
conditionList.add(qbCondition);
}
builder.setQueryBuilderConditionCollection(conditionList);
System.out.println("==========conditionList========="+conditionList.toString()+ "======SIZE is ============="+conditionList.size());
result=new QueryBuilderJpaController().saveQuery(builder);
if(result.equals("success")){
jObject.put("result", result);
}
}catch(Exception ex){
result="error";
ex.printStackTrace();
logger.log(Level.INFO,"===============saveQuery==============="+ex.getMessage());
}
jArray.add(jObject);
return null;
}
from here i call my jpa control
public String saveQuery(QueryBuilder builder) {
logger.log(Level.SEVERE, " ############### saveQuery############### ");
String result = "";
try {
EntityManager em = getEntityManager();
em.getTransaction().begin();
em.persist(builder);
//em.persist(builderCondition);
em.getTransaction().commit();
result = "success";
} catch (Exception ex) {
result = "error";
ex.printStackTrace();
logger.log(Level.SEVERE, "=======================" + ex.getMessage());
}
return result;
}
don't know but this code gives me an error:
InsertObjectQuery(com.medikm.entity.QueryBuilder[ id=null ])
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commitInternal(EntityTransactionImpl.java:102)
please let me know what i did wrong here .pelase let me know if any clrification required
here is queryBuilder class
public class QueryBuilder implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#Column(name = "query_title")
private String queryTitle;
#Basic(optional = false)
#Lob
#Column(name = "sql_query")
private String sqlQuery;
#Basic(optional = false)
#Column(name = "condition")
private String condition;
#Basic(optional = false)
#Column(name = "output_fields")
private String outputFields;
#Column(name = "creation_time")
#Temporal(TemporalType.TIMESTAMP)
private Date creationTime;
#Column(name = "modification_time")
#Temporal(TemporalType.TIMESTAMP)
private Date modificationTime;
#Basic(optional = false)
#Lob
#Column(name = "discription")
private String discription;
#JoinColumn(name = "physician", referencedColumnName = "Physician_Id")
#ManyToOne(optional = false)
private Physician physician;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "querybuilderId")
private Collection<QueryBuilderCondition> queryBuilderConditionCollection;
public QueryBuilder() {
}
public QueryBuilder(Integer id) {
this.id = id;
}
public QueryBuilder(Integer id, String queryTitle, String sqlQuery, String condition, String outputFields, String discription) {
this.id = id;
this.queryTitle = queryTitle;
this.sqlQuery = sqlQuery;
this.condition = condition;
this.outputFields = outputFields;
this.discription = discription;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getQueryTitle() {
return queryTitle;
}
public void setQueryTitle(String queryTitle) {
this.queryTitle = queryTitle;
}
public String getSqlQuery() {
return sqlQuery;
}
public void setSqlQuery(String sqlQuery) {
this.sqlQuery = sqlQuery;
}
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
public String getOutputFields() {
return outputFields;
}
public void setOutputFields(String outputFields) {
this.outputFields = outputFields;
}
public Date getCreationTime() {
return creationTime;
}
public void setCreationTime(Date creationTime) {
this.creationTime = creationTime;
}
public Date getModificationTime() {
return modificationTime;
}
public void setModificationTime(Date modificationTime) {
this.modificationTime = modificationTime;
}
public String getDiscription() {
return discription;
}
public void setDiscription(String discription) {
this.discription = discription;
}
public Physician getPhysician() {
return physician;
}
public void setPhysician(Physician physician) {
this.physician = physician;
}
#XmlTransient
public Collection<QueryBuilderCondition> getQueryBuilderConditionCollection() {
return queryBuilderConditionCollection;
}
public void setQueryBuilderConditionCollection(Collection<QueryBuilderCondition> queryBuilderConditionCollection) {
this.queryBuilderConditionCollection = queryBuilderConditionCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 QueryBuilder)) {
return false;
}
QueryBuilder other = (QueryBuilder) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.medikm.entity.QueryBuilder[ id=" + id + " ]";
}
}
Configuration has article type as children and article types may have different article types as children.
I am trying to retrieve all configuration and its children (all article type for a configuration).
I don't get parent and child article type here.
I want to retrieve all grant children by using Configuration entity.
This is my configuration entity :-
#Entity
#Table(name = "tbl_configuration")
#XmlRootElement
public class Configuration extends BaseEntity implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "config_index")
private Integer configIndex;
#Column(name = "config_nom")
private String configNom;
#Column(name = "config_revision")
private String configRevision;
#JsonManagedReference(value="configuration-article-type")
#OneToMany(mappedBy = "artTypPcIndexConfig", fetch = FetchType.EAGER)
private Collection<ArticleTypeParentChild> articleTypeParentChildCollection;
public Configuration()
{
}
public Configuration(Integer configIndex)
{
this.configIndex = configIndex;
}
public Integer getConfigIndex()
{
return configIndex;
}
public void setConfigIndex(Integer configIndex)
{
this.configIndex = configIndex;
}
public String getConfigNom()
{
return configNom;
}
public void setConfigNom(String configNom)
{
this.configNom = configNom;
}
public String getConfigRevision()
{
return configRevision;
}
public void setConfigRevision(String configRevision)
{
this.configRevision = configRevision;
}
public Collection<ArticleTypeParentChild> getArticleTypeParentChildCollection()
{
return articleTypeParentChildCollection;
}
public void setArticleTypeParentChildCollection(Collection<ArticleTypeParentChild> articleTypeParentChildCollection)
{
this.articleTypeParentChildCollection = articleTypeParentChildCollection;
}
}
ArticleTypeParentChild Table Entity
#Entity
#Table(name = "tbl_article_type_parent_child")
#XmlRootElement
public class ArticleTypeParentChild extends BaseEntity implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "art_type_pc_index")
private Integer artTypePcIndex;
#JsonBackReference(value="child-article-type")
#JoinColumn(name = "art_typ_child_index", referencedColumnName = "art_typ_index")
#ManyToOne(fetch = FetchType.EAGER)
private ArticleType artTypChildIndex;
#JsonBackReference(value="parent-article-type")
#JoinColumn(name = "art_typ_parent_index", referencedColumnName = "art_typ_index")
#ManyToOne(fetch = FetchType.EAGER)
private ArticleType artTypParentIndex;
#JsonBackReference(value="configuration-article-type")
#JoinColumn(name = "art_typ_pc_index_config", referencedColumnName = "config_index")
#ManyToOne(fetch = FetchType.EAGER)
private Configuration artTypPcIndexConfig;
public ArticleTypeParentChild()
{
}
public ArticleTypeParentChild(Integer artTypePcIndex)
{
this.artTypePcIndex = artTypePcIndex;
}
public Integer getArtTypePcIndex()
{
return artTypePcIndex;
}
public void setArtTypePcIndex(Integer artTypePcIndex)
{
this.artTypePcIndex = artTypePcIndex;
}
public ArticleType getArtTypChildIndex()
{
return artTypChildIndex;
}
public void setArtTypChildIndex(ArticleType artTypChildIndex)
{
this.artTypChildIndex = artTypChildIndex;
}
public ArticleType getArtTypParentIndex()
{
return artTypParentIndex;
}
public void setArtTypParentIndex(ArticleType artTypParentIndex)
{
this.artTypParentIndex = artTypParentIndex;
}
public Configuration getArtTypPcIndexConfig()
{
return artTypPcIndexConfig;
}
public void setArtTypPcIndexConfig(Configuration artTypPcIndexConfig)
{
this.artTypPcIndexConfig = artTypPcIndexConfig;
}
}
ArticleType Table Entity:-
public class ArticleType extends BaseEntity implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "art_typ_index")
private Integer artTypIndex;
#Basic(optional = false)
#Column(name = "art_typ_index_designation")
private int artTypIndexDesignation;
#Basic(optional = false)
#Column(name = "art_typ_code")
private String artTypCode;
#Basic(optional = false)
#Column(name = "art_typ_code_effectivite")
private String artTypCodeEffectivite;
#Basic(optional = false)
#Column(name = "art_typ_numero_serie")
private boolean artTypNumeroSerie;
#Basic(optional = false)
#Column(name = "art_typ_version_materiel")
private boolean artTypVersionMateriel;
#Basic(optional = false)
#Column(name = "art_typ_version_logiciel")
private boolean artTypVersionLogiciel;
#Column(name = "art_typ_index_description")
private String artTypIndexDescription;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "atrIndexArticleType")
private Collection<ArticleTypeReseau> articleTypeReseauCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "atvIndexArticleType")
private Collection<ArticleTypeVariante> articleTypeVarianteCollection;
#JoinColumn(name = "art_typ_index_option", referencedColumnName = "opt_art_index")
#ManyToOne
private OptionArticle artTypIndexOption;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "atpIndexArticleType")
private Collection<ArticleTypeProjet> articleTypeProjetCollection;
#OneToMany(mappedBy = "atvoIndexArticleType")
private Collection<ArticleTypeVarianteOption> articleTypeVarianteOptionCollection;
#JsonManagedReference(value="child-article-type")
#OneToMany(mappedBy = "artTypChildIndex", fetch = FetchType.EAGER)
private Collection<ArticleTypeParentChild> articleTypeChildCollection;
#JsonManagedReference(value="parent-article-type")
#OneToMany(mappedBy = "artTypParentIndex", fetch = FetchType.EAGER)
private Collection<ArticleTypeParentChild> articleTypeParentCollection;
#OneToMany(mappedBy = "atoIndexArtType")
private Collection<ArticleTypeOption> articleTypeOptionCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "locIndexArticleType")
private Collection<Localisation> localisationCollection;
#OneToMany(mappedBy = "atlIndexArticleType")
private Collection<ArticleTypeLocalisation> articleTypeLocalisationCollection;
public ArticleType()
{
}
public ArticleType(Integer artTypIndex)
{
this.artTypIndex = artTypIndex;
}
public ArticleType(Integer artTypIndex, int artTypIndexDesignation, String artTypCode, String artTypCodeEffectivite, boolean artTypNumeroSerie, boolean artTypVersionMateriel, boolean artTypVersionLogiciel)
{
this.artTypIndex = artTypIndex;
this.artTypIndexDesignation = artTypIndexDesignation;
this.artTypCode = artTypCode;
this.artTypCodeEffectivite = artTypCodeEffectivite;
this.artTypNumeroSerie = artTypNumeroSerie;
this.artTypVersionMateriel = artTypVersionMateriel;
this.artTypVersionLogiciel = artTypVersionLogiciel;
}
public Integer getArtTypIndex()
{
return artTypIndex;
}
public void setArtTypIndex(Integer artTypIndex)
{
this.artTypIndex = artTypIndex;
}
public int getArtTypIndexDesignation()
{
return artTypIndexDesignation;
}
public void setArtTypIndexDesignation(int artTypIndexDesignation)
{
this.artTypIndexDesignation = artTypIndexDesignation;
}
public String getArtTypCode()
{
return artTypCode;
}
public void setArtTypCode(String artTypCode)
{
this.artTypCode = artTypCode;
}
public String getArtTypCodeEffectivite()
{
return artTypCodeEffectivite;
}
public void setArtTypCodeEffectivite(String artTypCodeEffectivite)
{
this.artTypCodeEffectivite = artTypCodeEffectivite;
}
public boolean getArtTypNumeroSerie()
{
return artTypNumeroSerie;
}
public void setArtTypNumeroSerie(boolean artTypNumeroSerie)
{
this.artTypNumeroSerie = artTypNumeroSerie;
}
public boolean getArtTypVersionMateriel()
{
return artTypVersionMateriel;
}
public void setArtTypVersionMateriel(boolean artTypVersionMateriel)
{
this.artTypVersionMateriel = artTypVersionMateriel;
}
public boolean getArtTypVersionLogiciel()
{
return artTypVersionLogiciel;
}
public void setArtTypVersionLogiciel(boolean artTypVersionLogiciel)
{
this.artTypVersionLogiciel = artTypVersionLogiciel;
}
public String getArtTypIndexDescription()
{
return artTypIndexDescription;
}
public void setArtTypIndexDescription(String artTypIndexDescription)
{
this.artTypIndexDescription = artTypIndexDescription;
}
#XmlTransient
public Collection<ArticleTypeReseau> getArticleTypeReseauCollection()
{
return articleTypeReseauCollection;
}
public void setArticleTypeReseauCollection(Collection<ArticleTypeReseau> articleTypeReseauCollection)
{
this.articleTypeReseauCollection = articleTypeReseauCollection;
}
#XmlTransient
public Collection<ArticleTypeVariante> getArticleTypeVarianteCollection()
{
return articleTypeVarianteCollection;
}
public void setArticleTypeVarianteCollection(Collection<ArticleTypeVariante> articleTypeVarianteCollection)
{
this.articleTypeVarianteCollection = articleTypeVarianteCollection;
}
public OptionArticle getArtTypIndexOption()
{
return artTypIndexOption;
}
public void setArtTypIndexOption(OptionArticle artTypIndexOption)
{
this.artTypIndexOption = artTypIndexOption;
}
#XmlTransient
public Collection<ArticleTypeProjet> getArticleTypeProjetCollection()
{
return articleTypeProjetCollection;
}
public void setArticleTypeProjetCollection(Collection<ArticleTypeProjet> articleTypeProjetCollection)
{
this.articleTypeProjetCollection = articleTypeProjetCollection;
}
#XmlTransient
public Collection<ArticleTypeVarianteOption> getArticleTypeVarianteOptionCollection()
{
return articleTypeVarianteOptionCollection;
}
public void setArticleTypeVarianteOptionCollection(Collection<ArticleTypeVarianteOption> articleTypeVarianteOptionCollection)
{
this.articleTypeVarianteOptionCollection = articleTypeVarianteOptionCollection;
}
// #XmlTransient
public Collection<ArticleTypeParentChild> getArticleTypeParentChildCollection()
{
return articleTypeChildCollection;
}
public void setArticleTypeParentChildCollection(Collection<ArticleTypeParentChild> articleTypeParentChildCollection)
{
this.articleTypeChildCollection = articleTypeParentChildCollection;
}
// #XmlTransient
public Collection<ArticleTypeParentChild> getArticleTypeParentChildCollection1()
{
return articleTypeParentCollection;
}
public void setArticleTypeParentChildCollection1(Collection<ArticleTypeParentChild> articleTypeParentChildCollection1)
{
this.articleTypeParentCollection = articleTypeParentChildCollection1;
}
#XmlTransient
public Collection<ArticleTypeOption> getArticleTypeOptionCollection()
{
return articleTypeOptionCollection;
}
public void setArticleTypeOptionCollection(Collection<ArticleTypeOption> articleTypeOptionCollection)
{
this.articleTypeOptionCollection = articleTypeOptionCollection;
}
#XmlTransient
public Collection<Localisation> getLocalisationCollection()
{
return localisationCollection;
}
public void setLocalisationCollection(Collection<Localisation> localisationCollection)
{
this.localisationCollection = localisationCollection;
}
#XmlTransient
public Collection<ArticleTypeLocalisation> getArticleTypeLocalisationCollection()
{
return articleTypeLocalisationCollection;
}
public void setArticleTypeLocalisationCollection(Collection<ArticleTypeLocalisation> articleTypeLocalisationCollection)
{
this.articleTypeLocalisationCollection = articleTypeLocalisationCollection;
}
}
Here i have two JPA Classes: TimeSheet and TimeSheetDetails
In this case i have a trouble with updation of timesheet, while updation the timesheet (master table) updated smoothly, but timesheet details (child table) generate new rows instead of updation and the link table also updated with the new values.....
Here what is the re
1)TimeSheet.java
#Entity
#Table(name = AMAM_Constants.tb_name.TIMESHEET, schema = AMAM_Constants.db_name)
public class TimeSheet implements Serializable {
private long ts_Id;
private String ts_Candidate;
private Date ts_Sdate;
private Date ts_Edate;
private String active;
private String ts_Type;
private String ts_Status;
private List<TimeSheetDetails> timesheetDetails = new ArrayList<TimeSheetDetails>();
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinTable(name = AMAM_Constants.tb_name.TIMESHEET_LINK_DETAILS, joinColumns = {
#JoinColumn(name = "TS_ID")}, inverseJoinColumns = {
#JoinColumn(name = "TSD_ID")
})
public List<TimeSheetDetails> getTimesheetDetails() {
return timesheetDetails;
}
public void setTimesheetDetails(List<TimeSheetDetails> timesheetDetails) {
this.timesheetDetails = timesheetDetails;
}
#Column(name = "ACTIVE", length = 1)
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
#Column(name = "TS_CANDIDATE", length = 25)
public String getTs_Candidate() {
return ts_Candidate;
}
public void setTs_Candidate(String ts_Candidate) {
this.ts_Candidate = ts_Candidate;
}
#Column(name = "TS_EDATE")
public Date getTs_Edate() {
return ts_Edate;
}
public void setTs_Edate(Date ts_Edate) {
this.ts_Edate = ts_Edate;
}
#Id
#GeneratedValue
#Column(name = "TS_ID")
public long getTs_Id() {
return ts_Id;
}
public void setTs_Id(long ts_Id) {
this.ts_Id = ts_Id;
}
#Column(name = "TS_SDATE")
public Date getTs_Sdate() {
return ts_Sdate;
}
public void setTs_Sdate(Date ts_Sdate) {
this.ts_Sdate = ts_Sdate;
}
#Column(name = "TS_STATUS", length = 25)
public String getTs_Status() {
return ts_Status;
}
public void setTs_Status(String ts_Status) {
this.ts_Status = ts_Status;
}
#Column(name = "TS_TYPE", length = 10)
public String getTs_Type() {
return ts_Type;
}
public void setTs_Type(String ts_Type) {
this.ts_Type = ts_Type;
}
}
#Entity
#Table(name = AMAM_Constants.tb_name.TIMESHEET_DETAILS, schema = AMAM_Constants.db_name)
public class TimeSheetDetails implements Serializable {
private long tsd_Id;
private String tsd_Po;
private Date tsd_Date;
private String tsd_DayName;
private int tsd_Hours;
private String tsd_HourType;
private String tsd_DayType;
#Column(name = "TSD_DATE")
public Date getTsd_Date() {
return tsd_Date;
}
public void setTsd_Date(Date tsd_Date) {
this.tsd_Date = tsd_Date;
}
#Column(name = "TSD_DAYNAME", length = 25)
public String getTsd_DayName() {
return tsd_DayName;
}
public void setTsd_DayName(String tsd_DayName) {
this.tsd_DayName = tsd_DayName;
}
#Column(name = "TSD_DAYTYPE", length = 25)
public String getTsd_DayType() {
return tsd_DayType;
}
public void setTsd_DayType(String tsd_DayType) {
this.tsd_DayType = tsd_DayType;
}
#Column(name = "TSD_HOURTYPE", length = 25)
public String getTsd_HourType() {
return tsd_HourType;
}
public void setTsd_HourType(String tsd_HourType) {
this.tsd_HourType = tsd_HourType;
}
#Column(name = "TSD_HOURS")
public int getTsd_Hours() {
return tsd_Hours;
}
public void setTsd_Hours(int tsd_Hours) {
this.tsd_Hours = tsd_Hours;
}
#Id
#GeneratedValue
#Column(name = "TSD_ID")
public long getTsd_Id() {
return tsd_Id;
}
public void setTsd_Id(long tsd_Id) {
this.tsd_Id = tsd_Id;
}
#Column(name = "TSD_PO", length = 25)
public String getTsd_Po() {
return tsd_Po;
}
public void setTsd_Po(String tsd_Po) {
this.tsd_Po = tsd_Po;
}
}
public class TimeSheetDao extends HibDao {
public void insertTimeSheet(TimeSheet objTimeSheet) throws Exception {
try {
begin();
getSession().save(objTimeSheet);
commit();
} catch (Exception ex) {
rollback();
throw new Exception(ex.getMessage());
} finally {
flush();
close();
}
}
public void updateTimeSheet(TimeSheet objTimeSheet) throws Exception {
try {
begin();
TimeSheet obj =(TimeSheet)getSession().get(TimeSheet.class,objTimeSheet.getTs_Id());
obj.setActive("Y");
obj.setTimesheetDetails(objTimeSheet.getTimesheetDetails());
obj.setTs_Candidate(objTimeSheet.getTs_Candidate());
obj.setTs_Edate(objTimeSheet.getTs_Edate());
obj.setTs_Sdate(objTimeSheet.getTs_Sdate());
obj.setTs_Status(objTimeSheet.getTs_Status());
obj.setTs_Type(objTimeSheet.getTs_Type());
getSession().update(obj);
commit();
} catch (Exception ex) {
rollback();
throw new Exception(ex.getMessage());
} finally {
flush();
close();
}
}
}
The problem is in this line:
obj.setTimesheetDetails(objTimeSheet.getTimesheetDetails());
You should do the same to update the child to what you are doing to update the parent. I.e:
obj.getTimesheetDetails().setTsd_Date(objTimeSheet.getTimesheetDetails().getTsd_Date);
...