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 + " ]";
}
}
Related
I have a problem when using Long type attributes, I created an attribute called 'Cnh' which receives a 11 digit code, I already put the L in the end of the value, but when I run it in JUnit it still says Integer number too large: 06161567318l.
Is there any possible way I can avoid it
I don't wanna change the attribute type, because I have another which has the same problem but it is a 'hashcode' (it would be really tough to change)
SetUp Values
public void setUp() {
cli = new Cliente();
cli.setEmail("lucasoaresleite#gmail.com");
cli.setCpf(06161567318l);
cli.setCnh(06161567318l);
cli.setCnpj("--");
cli.setDataNascimento("23081998");
cli.setNomeCompleto("Lucas Soares");
cli.setNomeFantasia("--");
}
JUnit Test
public void testSetCnh() {
assertEquals(06161567318l, cli.getCnh());
}
public class Cliente implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "cpf")
private Long cpf;
#Basic(optional = false)
#Column(name = "nome_completo")
private String nomeCompleto;
#Basic(optional = false)
#Column(name = "data_nascimento")
private String dataNascimento;
#Basic(optional = false)
#Column(name = "email")
private String email;
#Basic(optional = false)
#Column(name = "cnh")
private Long cnh;
#Column(name = "cnpj")
private String cnpj;
#Column(name = "nome_fantasia")
private String nomeFantasia;
public Cliente() {
}
public Cliente(Long cpf) {
this.cpf = cpf;
}
public Cliente(Long cpf, String nomeCompleto, String dataNascimento, String email, Long cnh) {
this.cpf = cpf;
this.nomeCompleto = nomeCompleto;
this.dataNascimento = dataNascimento;
this.email = email;
this.cnh = cnh;
}
public Long getCpf() {
return cpf;
}
public void setCpf(Long cpf) {
this.cpf = cpf;
}
public String getNomeCompleto() {
return nomeCompleto;
}
public void setNomeCompleto(String nomeCompleto) {
this.nomeCompleto = nomeCompleto;
}
public String getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(String dataNascimento) {
this.dataNascimento = dataNascimento;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Long getCnh() {
return cnh;
}
public void setCnh(Long cnh) {
this.cnh = cnh;
}
public String getCnpj() {
return cnpj;
}
public void setCnpj(String cnpj) {
this.cnpj = cnpj;
}
public String getNomeFantasia() {
return nomeFantasia;
}
public void setNomeFantasia(String nomeFantasia) {
this.nomeFantasia = nomeFantasia;
}
#Override
public int hashCode() {
int hash = 0;
hash += (cpf != null ? cpf.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 Cliente)) {
return false;
}
Cliente other = (Cliente) object;
if ((this.cpf == null && other.cpf != null) || (this.cpf != null && !this.cpf.equals(other.cpf))) {
return false;
}
return true;
}
#Override
public String toString() {
return "alocar.java.models.Cliente[ cpf=" + cpf + " ]";
}
}
I need it to accept values way bigger than the limit(I know... but I also know you know what I'm talking about) ]:)
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 developed an application using Java Spring (backend api), mysql (DB) and Anguljar JS (frontend) that is designed to let users schedule an appointment. The endtime of each appointment is five minutes after its starttime, between 8 o’clock and 2 p.m.
In my data base I have the following information:
• A table named “turno” which contains the parameters time and date of the appointments given.
• Another table contains all the available appointments.
I want to substract both arrays so as to see which appointments have not been given yet. The objective is not to allow users to fix an appointment that has already been made by someone else.
Does anyone have any idea how to do this?
Data examples:
Java Example:
#Entity
#Table(name = "turno")
public class Turno implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String solicitante;
private String telefono;
private TipoDocumento tipoDocumento;
private String numeroDocumento;
private String email;
private Horario horario;
private String numeroTurno;
private String fecha;
private Date formatfecha;
private Date controlFecha;
#Id
#GeneratedValue
#Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "solicitante")
public String getSolicitante() {
return solicitante;
}
public void setSolicitante(String solicitante) {
this.solicitante = solicitante;
}
#Column(name = "telefono")
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
#Column(name = "numero_documento")
public String getNumeroDocumento() {
return numeroDocumento;
}
public void setNumeroDocumento(String numeroDocumento) {
this.numeroDocumento = numeroDocumento;
}
#Column(name = "email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "horario", referencedColumnName = "id")
public Horario getHorario() {
return horario;
}
public void setHorario(Horario horario) {
this.horario = horario;
}
#Column(name = "numero_turno")
public String getNumeroTurno() {
return numeroTurno;
}
public void setNumeroTurno(String numeroTurno) {
this.numeroTurno = numeroTurno;
}
#Column(name = "fecha")
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
#Column(insertable = false, updatable = false, name = "fecha")
public Date getFormatFecha() {
return formatfecha;
}
public void setFormatFecha(Date formatfecha) {
this.formatfecha = formatfecha;
}
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "tipoDocumento", referencedColumnName = "id")
public TipoDocumento getTipoDocumento() {
return tipoDocumento;
}
public void setTipoDocumento(TipoDocumento tipoDocumento) {
this.tipoDocumento = tipoDocumento;
}
#Column(name = "fecha_control")
public Date getControlFecha() {
return controlFecha;
}
public void setControlFecha(Date controlFecha) {
this.controlFecha = controlFecha;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((numeroTurno == null) ? 0 : numeroTurno.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Turno other = (Turno) obj;
if (numeroTurno == null) {
if (other.numeroTurno != null)
return false;
} else if (!numeroTurno.equals(other.numeroTurno))
return false;
return true;
}
}
Updated
Heres how I fixed it in case anyone is interested:
Method in the controller:
#RequestMapping(value = "/horario/{fecha}", method = RequestMethod.GET)
#ResponseBody
public Object queryHorariosLibres(#PathVariable("fecha") Date fecha) {
List<Long> horariosLibres = null;
List<Long> turnosTomados = turnoService.getTurnosTomados(fecha);
Calendar dia = new GregorianCalendar();
dia.setTime(fecha);
Horario horario = horarioRepository.findByDia(dia.get(Calendar.DAY_OF_WEEK));
horariosLibres = horario.getHorariosLibres(turnosTomados);
if (horariosLibres == null) {
return "hola";
}
else
return horariosLibres;
}
Local methods:
#Transient
public List<Long> getHorarios(){
List<Long> horarios = new ArrayList<Long>();
for(Long i = horarioInicio; i <= horarioFin; i+=300){
horarios.add(i);
}
return horarios;
}
#Transient
public List<Long> getHorariosLibres(List<Long> horariosTomados){
List<Long> horariosLibres = getHorarios();
horariosLibres.removeAll(horariosTomados);
return horariosLibres;
}
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);
this is my first post, so please bear with me if i do make any errors.
I get an error " java.lang.IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST"
whenever i want to query(add,edit,delete) the database.
The tables related are sponsors and donations. There is a one to many relationship between them. Classes below:
Sponsors
#Entity
#Table(name = "SPONSORS")
#NamedQueries({
#NamedQuery(name = "Sponsors.findAll", query = "SELECT s FROM Sponsors s")})
public class Sponsors implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "SPONSORID")
private Short sponsorid;
#Basic(optional = false)
#Column(name = "NAME")
private String name;
#Basic(optional = false)
#Column(name = "SURNAME")
private String surname;
#Basic(optional = false)
#Column(name = "ADDRESS")
private String address;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "sponsorid")
private List<Donations> donationsList;
public Sponsors() {
}
public Sponsors(Short sponsorid) {
this.sponsorid = sponsorid;
}
public Sponsors(Short sponsorid, String name, String surname, String address) {
this.sponsorid = sponsorid;
this.name = name;
this.surname = surname;
this.address = address;
}
public Short getSponsorid() {
return sponsorid;
}
public void setSponsorid(Short sponsorid) {
this.sponsorid = sponsorid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public List<Donations> getDonationsList() {
return donationsList;
}
public void setDonationsList(List<Donations> donationsList) {
this.donationsList = donationsList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (sponsorid != null ? sponsorid.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 Sponsors)) {
return false;
}
Sponsors other = (Sponsors) object;
if ((this.sponsorid == null && other.sponsorid != null) || (this.sponsorid != null && !this.sponsorid.equals(other.sponsorid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Pat.Sponsors[ sponsorid=" + sponsorid + " ]";
}
}
Donations:
#Entity
#Table(name = "DONATIONS")
#NamedQueries({
#NamedQuery(name = "Donations.findAll", query = "SELECT d FROM Donations d")})
public class Donations implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "DONATIONID")
private Short donationid;
#Basic(optional = false)
#Column(name = "DONATIONDATE")
#Temporal(TemporalType.DATE)
private Date donationdate;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Column(name = "DONATIONAMOUNT")
private Double donationamount;
#JoinColumn(name = "SPONSORID", referencedColumnName = "SPONSORID")
#ManyToOne(optional = false)
private Sponsors sponsorid;
public Donations() {
}
public Donations(Short donationid) {
this.donationid = donationid;
}
public Donations(Short donationid, Date donationdate) {
this.donationid = donationid;
this.donationdate = donationdate;
}
public Short getDonationid() {
return donationid;
}
public void setDonationid(Short donationid) {
this.donationid = donationid;
}
public Date getDonationdate() {
return donationdate;
}
public void setDonationdate(Date donationdate) {
this.donationdate = donationdate;
}
public Double getDonationamount() {
return donationamount;
}
public void setDonationamount(Double donationamount) {
this.donationamount = donationamount;
}
public Sponsors getSponsorid() {
return sponsorid;
}
public void setSponsorid(Sponsors sponsorid) {
this.sponsorid = sponsorid;
}
#Override
public int hashCode() {
int hash = 0;
hash += (donationid != null ? donationid.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 Donations)) {
return false;
}
Donations other = (Donations) object;
if ((this.donationid == null && other.donationid != null) || (this.donationid != null && !this.donationid.equals(other.donationid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Pat.Donations[ donationid=" + donationid + " ]";
}
}
The field
#ManyToOne(optional = false)
private Sponsors sponsorid;
in the Donations entity is not configured for cascading. Try changing it to:
#ManuToOne(optional = false, cascade = CascadeType.ALL)
private Sponsors sponsorid;