I have a form with many fields, I want to save this fields in mongodb in a collection. I want if the user doesnt fill a textfield, then this field should not be saved in the collection.
I have an District
Entity. This entity contains another two entities (contact
and address
).
The District class lokks like this:
public class District {
@Id private ObjectId id;
private String Type;
private String Name;
private Contact contact;
private Address address;
/**
* @return the Type
*/
public String getType() {
return Type;
}
....
/**
* @param Type the Type to set
*/
public void setType(String Type) {
this.Type = Type;
}
For contact I have this Java class:
@Embedded
public class Contact {
private String email;
private String fax;
private String firstname;
private String lastname;
private String gender;
private String telephone;
private String title;
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* @return the fax
*/
public String getFax() {
return fax;
}
/**
* @param fax the fax to set
*/
public void setFax(String fax) {
this.fax = fax;
}
...
and my form lokks like this:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
Mongo mongo = null;
try {
mongo = new Mongo();
} catch (UnknownHostException ex) {
Logger.getLogger(TestForm.class.getName()).log(Level.SEVERE, null, ex);
}
Morphia morphia=new Morphia();
morphia.map(District).map(Contact).map(Address);
District district=new District();
district.setName(jTextField2.getText());
district.setType(jTextField3.getText());
Address address=new Address();
address.setCity(jTextField11.getText());
address.setStreet(jTextField10.getText());
address.setZipcode(jTextField9.getText());
....
Datastore ds=morphia.createDatastore(mongo, "rcfdb");
ds.save(district);
I want if the user doesnt fill the Name
field in the Form, then this field is not written in the MongoDB.(now I see the field i.e Name
with null value) I have tried to do that but that didnt help me:
....
if(jTextField4.getText()!="")
{
contact.setName(jTextField4.getText());
}
....
could you please help me to do this job?
thanks
Use String#equals
to compare String
content. The ==
operator compares object references. JTextField#getText
returns a different String
object compared to the interned one ""
being compared so the field value for the Entity
contact
is never set.
if (jTextField4.getText().equals("")) {
contact.setName(jTextField4.getText());
}