springboot mongo if image not present use existing one - java

This api works for inserting and updating but everytim I update the image dissapears so I am trying to say orElse if image not exist set image to existing image any advice pls
#RequestMapping(value = "/updateBank", method = RequestMethod.POST, consumes = "multipart/form-data")
public ResponseEntity<Bank> updateBank(
#RequestPart("bank") #Valid Bank bank,
#RequestPart("file") #Valid Optional<MultipartFile> image) throws IOException {
// routine to update a bank including image
image.ifPresent(pic ->
{
try {
bank.setImage(new Binary(BsonBinarySubType.BINARY, pic.getBytes()));
} catch (IOException e) {
e.printStackTrace();
}
});
Bank result = bankRepository.save(bank);
return ResponseEntity.ok().body(result);
}
#Document(collection = "mst_Bank")
public class Bank {
#Id
private String id;
private String name;
private String address;
private String country;
private String region;
private String city;
private String swiftCode;
private String routeCode;
private Binary flag;
private Binary image;
public Bank(String name, String address, String country, String region, String city, String swiftCode,
String routeCode) {
this.name = name;
this.address = address;
this.country = country;
this.region = region;
this.city = city;
this.swiftCode = swiftCode;
this.routeCode = routeCode;
}
public Bank() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getSwiftCode() {
return swiftCode;
}
public void setSwiftCode(String swiftCode) {
this.swiftCode = swiftCode;
}
public String getRouteCode() {
return routeCode;
}
public void setRouteCode(String routeCode) {
this.routeCode = routeCode;
}
public Binary getImage() {
return image;
}
public void setImage(Binary image) {
this.image = image;
}
}
/No Point of this
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details./

Use Something like this
#RequestMapping(value = "/updateEntity", method = RequestMethod.POST, consumes = "multipart/form-data")
public ResponseEntity<Entity> updateEntity(#RequestPart("entity") #Valid Entity entity, #RequestPart("file") #Valid Optional<MultipartFile> image) throws IOException {
// routine to update a entity including image
byte[] imageData = null;
if (image.isPresent() && image.get() != null)
imageData = image.get().getBytes();
if (imageData == null && entity.getId() != null) {
Optional<Entity> readEntity = entityRepository.findById(entity.getId());
if (readEntity.get() != null)
imageData = readEntity.get().getImage().getData();
}
if (imageData != null) {
entity.setImage(new Binary(BsonBinarySubType.BINARY, imageData));
}
Entity result = entityRepository.save(entity);
return ResponseEntity.ok().body(result);
}

Related

Not able to retrive data from Crud Operation in Hibernate

I have a application written in Spring, Hibernate and SpringBoot,
I have 2 entities class with one to many mapping,
Here are my LeadUserDb entity class
#Entity
#Table(name="lead_user_db")
#NamedQuery(name="LeadUserDb.findAll", query="SELECT l FROM LeadUserDb l")
public class LeadUserDb implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column(name="branchcode")
private String branchcode;
#Column(name="reporting_level")
private int reportingLevel;
//bi-directional many-to-one association to UserBasicDetailsDb
#ManyToOne
#JoinColumn(name="email_Id")
private UserBasicDetailsDb userBasicDetailsDb;
public LeadUserDb() {
}
public String getBranchcode() {
return this.branchcode;
}
public void setBranchcode(String branchcode) {
this.branchcode = branchcode;
}
public int getReportingLevel() {
return this.reportingLevel;
}
public void setReportingLevel(int reportingLevel) {
this.reportingLevel = reportingLevel;
}
public UserBasicDetailsDb getUserBasicDetailsDb() {
return this.userBasicDetailsDb;
}
public void setUserBasicDetailsDb(UserBasicDetailsDb userBasicDetailsDb) {
this.userBasicDetailsDb = userBasicDetailsDb;
}
And This is my UserBasicDetailsDb Entity Class
#Entity
#Table(name="user_basic_details_db")
public class UserBasicDetailsDb implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private String email;
private String address;
private String city;
private String dob;
private String mobile;
private String name;
private String pan;
private String pincode;
private String state;
#OneToMany(mappedBy="userBasicDetailsDb")
private List<LeadUserDb> leadUserDbs;
public UserBasicDetailsDb() {
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getDob() {
return this.dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getMobile() {
return this.mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPan() {
return this.pan;
}
public void setPan(String pan) {
this.pan = pan;
}
public String getPincode() {
return this.pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public List<LeadUserDb> getLeadUserDbs() {
return this.leadUserDbs;
}
public void setLeadUserDbs(List<LeadUserDb> leadUserDbs) {
this.leadUserDbs = leadUserDbs;
}
public LeadUserDb addLeadUserDb(LeadUserDb leadUserDb) {
getLeadUserDbs().add(leadUserDb);
leadUserDb.setUserBasicDetailsDb(this);
return leadUserDb;
}
public LeadUserDb removeLeadUserDb(LeadUserDb leadUserDb) {
getLeadUserDbs().remove(leadUserDb);
leadUserDb.setUserBasicDetailsDb(null);
return leadUserDb;
}
what i want to achieve is to create a query like this one
SELECT a.branchcode as branchCode,b.name FROM lead_user_db a
inner join user_basic_details_db b
where b.email = a.email_id and a.reporting_level = 3
here is what I have written my Repository class
public interface GetUserList extends CrudRepository<LeadUserDb, Integer> {
#Query(value = "SELECT a.id, a.branchcode as branchCode,b.name as name,a.reporting_level,a.email_id FROM lead_user_db a\n" +
"inner join user_basic_details_db b\n" +
"where b.email = a.email_id and a.reporting_level = ?1", nativeQuery = true)
List<LeadUserDb> findByReportingLevel(int reportingLevel);
}
and this is how I am calling it
UserBasicDetailsDb details = GetUserList.findByReportingLevel(3);
NOTE
Getting a new error Cannot determine value type from string test#dev.com
I am getting a hell lot of data, and the actual output have only 2 records
My question is how can i fetch the list of user based on reportingLevel
Any help would be appreciated

ObjectMapper can't map the variables of inner class

ObjectMapper mapper = new ObjectMapper();
try {
attractionMainResponse = mapper.readValue(response,AttractionMainResponse.class);
} catch(IOException io) {
showToast("Something went wrong");
FirebaseCrash.log(io.toString());
finish();
}
AttractionMainResponse :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AttractionMainResponse {
private AttractionDetailModel Attraction_Info;
private String response;
public AttractionMainResponse() {
Attraction_Info = null;
response =null;
}
public AttractionMainResponse(AttractionDetailModel aa,String ab) {
Attraction_Info = aa;
response = ab;
}
public AttractionDetailModel getAttraction_Info() {
return Attraction_Info;
}
public void setAttraction_Info(AttractionDetailModel attraction_Info) {
Attraction_Info = attraction_Info;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
}
AttractionDetailModel :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AttractionDetailModel {
private AddressDataAttraction address_data;
private List<Image> Images;
private TypesInAttraction Type;
private String architect;
private String architectural_style;
private int city_id;
private String founder;
private String description;
private int id;
private String name;
private String height;
private String opened_since;
private String popularity;
private String timings;
private String visitors;
private String profile_image_url;
public AttractionDetailModel() {
address_data = null;
architect = null;
architectural_style = null;
city_id=-1;
founder = null;
description = null;
id=-1;
name=null;
height=null;
opened_since=null;
popularity = null;
timings=null;
visitors=null;
Images = null;
Type=null;
profile_image_url=null;
}
public AttractionDetailModel(AddressDataAttraction address_data, List<Image> images, TypesInAttraction type, String architect, String architectural_style, int city_id, String founder, String description, int id, String name, String height, String opened_since, String popularity, String timings, String visitors, String profile_image_url) {
this.address_data = address_data;
Images = images;
Type = type;
this.architect = architect;
this.architectural_style = architectural_style;
this.city_id = city_id;
this.founder = founder;
this.description = description;
this.id = id;
this.name = name;
this.height = height;
this.opened_since = opened_since;
this.popularity = popularity;
this.timings = timings;
this.visitors = visitors;
this.profile_image_url = profile_image_url;
}
public String getProfile_image_url() {
return profile_image_url;
}
public void setProfile_image_url(String profile_image_url) {
this.profile_image_url = profile_image_url;
}
public AddressDataAttraction getAddress_data() {
return address_data;
}
public void setAddress_data(AddressDataAttraction address_data) {
this.address_data = address_data;
}
public List<Image> getImages() {
return Images;
}
public void setImages(List<Image> images) {
Images = images;
}
public TypesInAttraction getType() {
return Type;
}
public void setType(TypesInAttraction type) {
Type = type;
}
public String getArchitect() {
return architect;
}
public void setArchitect(String architect) {
this.architect = architect;
}
public String getArchitectural_style() {
return architectural_style;
}
public void setArchitectural_style(String architectural_style) {
this.architectural_style = architectural_style;
}
public int getCity_id() {
return city_id;
}
public void setCity_id(int city_id) {
this.city_id = city_id;
}
public String getFounder() {
return founder;
}
public void setFounder(String founder) {
this.founder = founder;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getOpened_since() {
return opened_since;
}
public void setOpened_since(String opened_since) {
this.opened_since = opened_since;
}
public String getPopularity() {
return popularity;
}
public void setPopularity(String popularity) {
this.popularity = popularity;
}
public String getTimings() {
return timings;
}
public void setTimings(String timings) {
this.timings = timings;
}
public String getVisitors() {
return visitors;
}
public void setVisitors(String visitors) {
this.visitors = visitors;
}
}
AddressDataAttractions :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AddressDataAttraction {
private String address;
private String city;
private String country;
private String landmark;
private float latitude;
private float longitude;
private String pincode;
private String state;
public AddressDataAttraction() {
address=null;
city=null;
country=null;
landmark=null;
latitude=-1;
longitude=-1;
pincode=null;
state=null;
}
public AddressDataAttraction(String address, String city, String country, String landmark, float latitude, float longitude, String pincode, String state) {
this.address = address;
this.city = city;
this.country = country;
this.landmark = landmark;
this.latitude = latitude;
this.longitude = longitude;
this.pincode = pincode;
this.state = state;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getLandmark() {
return landmark;
}
public void setLandmark(String landmark) {
this.landmark = landmark;
}
public float getLatitude() {
return latitude;
}
public void setLatitude(float latitude) {
this.latitude = latitude;
}
public float getLongitude() {
return longitude;
}
public void setLongitude(float longitude) {
this.longitude = longitude;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
TypeInAttraction :
#JsonIgnoreProperties (ignoreUnknown = true)
public class TypesInAttraction{
private String type;
private int id ;
public TypesInAttraction() {
type=null;
id=-1;
}
public TypesInAttraction(String type, int id) {
this.type = type;
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
In debug mode, string response in objectMapper shows correct response, string response in attractionMainResponse giving a success but can't map the attractionDetailModel, giving null.
Is this about a Jackson ObjectMapper? Is it possible to create a smaller example, that makes it easier to give a solution.

How can my server's response quiker by perfect my code and algorithm? I want to get some suggestions

I feel my app runs slow. I use Java for my server, so except java itself,the first reason of slow run, I think, is the account of database access. Hibernate could search all attribute associate with the entity which you are using, so I think it may send a lot of SQL language when finding one entity. If there's a large concurrent happening ,the trouble will happen.
#Component("user")
#Entity
#Table(name="users")
public class User implements Serializable{
#Id
#GenericGenerator(strategy="assigned",name="idGenerator")
#GeneratedValue(generator="idGenerator")
private String client_id;
#Column(name="username")
private String username;
#Column(name="password")
private String password;
#Column(name="email")
private String email;
#Column(name="phone")
private String phone;
#Column(name="sex")
private String sex;
#Column(name="birth")
private String birth;
#Column(name="status")
public String status;
#Column(name="isonline")
private String isonline;
#Column(name="province")
private String province;
#Column(name="city")
private String city;
#ManyToOne()
#JoinColumn(name="channel_id")
private Channel channel;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="created_at",updatable=true)
private Date created_at = new Date();
#Column(name="last_login_at")
private Date last_login_at;
#ManyToMany()
#JoinTable(name = "users_labels",
joinColumns = #JoinColumn(name = "client_id"),
inverseJoinColumns = #JoinColumn(name = "label_name"))
#LazyCollection(LazyCollectionOption.FALSE)
private Set<Label> labellist;
#ManyToOne()
#JoinTable(name = "user_topics",
joinColumns = #JoinColumn(name = "client_id"),
inverseJoinColumns = #JoinColumn(name = "huanxin_group_id"))
private Topic topic;
#ManyToMany()
#JoinTable(name="friends",
joinColumns=#JoinColumn(name="client_id"),
inverseJoinColumns=#JoinColumn(name="friend_id"))
#LazyCollection(LazyCollectionOption.FALSE)
private Set<User> friends;
#OneToMany(mappedBy="user")
private Set<FeedBack> feedbacks;
#ManyToMany()
#JoinTable(name="blacklist",
joinColumns=#JoinColumn(name="client_id"),
inverseJoinColumns=#JoinColumn(name="blocker_id"))
#LazyCollection(LazyCollectionOption.FALSE)
private Set<User> blacklist;
public Topic getTopic() {
return topic;
}
public void setTopic(Topic topic) {
this.topic = topic;
}
public Set<Label> getLabellist() {
return labellist;
}
public void setLabellist(Set<Label> labellist) {
this.labellist = labellist;
}
public String getClient_id() {
return client_id;
}
public void setClient_id(String client_id) {
this.client_id = client_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getBirth() {
return birth;
}
public void setBirth(String birth) {
this.birth = birth;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getIsonline() {
return isonline;
}
public void setIsonline(String isonline) {
this.isonline = isonline;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public Channel getChannel() {
return channel;
}
public void setChannel(Channel channel) {
this.channel = channel;
}
public Date getCreated_at() {
return created_at;
}
public void setCreated_at(Date created_at) {
this.created_at = created_at;
}
public Date getLast_login_at() {
return last_login_at;
}
public void setLast_login_at(Date last_login_at) {
this.last_login_at = last_login_at;
}
public Set<User> getFriends() {
return friends;
}
public void setFriends(Set<User> friends) {
this.friends = friends;
}
public Set<FeedBack> getFeedbacks() {
return feedbacks;
}
public void setFeedbacks(Set<FeedBack> feedbacks) {
this.feedbacks = feedbacks;
}
public Set<User> getBlacklist() {
return blacklist;
}
public void setBlacklist(Set<User> blacklist) {
this.blacklist = blacklist;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((client_id == null) ? 0 : client_id.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;
User other = (User) obj;
if (client_id == null) {
if (other.client_id != null)
return false;
} else if (!client_id.equals(other.client_id))
return false;
return true;
}
#Override
public String toString() {
return "User [client_id=" + client_id + ", username=" + username
+ ", labellist=" + labellist+ "]";
}
}
Just like this, User contains Topic, Label or other Entity in future. So I think that is not possible to remove this association. How could I improve my database access to improve access speed?
Another reason influncing the app speed may be my algorithm. I use bubble sort, selection sort, and quick sort. Each sort seems to cost little time on little data. But what if the concurrent occurs? 300 users may cost only 20 msec but 300 000 I couldn't imagine.
Here is my sort code:
private static List<Map<String,Object>> sortInteger(List<Map<String,Object>> list){
int index = 0;
int max = 0;
Map<String,Object> temp = new HashMap<String, Object>();
for(int i=0;i<list.size();i++){
for(int j=0;j<list.size()-i-1;j++){
Map<String,Object> pre = (Map<String, Object>) list.get(j);
Map<String,Object> next = (Map<String, Object>) list.get(j+1);
if((Integer)pre.get("sortnum")<(Integer)next.get("sortnum")){
temp = pre;
list.set(j, next);
list.set(j+1,pre);
}
}
}
return list;
}
So in terms of above, I need some suggestion to solve my question,either theory or code.

GAE data store not returning entities

I have used objectify to query the GAE datastore i have set up that has at least one entity in it but i keep getting the following response
200 OK
Show headers -
{
"kind": "call#resourcesItem",
"etag": "\"AiR-q6YO1YYMgAaz-ZfT_fl7oeY/pcKQAVaDylr_ZSckRfQAxsphOUU\""
}
here is what the objectify request looks like
#ApiMethod(name = "queryCalls", path = "queryCalls", httpMethod = HttpMethod.POST)
public List<Call> queryCalls()
{
Query<Call> query = ofy().load().type(Call.class).order("name");
return query.list();
}
Call is obviously the class of the entity that is being used.
Any solutions would be most appreciated
EDIT
Here is the call class for reference
package com.cms.log;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Index;
/* Patient Entity */
#Entity
public class Call {
#Id Long callId;
#Index String patientName;
#Index String doctor;
String address1;
String address2;
String address3;
String postCode;
String patientLocation;
#Index String symptoms;
Integer contactNumber;
#Index String callDateTime;
String currentStatus;
public Call(Long callId, String patientName, String doctor, String address1,
String address2, String address3, String postCode, String patientLocation, String symptoms,
Integer contactNumber, String callDateTime, String currentStatus)
{
this.callId = callId;
this.patientName = patientName;
this.doctor = doctor;
this.address1 = address1;
this.address2 = address2;
this.address3 = address3;
this.postCode = postCode;
this.patientLocation = patientLocation;
this.symptoms = symptoms;
this.contactNumber = contactNumber;
this.callDateTime = callDateTime;
this.currentStatus = currentStatus;
};
public Long getCallId() {
return callId;
}
public void setCallId(Long Id) {
this.callId = Id;
}
public String getPatientName() {
return patientName;
}
public void setPatientName(String patientName) {
this.patientName = patientName;
}
public String getDoctor() {
return doctor;
}
public void setDoctor(String doctor) {
this.doctor = doctor;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getAddress3() {
return address3;
}
public void setAddress3(String address3) {
this.address3 = address3;
}
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
public String getPatientLocation() {
return patientLocation;
}
public void setPatientLocation(String patientLocation) {
this.patientLocation = patientLocation;
}
public String getSymptoms() {
return symptoms;
}
public void setSymptoms(String symptoms) {
this.symptoms = symptoms;
}
public int getContactNumber() {
return contactNumber;
}
public void setContactNumber(int contactNumber) {
this.contactNumber = contactNumber;
}
public String getCallDateTime() {
return callDateTime;
}
public void setCallDateTime(String callDateTime) {
this.callDateTime = callDateTime;
}
public String getCurrentStatus() {
return currentStatus;
}
public void setCurrentStatus(String currentStatus) {
this.currentStatus = currentStatus;
}
}
As you have highlighted in your last comment, your #Entity classes must have a no-arg constructor in order for Objectify to be able to construct objects from Datastore entities.
Once that is sorted you will be able to order your results using #Indexed properties defined in your class.

I Can't Update table with ormlite android

The problem is that I have a table product and my update script doesn't work aparently. It allwas return false.
Product.class
#DatabaseTable(tableName = "Product")
public class Product {
#DatabaseField(index = true, generatedId = true)
private int productId;
#DatabaseField
private String name;
#DatabaseField
private int quantity;
//#DatabaseField(canBeNull = true)
//private Integer categorie;
//http://logic-explained.blogspot.com.ar/2011/12/using-ormlite-in-android-projects.html
#DatabaseField
private int categorie;
//#ForeignCollectionField
//private ForeignCollection<Categorie> itemsCategorie;
#DatabaseField
private String description;
#DatabaseField
private String photo;
Product() {
}
public Product(int productId, String name, int quantity, int categorie, String description, String photo) {
super();
this.productId = productId;
this.name = name;
this.quantity = quantity;
this.categorie = categorie;
this.description = description;
this.photo = photo;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return description;
}
public void setAddress(String address) {
this.description = address;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getCategorie() {
return categorie;
}
public void setCategorie(int categorie) {
this.categorie = categorie;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public CharSequence getDesc() {
return null;
}
}
my script updateProduct
public boolean updateProduct(Product p) {
boolean ret = false;
if (productDao != null) {
try {
productDao = getDao(Product.class);
UpdateBuilder<Product, Integer> updateBuilder = productDao
.updateBuilder();
updateBuilder.updateColumnValue("name", p.getName());
updateBuilder.updateColumnValue("quantity", p.getQuantity());
updateBuilder.updateColumnValue("categorie", p.getCategorie());
updateBuilder.updateColumnValue("description", p.getDesc());
updateBuilder.updateColumnValue("photo", p.getPhoto());
// but only update the rows where the description is some value
updateBuilder.where().eq("productId", p.getProductId());
// actually perform the update
String str = updateBuilder.prepareStatementString();
// UPDATE `Product` SET `name` = 'gcd' ,`quantity` = 1
// ,`categorie` = 1 ,`description` = ? ,`photo` = '' WHERE
// `productId` = 0
if (productDao.update(updateBuilder.prepare()) != 1) {
ret = false;
} else {
productDao.refresh(p);
ret = true;
}
} catch (Exception e) {
ret = false;
e.printStackTrace();
}
}
return ret;
}
then I call it with a function like this, but allways return false :(
public boolean updateProduct(Product p) {
boolean ret = false;
try {
ret = getHelper().updateProduct(p);
} catch (Exception e) {
e.printStackTrace();
ret =false;
}
return ret;
}
I can create and delete but I can not update . I tried everything.
If you please take a moment to answer my question I will appreciate.
for other developers, if you come face to face with a problem like this you should ensure the table must have an identity key.
#DatabaseTable(tableName = "User")
public class User {
#DatabaseField(generatedId = true)
public int id;
#DatabaseField
public String ServiceUserId;
#DatabaseField
public boolean IsActive;
#DatabaseField
public String FirstName;
#DatabaseField
public String LastName;
#DatabaseField
public String Key;
#DatabaseField
public String Email;
}
The solution was
Simply get the Instance of the object Product from the DB then modify to finaly send to the updateProduct method.
for example first I need to create any method first to get an objet by ID
// get the Instance calling to the getProductByID
Product p = getHelper().getProductByID(p.getId())
//modify any value of the product
p.setFirstName("asd");
//call the update
ret = getHelper().updateProduct(p);
then my objects is Updated.
Put attention for the object Id(should be the same) and use the natif function update(Product);
In your case, you must override equals and hashCode.

Categories

Resources