Cannot convert from List to List
When trying to use a list in my Test method, I am getting an error with adding a list to an ArrayList.
This is the code that the error is in:
#Test
public void testGetAllModules_OK() throws Exception {
List<Modules> modules = Arrays.asList(new Modules(1, "C02103", "Architecture", 1, true));
when(modRepo.findAll()).thenReturn(modules);
mockMvc.perform(get("/Modules"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].ModuleCode", is ("C02103")))
.andExpect(jsonPath("$[0].title", is ("Architecture")))
.andExpect(jsonPath("$.[0].semester", is (1)))
.andExpect(jsonPath("$[0].CoreModule", is(true)));
verify(modRepo, times(1)).findAll();
}
Here is the creation of Module class
#Entity
public class Modules implements Iterable<Modules> {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int ModuleId;
private String ModuleCode;
private String title;
private int semester;
private boolean CoreModule;
ArrayList<String> lecture = new ArrayList<String>();
ArrayList<String> mod = new ArrayList<String>();
public Modules(int ModuleId, String ModuleCode, String title, int semester, boolean CoreModule) {
this.ModuleId = ModuleId;
this.ModuleCode = ModuleCode;
this.title = title;
this.semester = semester;
this.CoreModule = CoreModule;
}
public Modules(String ModuleCode, String title, int semester, boolean CoreModule)
{
this.ModuleCode = ModuleCode;
this.title = title;
this.semester = semester;
this.CoreModule = CoreModule;
}
public Modules(String ModuleCode,String title, boolean CoreModule )
{
this.ModuleCode = ModuleCode;
this.title = title;
this.CoreModule = CoreModule;
}
public Modules()
{}
/*
* #ManyToOne(fetch = FetchType.EAGER, optional = false)
*
* #OneToMany(mappedBy = "module", fetch = FetchType.EAGER, cascade =
* CascadeType.ALL)
*/
public int getModuleId() {
return ModuleId;
}
public void setModuleId(int moduleId) {
ModuleId = moduleId;
}
public String getModuleCode() {
return ModuleCode;
}
public void setModuleCode(String moduleCode) {
ModuleCode = moduleCode;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getSemester() {
return semester;
}
public void setSemester(int semester) {
this.semester = semester;
}
public boolean isCoreModule() {
return CoreModule;
}
public void setCoreModule(boolean coreModule) {
CoreModule = coreModule;
}
#Override
public String toString() {
return "Modules [ModuleId=" + ModuleId + ", ModuleCode=" + ModuleCode + ", title=" + title + ", semester="
+ semester + ", CoreModule=" + CoreModule + "]";
}
}
Any help would be very appreciated, as I'm getting the same error with similar test methods
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'm making an application with JavaFX for an University Project to manage data in a mysql database and a List. I have to display data into a tableview. But a Table View allow only one POJO Class. How can I make join between two POJO Class? (like SQL Join function)
I tried to make a buffer class, but I don't understand how to do that and how to use it.
Controller class:
public class RevuesController implements Initializable, ChangeListener<Revue> {
---
#FXML private TableView<Revue> revuesTable;
#FXML private TableColumn<Revue, String> titleCol = new TableColumn<>("Titre");
#FXML private TableColumn<Revue, String> descCol = new TableColumn<>("Description");
#FXML private TableColumn<Revue, Double> priceCol = new TableColumn<>("Tarif numéro");
#FXML private TableColumn<Revue, String> visualCol = new TableColumn<>("Visuel");
#FXML private TableColumn<Periodicite, String> periodCol = new TableColumn<>("Périodicité");
#FXML private TableColumn<Integer, String> aboCol = new TableColumn<>("Abonnements en cours");
------
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
ObservableList<Revue> oListRevue = FXCollections.observableArrayList();
try {
oListRevue = FXCollections.observableArrayList(daos.getRevueDAO().getAll());
} catch (Exception e) {
System.out.println("Erreur de récupération des données de revue : " + e.getMessage());
e.printStackTrace();
}
this.titleCol.setCellValueFactory(new PropertyValueFactory<Revue, String>("titre"));
this.descCol.setCellValueFactory(new PropertyValueFactory<Revue, String>("description"));
this.priceCol.setCellValueFactory(new PropertyValueFactory<Revue, Double>("tarif_numero"));
this.visualCol.setCellValueFactory(new PropertyValueFactory<Revue, String>("visuel"));
this.periodCol.setCellValueFactory(new PropertyValueFactory<Periodicite, String>("libelle"));
this.aboCol.setCellValueFactory(new PropertyValueFactory<Integer, Integer>(""));
this.revuesTable.getColumns().setAll(titleCol, descCol, priceCol, visualCol, periodCol, aboCol);
FilteredList<Revue> fListRevue = new FilteredList<>(oListRevue);
this.revuesTable.getItems().addAll(fListRevue);
}
POJO Class Revue:
public class Revue {
private int id_revue;
private String titre;
private String description;
private double tarif_numero;
private String visuel;
private int id_periodicite;
public Revue() {}
public Revue(String titre, String description, double tarif_numero, String visuel, int id_periodicite) {
this.id_revue = -1;
this.titre = titre;
this.description = description;
this.tarif_numero = tarif_numero;
this.visuel = visuel;
this.id_periodicite = id_periodicite;
}
public Revue(int id_revue, String titre, String description, double tarif_numero, String visuel, int id_periodicite) {
this.id_revue = id_revue;
this.titre = titre;
this.description = description;
this.tarif_numero = tarif_numero;
this.visuel = visuel;
this.id_periodicite = id_periodicite;
}
public int getId_revue() {
return id_revue;
}
public void setId_revue(int id_revue) {
this.id_revue = id_revue;
}
public String getTitre() {
return titre;
}
public void setTitre(String titre) {
this.titre = titre;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getTarif_numero() {
return tarif_numero;
}
public void setTarif_numero(double tarif_numero) {
this.tarif_numero = tarif_numero;
}
public String getVisuel() {
return visuel;
}
public void setVisuel(String visuel) {
this.visuel = visuel;
}
public int getId_periodicite() {
return id_periodicite;
}
public void setId_periodicite(int id_periodicite) {
this.id_periodicite = id_periodicite;
}
POJO Class Periodicite:
public class Periodicite {
private int id;
private String libelle;
public Periodicite(int id, String libelle) {
this.id = id;
this.libelle = libelle;
}
public Periodicite(String libelle) {
this.id = -1;
this.libelle = libelle;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLibelle() {
return libelle;
}
public void setLibelle(String libelle) {
this.libelle = libelle;
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.sanu.siri.entity;
import javax.persistence.*;
import java.sql.Blob;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* #author Sanu AK
*/
#Entity
#Table(name = "Parts")
public class Parts implements SuperEntity {
#Id
#GeneratedValue(strategy = GenerationType.TABLE, generator = "map")
#TableGenerator(name = "map", table = "Id_Gen", pkColumnName = "Tables_Names", valueColumnName = "Gen_keys", pkColumnValue = "PartsDTO", initialValue = 1, allocationSize = 1)
private int id;
private String partName;
private String partNumber;
private String barCode;
private String brand;
private String partType;
private String country;
private String vehicleModel;
private String packSize;
private String location;
private String rackNo;
private String roq;
private String rql;
#Column(name = "imageUrl1")
private String imageUrl1;
#Column(name = "imageUrl2")
private String imageUrl2;
#Column(name = "imageUrl3")
private String imageUrl3;
#Column(name = "imageUrl4")
private String imageUrl4;
private Blob image;
private Blob image1;
private Blob image2;
private Blob image3;
private String warranty;
private Date adedDate;
#Enumerated(value = EnumType.STRING)
private Catogary catogary;
#ManyToMany(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
#JoinTable(name = "Parts_FuelType",
joinColumns = {#JoinColumn(name = "part_ID", referencedColumnName = "id")},
inverseJoinColumns = {#JoinColumn(name = "fuel_Type", referencedColumnName = "id")})
private List<FuelType> fuelTypes = new ArrayList<>();
#OneToMany(mappedBy = "parts", cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
private List<OrderDetails> orderDetail = new ArrayList<>();
#OneToMany(mappedBy = "parts", cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
#OrderBy("date DESC")
private List<Bulk> bulks = new ArrayList<>();
public Parts() {
}
public Parts(String partName, String partNumber, String barCode, String brand, String partType, String country, String vehicleModel, String packSize, String location, String rackNo, String roq, String rql, Blob image, Blob image1, Blob image2, Blob image3, String warranty, Date adedDate, Catogary catogary, List<FuelType> fuelTypes, List<OrderDetails> orderDetail, List<Bulk> bulks) {
this.partName = partName;
this.partNumber = partNumber;
this.barCode = barCode;
this.brand = brand;
this.partType = partType;
this.country = country;
this.vehicleModel = vehicleModel;
this.packSize = packSize;
this.location = location;
this.rackNo = rackNo;
this.roq = roq;
this.rql = rql;
this.image = image;
this.image1 = image1;
this.image2 = image2;
this.image3 = image3;
this.warranty = warranty;
this.adedDate = adedDate;
this.catogary = catogary;
this.fuelTypes = fuelTypes;
this.orderDetail = orderDetail;
this.bulks = bulks;
}
public Parts(int id, String partName, String partNumber, String barCode, String brand, String partType, String country, String vehicleModel, String packSize, String location, String rackNo, String roq, String rql, String imageUrl1, String imageUrl2, String imageUrl3, String imageUrl4, Blob image, Blob image1, Blob image2, Blob image3, String warranty, Date adedDate, Catogary catogary, List<FuelType> fuelTypes, List<OrderDetails> orderDetail, List<Bulk> bulks) {
this.setId(id);
this.partName = partName;
this.partNumber = partNumber;
this.barCode = barCode;
this.brand = brand;
this.partType = partType;
this.country = country;
this.vehicleModel = vehicleModel;
this.packSize = packSize;
this.location = location;
this.rackNo = rackNo;
this.roq = roq;
this.rql = rql;
this.imageUrl1 = imageUrl1;
this.imageUrl2 = imageUrl2;
this.imageUrl3 = imageUrl3;
this.imageUrl4 = imageUrl4;
this.image = image;
this.image1 = image1;
this.image2 = image2;
this.image3 = image3;
this.warranty = warranty;
this.adedDate = adedDate;
this.catogary = catogary;
this.fuelTypes = fuelTypes;
this.orderDetail = orderDetail;
this.bulks = bulks;
}
public String getImageUrl1() {
return imageUrl1;
}
public void setImageUrl1(String imageUrl1) {
this.imageUrl1 = imageUrl1;
}
public String getImageUrl2() {
return imageUrl2;
}
public void setImageUrl2(String imageUrl2) {
this.imageUrl2 = imageUrl2;
}
public String getImageUrl3() {
return imageUrl3;
}
public void setImageUrl3(String imageUrl3) {
this.imageUrl3 = imageUrl3;
}
public String getImageUrl4() {
return imageUrl4;
}
public void setImageUrl4(String imageUrl4) {
this.imageUrl4 = imageUrl4;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPartName() {
return partName;
}
public void setPartName(String partName) {
this.partName = partName;
}
public String getPartNumber() {
return partNumber;
}
public void setPartNumber(String partNumber) {
this.partNumber = partNumber;
}
public String getBarCode() {
return barCode;
}
public void setBarCode(String barCode) {
this.barCode = barCode;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getPartType() {
return partType;
}
public void setPartType(String partType) {
this.partType = partType;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getVehicleModel() {
return vehicleModel;
}
public void setVehicleModel(String vehicleModel) {
this.vehicleModel = vehicleModel;
}
public String getPackSize() {
return packSize;
}
public void setPackSize(String packSize) {
this.packSize = packSize;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getRackNo() {
return rackNo;
}
public void setRackNo(String rackNo) {
this.rackNo = rackNo;
}
public String getRoq() {
return roq;
}
public void setRoq(String roq) {
this.roq = roq;
}
public String getRql() {
return rql;
}
public void setRql(String rql) {
this.rql = rql;
}
public Blob getImage() {
return image;
}
public void setImage(Blob image) {
this.image = image;
}
public Blob getImage1() {
return image1;
}
public void setImage1(Blob image1) {
this.image1 = image1;
}
public Blob getImage2() {
return image2;
}
public void setImage2(Blob image2) {
this.image2 = image2;
}
public Blob getImage3() {
return image3;
}
public void setImage3(Blob image3) {
this.image3 = image3;
}
public String getWarranty() {
return warranty;
}
public void setWarranty(String warranty) {
this.warranty = warranty;
}
public Date getAdedDate() {
return adedDate;
}
public void setAdedDate(Date adedDate) {
this.adedDate = adedDate;
}
public Catogary getCatogary() {
return catogary;
}
public void setCatogary(Catogary catogary) {
this.catogary = catogary;
}
public List<FuelType> getFuelTypes() {
return fuelTypes;
}
public void setFuelTypes(List<FuelType> fuelTypes) {
this.fuelTypes = fuelTypes;
}
public List<OrderDetails> getOrderDetail() {
return orderDetail;
}
public void setOrderDetail(List<OrderDetails> orderDetail) {
this.orderDetail = orderDetail;
}
public List<Bulk> getBulks() {
return bulks;
}
public void setBulks(List<Bulk> bulks) {
this.bulks = bulks;
}
#Override
public String toString() {
return "Parts{" +
"id=" + id +
", partName='" + partName + '\'' +
", partNumber='" + partNumber + '\'' +
", barCode='" + barCode + '\'' +
", brand='" + brand + '\'' +
", partType='" + partType + '\'' +
", country='" + country + '\'' +
", vehicleModel='" + vehicleModel + '\'' +
", packSize='" + packSize + '\'' +
", location='" + location + '\'' +
", rackNo='" + rackNo + '\'' +
", roq='" + roq + '\'' +
", rql='" + rql + '\'' +
", image=" + image +
", image1=" + image1 +
", image2=" + image2 +
", image3=" + image3 +
", warranty='" + warranty + '\'' +
", adedDate=" + adedDate +
", catogary=" + catogary +
", fuelTypes=" + fuelTypes +
", orderDetail=" + orderDetail +
", bulks=" + bulks +
'}';
}
}
I have a problem about this row. Is there any way to limit those BulkList when we call this BulkList from Part.
#OrderBy("date DESC")
private List<Bulk> bulks = new ArrayList<>();
I mean like this
This is My Repo
public interface PartsRepo extends CrudRepository<Parts, Integer> {
Parts findPartsByBarCode(String barCode) throws Exception;
List<Parts> findPartsByPartNameContaining(String partName) throws Exception;
List<Parts> findPartsByPartNumberContaining(String partNumber) throws Exception;
Parts findPartsByPartNumber(String partNumber) throws Exception;
}
This is my Controller
#GetMapping(value = "/search")
public void searchParts(HttpServletRequest req) {
try {
return
Parts
p=partsService.searchParts(Integer.parseInt(req.getParameter("id")));
List<Bulk> bulkList=p.getBulks();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
I want to limit the bulkList results from the entity.. is there any way to do that..?
List<Bulk> bulkList=p.getBulks();
limit above list from the
#OrderBy("date DESC")
private List<Bulk> bulks = new ArrayList<>();
review
I have a problem about this row is there any way to limit those BulkList when we call this BulkList from Part.
I want to limit the bulkList results from the entity. Is there any way to do that?
#OneToMany(mappedBy = "bulk", cascade=CascadeType.PERSIST, fetch=LAZY)
#BatchSize(size=5)
private List<Bulk> bulks = new ArrayList<>();
You can do this way
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Here is my response. I don't know how to create Response Model for this type of response model
[{"id":"4","templateName":"FUP 100","dataUsage":"100 GB","price":236,"groupName":"","bandwidthName":""},{"id":"19","templateName":"FUP200","dataUsage":"200 GB","price":299.72,"groupName":"","bandwidthName":""}]
your retrofit call must be a list of your object not just the object
your object is like that
public class MyClass
{
private String id;
private String groupName;
private String price;
private String dataUsage;
private String bandwidthName;
private String templateName;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getGroupName ()
{
return groupName;
}
public void setGroupName (String groupName)
{
this.groupName = groupName;
}
public String getPrice ()
{
return price;
}
public void setPrice (String price)
{
this.price = price;
}
public String getDataUsage ()
{
return dataUsage;
}
public void setDataUsage (String dataUsage)
{
this.dataUsage = dataUsage;
}
public String getBandwidthName ()
{
return bandwidthName;
}
public void setBandwidthName (String bandwidthName)
{
this.bandwidthName = bandwidthName;
}
public String getTemplateName ()
{
return templateName;
}
public void setTemplateName (String templateName)
{
this.templateName = templateName;
}
#Override
public String toString()
{
return "MyClass [id = "+id+", groupName = "+groupName+", price = "+price+", dataUsage = "+dataUsage+", bandwidthName = "+bandwidthName+", templateName = "+templateName+"]";
}
}
kotlin :
class MyClass {
var id:String
var groupName:String
var price:String
var dataUsage:String
var bandwidthName:String
var templateName:String
public override fun toString():String {
return "MyClass [id = " + id + ", groupName = " + groupName + ", price = " + price + ", dataUsage = " + dataUsage + ", bandwidthName = " + bandwidthName + ", templateName = " + templateName + "]"
}
}
there are online tools to help you http://pojo.sodhanalibrary.com/
public class Response {
#SerializedName("id")
#Expose
private String id;
#SerializedName("templateName")
#Expose
private String templateName;
#SerializedName("dataUsage")
#Expose
private String dataUsage;
#SerializedName("price")
#Expose
private Double price;
#SerializedName("groupName")
#Expose
private String groupName;
#SerializedName("bandwidthName")
#Expose
private String bandwidthName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTemplateName() {
return templateName;
}
public void setTemplateName(String templateName) {
this.templateName = templateName;
}
public String getDataUsage() {
return dataUsage;
}
public void setDataUsage(String dataUsage) {
this.dataUsage = dataUsage;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getBandwidthName() {
return bandwidthName;
}
public void setBandwidthName(String bandwidthName) {
this.bandwidthName = bandwidthName;
}
}
Then Create ArrayList because your response start with array :
#Headers("Content-Type:application/json")
#GET("your_api")
Call<ArrayList<Response>> api();
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;
}