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.
Related
I want to store class Reservation that a user makes when going to a cinema to watch a movie and I can't figure out how to convert it so that room can store it in the data base.
Errors appear for members: places and codeQR.
Class Reservation:
#Entity(tableName = "reservations", foreignKeys = #ForeignKey(entity = UtilizatorMADA.class, parentColumns = "id", childColumns = "idUser"))
public class Reservation implements Serializable {
#PrimaryKey(autoGenerate = true)
private long idReservation;
private long idUser;
#Embedded private Film film;
private Time startTime;
private List<Integer> places;
private Bitmap codeQR;
#Ignore
public Reservation(){}
public Reservation(long idReservation, long idUser, Film film, Time startTime, List<Integer> places, Bitmap codeQR) {
this.idReservation = idReservation;
this.idUser = idUser;
this.film = film;
this.startTime = startTime;
this.places = places;
this.codeQR = codeQR;
}
#Ignore
public Reservation(long idUser, Film film, Time startTime, List<Integer> places, Bitmap codeQR) {
this.idUser = idUser;
this.film = film;
this.startTime = startTime;
this.places = places;
this.codeQR = codeQR;
}
#Ignore
public Reservation(Film film, Time startTime, List<Integer> places, Bitmap codeQR) {
this.film = film;
this.startTime = startTime;
this.places = places;
this.codeQR = codeQR;
}
public long getIdReservation() {
return idReservation;
}
public void setIdReservation(long idReservation) {
this.idReservation = idReservation;
}
public long getIdUser() {
return idUser;
}
public void setIdUser(long idUser) {
this.idUser = idUser;
}
public void setPlaces(List<Integer> places) {
this.places = places;
}
public Film getFilm() {
return film;
}
public void setFilm(Film film) {
this.film = film;
}
public Time getStartTime() {
return startTime;
}
public void setStartTime(Time startTime) {
this.startTime = startTime;
}
public Bitmap getCodeQR() {
return codeQR;
}
public void setCodeQR(Bitmap codeQR) {
this.codeQR = codeQR;
}
public List<Integer> getPlaces() { return places; }
#Override
public String toString() {
return "Reservation{" +
"film=" + film +
", startTime=" + startTime +
", codeQR='" + codeQR + '\'' +
'}';
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Reservation that = (Reservation) o;
return Objects.equals(film, that.film) &&
Objects.equals(startTime, that.startTime) &&
Objects.equals(places, that.places);
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public int hashCode() {
return Objects.hash(film, startTime, places);
}
}
Class Film:
#Entity(tableName = "films")
public class Film implements Serializable {
#PrimaryKey(autoGenerate = true)
private int idFilm;
private String title;
private String genre;
private String description;
private double rating;
private int imagePath;
private boolean isFavorite;
public Film(int idFilm, String title, String genre, String description, double rating, int imagePath, boolean isFavorite) {
this.idFilm = idFilm;
this.title = title;
this.genre = genre;
this.description = description;
this.rating = rating;
this.imagePath = imagePath;
this.isFavorite = isFavorite;
}
#Ignore
public Film(String title, String genre, String description, double rating, int imagePath) {
this.title = title;
this.genre = genre;
this.description = description;
this.rating = rating;
this.imagePath = imagePath;
isFavorite = false;
}
#Ignore
public Film(String title) {
this.title = title;
}
public int getIdFilm() {
return idFilm;
}
public void setIdFilm(int idFilm) {
this.idFilm = idFilm;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
public int getImagePath() {
return imagePath;
}
public void setImagePath(int imagePath) {
this.imagePath = imagePath;
}
public boolean isFavorite() {
return isFavorite;
}
public void setFavorite(boolean favorite) {
isFavorite = favorite;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Film film = (Film) o;
return Objects.equals(title, film.title);
}
#Override
public int hashCode() {
return Objects.hash(title);
}
}
I also get the following error by the ReservationOfMoviesDao, which may or may not be related. The queries affected are: getReservationOfMoviesByUserId(long id), getReservationOfMovies() and getReservationOfMoviesByRservationId(long id);
error: The columns returned by the query does not have the fields [idFilm] in com.example.cinemaapp.model.ReservationMovie even though they are annotated as non-null or primitive. Columns returned by the query: [idReservation,idUser,film,startTime,places,codeQR]
Interface ReservationOfMoviesDao:
#Dao
public interface ReservationOfMoviesDao {
#Insert(onConflict = OnConflictStrategy.IGNORE)
void insert(ReservationMovie rm);
#Transaction
#Query("SELECT * FROM reservations where idUser = :id")
List<ReservationMovie> getReservationOfMoviesByUserId(long id);
#Transaction
#Query("SELECT * FROM reservations")
List<ReservationMovie> getReservationOfMovies();
#Transaction
#Query("SELECT * FROM reservations where idReservation = :id")
ReservationMovie getReservationOfMoviesByReservationId(long id);
}
If you could help me out please, I'd appreciate it.
You cant use entities inside other entities (e.g. Film in Reservation). You should either use "relationships between entities" or try "Embedded" annotation.
Reffer to this link for more info.
i have this function to query in hibernate:
public List<TransactionQR> getAllTransaction() throws HibernateException {
return this.session.createQuery("SELECT id FROM TransactionQR").list();
}
then is success to show the data like this in html:
[2, 3]
but when i add more column in SELECT like this:
public List<TransactionQR> getAllTransaction() throws HibernateException {
return this.session.createQuery("SELECT id, codeqr FROM TransactionQR").list();
}
the result show like this:
[Ljava.lang.Object;#25026824, [Ljava.lang.Object;#170b75f9]
what is Ljava.lang.Object;#25026824 ? is return object, can i handle it to convert from list to json ?
i have model TransactionQR.java :
public class TransactionQR implements Serializable {
private Long id;
private String codeqr;
private Date approvaltime;
private String merchant;
private String code_merchant;
private Long amount;
private Long saldoawal;
private Integer tracenumber;
private String state;
private Date createdate;
private Batch batch;
public TransactionQR() {
}
public TransactionQR(Long id, String codeqr, Date approvaltime, String merchant, String code_merchant, Long amount,
Long saldoawal, Integer tracenumber, String state, Date createdate, Batch batch) {
super();
this.id = id;
this.codeqr = codeqr;
this.approvaltime = approvaltime;
this.merchant = merchant;
this.code_merchant = code_merchant;
this.amount = amount;
this.saldoawal = saldoawal;
this.tracenumber = tracenumber;
this.state = state;
this.createdate = createdate;
this.batch = batch;
}
public Long getId() {
return id;
}
public Date getApprovalTime() {
return approvaltime;
}
public Batch getBatch() {
return batch;
}
public void setBatch(Batch batch) {
this.batch = batch;
}
public void setApprovalTime(Date approvalTime) {
this.approvaltime = approvalTime;
}
public void setId(Long id) {
this.id = id;
}
public Date getApprovaltime() {
return approvaltime;
}
public void setApprovaltime(Date approvaltime) {
this.approvaltime = approvaltime;
}
public String getCodeqr() {
return codeqr;
}
public void setCodeqr(String codeqr) {
this.codeqr = codeqr;
}
public String getMerchant() {
return merchant;
}
public void setMerchant(String merchant) {
this.merchant = merchant;
}
public String getCode_merchant() {
return code_merchant;
}
public void setCode_merchant(String code_merchant) {
this.code_merchant = code_merchant;
}
public Long getAmount() {
return amount;
}
public void setAmount(Long amount) {
this.amount = amount;
}
public Long getSaldoawal() {
return saldoawal;
}
public void setSaldoawal(Long saldoawal) {
this.saldoawal = saldoawal;
}
public Integer getTracenumber() {
return tracenumber;
}
public void setTracenumber(Integer tracenumber) {
this.tracenumber = tracenumber;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Date getCreatedate() {
return createdate;
}
public void setCreatedate(Date createdate) {
this.createdate = createdate;
}
}
the result is i want to show all data from database in list
In second case, since you are selecting two attributes, that is why session.createQuery("").list returns a list of object array(List<Object[]>) . At each index of list you will find an object array. Each array will have two indexes. First index will provide id while the second one would provide codeqr. So, basically you need to iterate over the list. Then fetch each value individually like arr[0], arr[1]..
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.
I want update only not null field. I have some class like below
#DatabaseTable
public class ClickCount implements Serializable {
private static final long serialVersionUID = -6582623980712135028L;
public static final String DATE_FIELD_NAME = "lastClickDate";
#DatabaseField(generatedId = true)
private Integer id;
#DatabaseField(columnName = DATE_FIELD_NAME)
private Date lastClickDate;
#DatabaseField(index = true)
private String name;
#DatabaseField
private String description;
#DatabaseField
private int value;
#DatabaseField(canBeNull = true, foreign = true)
private ClickGroup group;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public ClickGroup getGroup() {
return group;
}
public void setGroup(ClickGroup group) {
this.group = group;
}
public Date getLastClickDate() {
return lastClickDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
/**
* This updates the value and adjusts the date.
*/
public void changeValue(int value) {
this.value = value;
this.lastClickDate = new Date();
}
#Override
public String toString() {
return name + " " + value;
}
}
I get some json and parse with ClickCount class, but some field may be null. When I update data in DB null field writing into DB. How write only not null field?
Updating data below
Dao<ClickCount, Integer> dao = getHelper().getClickDao();
ClickCount clickCountInDb = dao.queryForAll().get(0);
ClickCount clickCountFromServer = getFromServer();
clickCountFromServer.setId(clickCountInDb.getId());
dao.update(clickCountFromServer);
You have update each field manually after checking if its null or not. After that just update your fetched entity like this:
Dao<ClickCount, Integer> dao = getHelper().getClickDao();
ClickCount clickCountFromServer = getFromServer();
ClickCount clickCountInDb = dao.queryForId(clickCountInDb.getId()); // query for specific item. After this you should check if the query was succesful.
if (clickCountFromServer.getLastClickDate() != null)
{
clickCountInDb.setLastClickDate(clickCountFromServer.getLastClickDate());
}
if (clickCountFromServer.getName() != null)
{
clickCountInDb.setName(clickCountFromServer.getName());
}
// and so on for all fields
// after you set not null properties on the object clickCountInDb you have to propagate changes back to the database:
dao.update(clickCountInDb);
i have a class where i am inserting data into a array-list based on the id provided.
I am passing a bookId into my class and by comparing bookid i am get a book object. And after getting that object(book) ,am inserting into my arraylist.
Now I do't want to insert same data more then once. If a same bookid passes in the class then only it should store once.
i am storing my arraylist into session.
please check my code. And suggest me a solution for my problem.How to avoid duplicate insertion of data into my arraylist?
AddBookToSession.java
..................
...................
...................
private Integer bid; HttpServletRequest request = ServletActionContext.getRequest();
private Map<String, Object> session;
List<Bookdetails> books = new ArrayList<Bookdetails>();
private BookdetailsDAO dao = new BookdetailsDAO();
public String execute()
{
String bookid = request.getParameter("bid");
Bookdetails book = dao.listBookDetailsById(Integer.parseInt(bookid));
int checkduplicate=1;
//getting list from session to compare with the id
List list = (List) session.get( VisionBooksConstants.USER );
Iterator itr = list.iterator();
int bidd=0;
while(itr.hasNext())
{
Bookdetails bks=(Bookdetails) itr.next();
bidd=bks.getId(); //getting bookid from arraylist,which was stored in session
if (bidd==Integer.parseInt(bookid))
{
checkduplicate=0; //returns 0 ,so that i can compare it below to avoid duplicate data
}
}
//
if (book != null && checkduplicate==1 )
{
books = sessionBooks();
HttpServletRequest request = ServletActionContext.getRequest();
books.add(book);
System.out.println("books size"+books.size());
}
return SUCCESS;
}
........................
......................
Alternative solution
HashSet() update
public String execute()
{ HashSet<Bookdetails> books = new HashSet<Bookdetails>();
String bookid = request.getParameter("bid");
Bookdetails book = dao.listBookDetailsById(Integer.parseInt(bookid));
books = (HashSet<Bookdetails>) session.get(BillTransactionBooksConstants.BOK);
if ( books == null ) books = new HashSet<Bookdetails>();
boolean already_exists = false;
books.add(book);
System.out.println("books size"+books.size());
session.put(BillTransactionBooksConstants.BOK,books);
return SUCCESS;
}
Bookdetails.java(Pojo)
package v.esoft.pojos;
// Generated Nov 5, 2012 9:37:14 PM by Hibernate Tools 3.4.0.CR1
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* Bookdetails generated by hbm2java
*/
#Entity
#Table(name = "bookdetails", catalog = "vbsoftware")
public class Bookdetails implements java.io.Serializable {
private Integer id;
private String isbn;
private String bookTitile;
private String authFirstname;
private String authLastname;
private String editionYear;
private Integer subjectId;
private Integer coverId;
private Integer languageId;
private String publisherName;
private Integer editionId;
private Float price;
private String quantity;
private String description;
private Integer locationId;
private String remarks;
private String img1;
private String img2;
private String videoUrl;
private Integer createrId;
private Date createdDate;
private Integer updateId;
private Date updatedDate;
public Bookdetails() {
}
public Bookdetails(String isbn, String bookTitile, String authFirstname,
String authLastname, String editionYear, Integer subjectId,
Integer coverId, Integer languageId, String publisherName,
Integer editionId, Float price, String quantity,
String description, Integer locationId, String remarks,
String img1, String img2, String videoUrl, Integer createrId,
Date createdDate, Integer updateId, Date updatedDate) {
this.isbn = isbn;
this.bookTitile = bookTitile;
this.authFirstname = authFirstname;
this.authLastname = authLastname;
this.editionYear = editionYear;
this.subjectId = subjectId;
this.coverId = coverId;
this.languageId = languageId;
this.publisherName = publisherName;
this.editionId = editionId;
this.price = price;
this.quantity = quantity;
this.description = description;
this.locationId = locationId;
this.remarks = remarks;
this.img1 = img1;
this.img2 = img2;
this.videoUrl = videoUrl;
this.createrId = createrId;
this.createdDate = createdDate;
this.updateId = updateId;
this.updatedDate = updatedDate;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
//###########################################################################
// FOR HASHSETS EQUALS
//###########################################################################
public Bookdetails(int i){ id = i; }
public boolean equals(Object obj){
System.err.println("called"); // Never happens
return id == ((Bookdetails)obj).id;
}
#Column(name = "isbn", length = 90)
public String getIsbn() {
return this.isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
#Column(name = "book_titile")
public String getBookTitile() {
return this.bookTitile;
}
public void setBookTitile(String bookTitile) {
this.bookTitile = bookTitile;
}
#Column(name = "auth_firstname", length = 120)
public String getAuthFirstname() {
return this.authFirstname;
}
public void setAuthFirstname(String authFirstname) {
this.authFirstname = authFirstname;
}
#Column(name = "auth_lastname", length = 120)
public String getAuthLastname() {
return this.authLastname;
}
public void setAuthLastname(String authLastname) {
this.authLastname = authLastname;
}
#Column(name = "edition_year", length = 20)
public String getEditionYear() {
return this.editionYear;
}
public void setEditionYear(String editionYear) {
this.editionYear = editionYear;
}
#Column(name = "subject_id")
public Integer getSubjectId() {
return this.subjectId;
}
public void setSubjectId(Integer subjectId) {
this.subjectId = subjectId;
}
#Column(name = "cover_id")
public Integer getCoverId() {
return this.coverId;
}
public void setCoverId(Integer coverId) {
this.coverId = coverId;
}
#Column(name = "language_id")
public Integer getLanguageId() {
return this.languageId;
}
public void setLanguageId(Integer languageId) {
this.languageId = languageId;
}
#Column(name = "publisher_name", length = 70)
public String getPublisherName() {
return this.publisherName;
}
public void setPublisherName(String publisherName) {
this.publisherName = publisherName;
}
#Column(name = "edition_id")
public Integer getEditionId() {
return this.editionId;
}
public void setEditionId(Integer editionId) {
this.editionId = editionId;
}
#Column(name = "price", precision = 12, scale = 0)
public Float getPrice() {
return this.price;
}
public void setPrice(Float price) {
this.price = price;
}
#Column(name = "quantity", length = 40)
public String getQuantity() {
return this.quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
#Column(name = "description", length = 65535)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "location_id")
public Integer getLocationId() {
return this.locationId;
}
public void setLocationId(Integer locationId) {
this.locationId = locationId;
}
#Column(name = "remarks", length = 65535)
public String getRemarks() {
return this.remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
#Column(name = "img1")
public String getImg1() {
return this.img1;
}
public void setImg1(String img1) {
this.img1 = img1;
}
#Column(name = "img2")
public String getImg2() {
return this.img2;
}
public void setImg2(String img2) {
this.img2 = img2;
}
#Column(name = "video_url", length = 65535)
public String getVideoUrl() {
return this.videoUrl;
}
public void setVideoUrl(String videoUrl) {
this.videoUrl = videoUrl;
}
#Column(name = "creater_id")
public Integer getCreaterId() {
return this.createrId;
}
public void setCreaterId(Integer createrId) {
this.createrId = createrId;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created_date", length = 19)
public Date getCreatedDate() {
return this.createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
#Column(name = "update_id")
public Integer getUpdateId() {
return this.updateId;
}
public void setUpdateId(Integer updateId) {
this.updateId = updateId;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "updated_date", length = 19)
public Date getUpdatedDate() {
return this.updatedDate;
}
public void setUpdatedDate(Date updatedDate) {
this.updatedDate = updatedDate;
}
}
How to avoid duplicate insertion of data into my arraylist?
Use a Set instead.
Also, make sure you are implementing equals and hashcode correctly.
EDITED: It should work now.
public String execute()
{
String bookid = request.getParameter("bid");
Bookdetails book = dao.listBookDetailsById(Integer.parseInt(bookid));
books = (ArrayList) session.get( VisionBooksConstants.USER );
if ( books == null ) books = new ArrayList<Bookdetails>();
boolean already_exists = false;
for ( Bookdetails b : books ) {
if ( b.getID().equals(bookid) ) {
already_exists = true; break;
}
}
if (book != null && !already_exists )
{
books.add(book);
System.out.println("books size"+books.size());
session.put(VisionBooksConstants.USER,books);
}
return SUCCESS;
}