AWS lambda java request POJO attributes null - java

I am just creating a handler in java which accepts a POJO called as ProductsModel.
public ProductsResponseObject handleRequest(ProductsRequestObject productsRequestObject, Context arg1) {
ProductsResponseObject respObj = null;
ProductsService productsService = new ProductsService();
arg1.getLogger().log("inside ProductsHandler.handleRequest with reqtype " + productsRequestObject.getReqType());
switch (productsRequestObject.getReqType()) {
case 0:
respObj = productsService.addProduct(productsRequestObject);
break;
case 1:
respObj = productsService.updateProduct(productsRequestObject);
break;
default:
break;
}
return respObj;
}
But here inside the handler method, the attributes of request, reqType and productModel are null. Not sure y?
Request POJO:
public class ProductsRequestObject {
private int reqType;
private ProductsModel productsModel;
public int getReqType() {
return reqType;
}
public void setReqType(int reqType) {
this.reqType = reqType;
}
public ProductsModel getProductsModel() {
return productsModel;
}
public void setProductsModel(ProductsModel productsModel) {
this.productsModel = productsModel;
}
}
Model POJO:
public class ProductsModel {
private String id;
private String dealerMobNumber;
private String name;
private String description;
private String price;
#DynamoDBHashKey(attributeName = "Id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDealerMobNumber() {
return dealerMobNumber;
}
public void setDealerMobNumber(String dealerMobNumber) {
this.dealerMobNumber = dealerMobNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}

Related

Parcelable Implementation for Custom Objects

I have 3 POJO types: a Recipe, which contains ingredients, and then the ingredients contain steps. Below is my setup, I am trying to implement Parcelable and cannot determine the appropriate read and write methods:
Recipe.Java:
public class Recipe implements Parcelable {
protected List<Ingredients> ingredients;
private String id;
private String servings;
private String name;
private String image;
private List<Steps> steps;
protected Recipe(Parcel in) {
in.createTypedArray(CREATOR.createFromParcel(Ingredients));
in.createTypedArray(Ingredients.);
id = in.readString();
servings = in.readString();
name = in.readString();
image = in.readString();
steps = in.readArrayList(ClassLoader.getSystemClassLoader());
}
public static final Creator<Ingredients> CREATOR = new Creator<Ingredients>() {
#Override
public Ingredients createFromParcel(Parcel parcel) {
return new Ingredients(parcel);
}
#Override
public Ingredients[] newArray(int i) {
return new Ingredients[0];
}
}
public static final Creator<Recipe> CREATOR = new Creator<Recipe>() {
#Override
public Recipe createFromParcel(Parcel in) {
return new Recipe(in);
}
#Override
public Recipe[] newArray(int size) {
return new Recipe[size];
}
};
public List<Ingredients> getIngredients() {
return ingredients;
}
public void setIngredients(List<Ingredients> ingredients) {
this.ingredients = ingredients;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getServings() {
return servings;
}
public void setServings(String servings) {
this.servings = servings;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public List<Steps> getSteps() {
return steps;
}
public void setSteps(List<Steps> steps) {
this.steps = steps;
}
#Override
public String toString() {
return "ClassPojo [ingredients = " + ingredients + ", id = " + id + ", servings = " + servings + ", name = " + name + ", image = " + image + ", steps = " + steps + "]";
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(id);
parcel.writeString(servings);
parcel.writeString(name);
parcel.writeString(image);
}
}
Ingredients.Java:
public class Ingredients {
private String measure;
private String ingredient;
private String quantity;
public Ingredients(Parcel parcel) {
}
public String getMeasure ()
{
return measure;
}
public void setMeasure (String measure)
{
this.measure = measure;
}
public String getIngredient ()
{
return ingredient;
}
public void setIngredient (String ingredient)
{
this.ingredient = ingredient;
}
public String getQuantity ()
{
return quantity;
}
public void setQuantity (String quantity)
{
this.quantity = quantity;
}
#Override
public String toString()
{
return "ClassPojo [measure = "+measure+", ingredient = "+ingredient+", quantity = "+quantity+"]";
}
}
Steps.Java:
public class Steps {
private String id;
private String shortDescription;
private String description;
private String videoURL;
private String thumbnailURL;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getShortDescription ()
{
return shortDescription;
}
public void setShortDescription (String shortDescription)
{
this.shortDescription = shortDescription;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getVideoURL ()
{
return videoURL;
}
public void setVideoURL (String videoURL)
{
this.videoURL = videoURL;
}
public String getThumbnailURL ()
{
return thumbnailURL;
}
public void setThumbnailURL (String thumbnailURL)
{
this.thumbnailURL = thumbnailURL;
}
#Override
public String toString()
{
return "ClassPojo [id = "+id+", shortDescription = "+shortDescription+", description = "+description+", videoURL = "+videoURL+", thumbnailURL = "+thumbnailURL+"]";
}
}
I suggest you to use third party library such as Paperparcel to reduce boilerplate.
Sample of usage:
#PaperParcel // (1)
public final class User implements Parcelable {
public static final Creator<User> CREATOR = PaperParcelUser.CREATOR; // (2)
long id; // (3)
String firstName; // (3)
String lastName; // (3)
#Override public int describeContents() {
return 0;
}
#Override public void writeToParcel(Parcel dest, int flags) {
PaperParcelUser.writeToParcel(this, dest, flags); // (4)
}
}

null response usin Retrofit Library in android

Here is my JSONArray Response from Web service:
And Class Java :
public class Product {
private int id,price,discount;
private String name,image,description,discount_type,discount_exp;
#SerializedName("products")
private List<Product> products;
public Product()
{
}
}
response is null
Your POJO class is wrong
Try this
public class Products_Main
{
#SerializedName("current_page")
int current_page;
#SerializedName("data")
private List<Product> products;
public int getCurrent_page() {
return current_page;
}
public void setCurrent_page(int current_page) {
this.current_page = current_page;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
and
class Product {
#SerializedName("id")
private int id;
#SerializedName("price")
int price;
#SerializedName("discount")
int discount;
#SerializedName("name")
private String name;
#SerializedName("image")
private String image;
#SerializedName("description")
private String description;
#SerializedName("discount_type")
private String discount_type;
#SerializedName("discount_exp")
private String discount_exp;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getDiscount() {
return discount;
}
public void setDiscount(int discount) {
this.discount = discount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDiscount_type() {
return discount_type;
}
public void setDiscount_type(String discount_type) {
this.discount_type = discount_type;
}
public String getDiscount_exp() {
return discount_exp;
}
public void setDiscount_exp(String discount_exp) {
this.discount_exp = discount_exp;
}
}
Any null data happens when the parsing failed.
This is the Java for the response you've shown
public class ProductResponse {
ProductPage products;
}
public class ProductPage {
int current_page;
#SerializedName("data")
private List<Product> products;
}
public class Product {
private int id,price,discount;
private String name,image,description,discount_type,discount_exp;
public Product() { }
}
You have to change like it will work
public class ProductModel {
private int current_page;
private ArrayList<DataModel> data = new ArrayList<>();
public int getCurrent_page() {
return current_page;
}
public void setCurrent_page(int current_page) {
this.current_page = current_page;
}
public ArrayList<DataModel> getData() {
return data;
}
public void setData(ArrayList<DataModel> data) {
this.data = data;
}
private class DataModel{
private int id,price,discount,shop_id,vote_id,vedeo_id,status;
private String name,image,description,discount_type,discount_exp,created_at,updated_at;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getDiscount() {
return discount;
}
public void setDiscount(int discount) {
this.discount = discount;
}
public int getShop_id() {
return shop_id;
}
public void setShop_id(int shop_id) {
this.shop_id = shop_id;
}
public int getVote_id() {
return vote_id;
}
public void setVote_id(int vote_id) {
this.vote_id = vote_id;
}
public int getVedeo_id() {
return vedeo_id;
}
public void setVedeo_id(int vedeo_id) {
this.vedeo_id = vedeo_id;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDiscount_type() {
return discount_type;
}
public void setDiscount_type(String discount_type) {
this.discount_type = discount_type;
}
public String getDiscount_exp() {
return discount_exp;
}
public void setDiscount_exp(String discount_exp) {
this.discount_exp = discount_exp;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
}
}
The issue is that the products are contained within the data field of the JSON response. Retrofit doesn't know this so it can't deserialize the response into a Product array.
You should use it like that
=>Main API Model Class
public class APIResult {
#SerializedName("products")
private ProductModelClass products;
public ProductModelClass getProducts() {
return products;
}
public void setProducts(ProductModelClass products) {
this.products = products;
}
}
=>For data and current page model class
public class ProductModelClass {
#SerializedName("current_page")
private int current_page;
#SerializedName("data")
private ArrayList<ProductDataModel> data;
public int getCurrent_page() {
return current_page;
}
public void setCurrent_page(int current_page) {
this.current_page = current_page;
}
public ArrayList<ProductDataModel> getData() {
return data;
}
public void setData(ArrayList<ProductDataModel> data) {
this.data = data;
}
}
=>For Details of products Data
public class ProductDataModel {
#SerializedName("id")
private int id;
#SerializedName("name")
private String name;
#SerializedName("image")
private String image;
#SerializedName("description")
private String description;
#SerializedName("price")
private int price;
#SerializedName("discount")
private int discount;
#SerializedName("shop_id")
private int shop_id;
#SerializedName("discount_type")
private String discount_type;
#SerializedName("discount_exp")
private String discount_exp;
#SerializedName("discount_limit")
private String discount_limit;
#SerializedName("vote_id")
private String vote_id;
#SerializedName("video_id")
private String video_id;
#SerializedName("status")
private String status;
#SerializedName("created_at")
private String created_at;
#SerializedName("updated_at")
private String updated_at;
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 getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getDiscount() {
return discount;
}
public void setDiscount(int discount) {
this.discount = discount;
}
public int getShop_id() {
return shop_id;
}
public void setShop_id(int shop_id) {
this.shop_id = shop_id;
}
public String getDiscount_type() {
return discount_type;
}
public void setDiscount_type(String discount_type) {
this.discount_type = discount_type;
}
public String getDiscount_exp() {
return discount_exp;
}
public void setDiscount_exp(String discount_exp) {
this.discount_exp = discount_exp;
}
public String getDiscount_limit() {
return discount_limit;
}
public void setDiscount_limit(String discount_limit) {
this.discount_limit = discount_limit;
}
public String getVote_id() {
return vote_id;
}
public void setVote_id(String vote_id) {
this.vote_id = vote_id;
}
public String getVideo_id() {
return video_id;
}
public void setVideo_id(String video_id) {
this.video_id = video_id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
}

Deserialization got null String should have value

I got a quite weird problem, forgive me if it became an attention problem, but I'm running on coffee right now!
I have this Json:
[
{
"address":"RS 239, Km 18,2 nÂș 4631 - Novo Hamburgo",
"closingTime":"06:00",
"description":"Curta como quiser.",
"distance":"6,328.35 km",
"iconUrl":"~\/Images\/Establishment\/Bar Alternativo.png",
"idEstablishment":5,
"name":"Bar Alternativo",
"openingTime":"22:30",
"phone":"(51) 3778-1820",
"type":"Casa Noturna \/ Balada"
}
]
And when I try deserialize this one using this code:
public static ArrayList<Establishment> serializeEstablishmentList(String json) {
ObjectMapper mapper = new ObjectMapper();
ArrayList<Establishment> establishments = null;
try {
establishments = mapper.readValue(json, new TypeReference<List<Establishment>>(){});
} catch (IOException e) {
e.printStackTrace();
}
return establishments;
}
My distance property do not get its value, image from debugger:
here goes my Establishment class:
public class Establishment {
private long idEstablishment;
private Drawable icon;
private String iconUrl;
private String name;
private String type;
private boolean workingStatus;
private String openingTime;
private String closingTime;
private String distance;
private String phone;
private String description;
private String address;
public Establishment() {
}
public Establishment(long idEstablishment, Drawable icon, String iconUrl, String name, String type, boolean workingStatus, String openingTime, String closingTime, String distance, String phone, String description, String address) {
this.idEstablishment = idEstablishment;
this.icon = icon;
this.iconUrl = iconUrl;
this.name = name;
this.type = type;
this.workingStatus = workingStatus;
this.openingTime = openingTime;
this.closingTime = closingTime;
this.distance = distance;
this.phone = phone;
this.description = description;
this.address = address;
}
public Establishment(long id, Drawable icon, String name, boolean workingStatus, String openingTime,
String closingTime, String distance) {
this.idEstablishment = id;
this.icon = icon;
this.name = name;
this.workingStatus = workingStatus;
this.openingTime = openingTime;
this.closingTime = closingTime;
this.distance = distance;
}
public long getIdEstablishment() {
return idEstablishment;
}
public void setIdEstablishment(long idEstablishment) {
this.idEstablishment = idEstablishment;
}
public Drawable getIcon() {
return icon;
}
public void setIcon(Drawable icon) {
this.icon = icon;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean getWorkingStatus() {
return workingStatus;
}
public String getWorkingStatusLabel(){
return workingStatus ? "Aberto" : "Fechado";
}
public void setWorkingStatus(boolean workingStatus) {
this.workingStatus = workingStatus;
}
public String getOpeningTime() {
return openingTime;
}
public void setOpeningTime(String openingTime) {
this.openingTime = openingTime;
}
public String getClosingTime() {
return closingTime;
}
public void setClosingTime(String closingTime) {
this.closingTime = closingTime;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = this.distance;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isWorkingStatus() {
return workingStatus;
}
public String getIconUrl() {
return iconUrl;
}
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Any idea?
Your setter method is wrong:
public void setDistance(String distance) {
this.distance = this.distance;
}
This should be:
public void setDistance(String distance) {
this.distance = distance;
}

map 2 collection types using modelmapper

I am developing and spring application and for object mapping I am using ModelMapper library.
I am able to map basic class mapping but when I am trying to map 2 collection elements, source is set of enumeration with additional property like name and description and destination is pojo having id, name and description.
I have tried typemap and converters in mapping profile but I am getting exception of mapper.
And the source class is from other application(whose dependency have been added in pom.xml). I also don't want source type as an argument in setter of destination.
Ex.
SOURCE:
public class VType{
private int id;
private String name;
private String description;
}
public class VDTO{
private Set<VType> vTypes;
public Set<VType> getVTypes(){
return this.vTypes;
}
public void setVType() { //here I don't want to pass source type as an argument
//code stuff that I don't know what to do here
}
}
SOURCE ENUM:
public enum SourceVType{
V1(1, "Name1", "Desc1");
V2(2, "Name2", "Desc2");
private Integer id;
private String name;
private String description;
SourceVType(Integer id, String name, String description) {
this.id = id;
this.name = name;
this.description = description;
}
//getter-setter
}
Have you tried converter feature of modelmapper. You can use typemap converter to achieve this requirement.
#RunWith(JUnit4.class)
public class TempTest {
#Test
public void TestThis(){
final ModelMapper mapper = new ModelMapper();
mapper.addMappings(new PropertyMap<SrcClass, DestClass>() {
#Override
protected void configure() {
this.map().setId(this.source.getId());
this.map().setName(this.source.getName());
mapper.createTypeMap(TypeEnum.class, TypeClass.class).setConverter(
new Converter<TypeEnum, TypeClass>() {
#Override
public TypeClass convert(MappingContext<TypeEnum, TypeClass> mappingContext) {
if (mappingContext.getSource() == null) {
return null;
}
TypeEnum typeEnum = mappingContext.getSource();
TypeClass typeClass = new TypeClass();
typeClass.setId(typeEnum.getId());
typeClass.setName(typeEnum.getName());
return typeClass;
}
});
}
});
SrcClass srcObj = new SrcClass();
srcObj.setId(1);
srcObj.setName("name");
srcObj.setTypes(new HashSet<>(Arrays.asList(TypeEnum.TYPE1, TypeEnum.TYPE2)));
DestClass dstObj = mapper.map(srcObj, DestClass.class);
Assert.assertEquals(srcObj.getId(), dstObj.getId());
Assert.assertEquals(srcObj.getName(), dstObj.getName());
Assert.assertEquals(srcObj.getTypes().size(), dstObj.getTypes().size());
for(TypeClass c : dstObj.getTypes()) {
TypeEnum e = TypeEnum.getById(c.getId());
Assert.assertNotNull(e);
Assert.assertTrue(srcObj.getTypes().contains(e));
}
}
public static <Source, Result> Set<Result> convertAll(Set<Source> source, Function<Source, Result> projection)
{
Set<Result> results = new HashSet<>();
if(source == null) return results;
for (Source element : source)
{
results.add(projection.apply(element));
}
return results;
}
public static class SrcClass{
private Integer id;
private String name;
private Set<TypeEnum> types;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<TypeEnum> getTypes() {
return types;
}
public void setTypes(Set<TypeEnum> types) {
this.types = types;
}
}
public static class DestClass{
private Integer id;
private String name;
private Set<TypeClass> types;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<TypeClass> getTypes() {
return types;
}
public void setTypes(Set<TypeClass> types) {
this.types = types;
}
}
public static enum TypeEnum{
TYPE1(1, "Type 1")
, TYPE2(2, "Type 2")
, TYPE3(3, "Type 3")
, TYPE4(4, "Type 4");
private Integer id;
private String name;
TypeEnum(Integer id, String name) {
this.id = id;
this.name = name;
}
private static final Map<Integer, TypeEnum> byId = new HashMap<>();
private static final Map<String, TypeEnum> byName = new HashMap<>();
static {
for (TypeEnum e : TypeEnum.values()) {
if (byId.put(e.getId(), e) != null) {
throw new IllegalArgumentException("duplicate id: " + e.getId());
}
if (byName.put(e.getName(), e) != null) {
throw new IllegalArgumentException("duplicate name: " + e.getName());
}
}
}
public Integer getId() {
return this.id;
}
public String getName() { return this.name; }
public static TypeEnum getById(Integer id) {
return byId.get(id);
}
public static TypeEnum getByName(String name) {
return byName.get(name);
}
}
public static class TypeClass{
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}

Hibernate:IllegalArgumentException : in class: ... getter method of property: id

public class Media implements java.io.Serializable {
private int id;
private MediaKind mediaKind;
private String name;
private byte[] cover;
private Date releaseDate;
private Integer contentRating;
private String summary;
private Set mediaCrews = new HashSet(0);
private Set mediaInstances = new HashSet(0);
private Set ratings = new HashSet(0);
private Set genres = new HashSet(0);
static SessionFactory mediaFactory=Main.config.buildSessionFactory();
public Media() {
}
public Media(int id, MediaKind mediaKind, String name) {
this.id = id;
this.mediaKind = mediaKind;
this.name = name;
Session mediaSession = mediaFactory.getCurrentSession();
}
public Media(int id, MediaKind mediaKind, String name, byte[] cover,
Date releaseDate, Integer contentRating, String summary,
Set mediaCrews, Set mediaInstances, Set ratings, Set genres) {
this.id = id;
this.mediaKind = mediaKind;
this.name = name;
this.cover = cover;
this.releaseDate = releaseDate;
this.contentRating = contentRating;
this.summary = summary;
this.mediaCrews = mediaCrews;
this.mediaInstances = mediaInstances;
this.ratings = ratings;
this.genres = genres;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public MediaKind getMediaKind() {
return this.mediaKind;
}
public void setMediaKind(MediaKind mediaKind) {
this.mediaKind = mediaKind;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public byte[] getCover() {
return this.cover;
}
public void setCover(byte[] cover) {
this.cover = cover;
}
public Date getReleaseDate() {
return this.releaseDate;
}
public void setReleaseDate(Date releaseDate) {
this.releaseDate = releaseDate;
}
public Integer getContentRating() {
return this.contentRating;
}
public void setContentRating(Integer contentRating) {
this.contentRating = contentRating;
}
public String getSummary() {
return this.summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public Set getMediaCrews() {
return this.mediaCrews;
}
public void setMediaCrews(Set mediaCrews) {
this.mediaCrews = mediaCrews;
}
public Set getMediaInstances() {
return this.mediaInstances;
}
public void setMediaInstances(Set mediaInstances) {
this.mediaInstances = mediaInstances;
}
public Set getRatings() {
return this.ratings;
}
public void setRatings(Set ratings) {
this.ratings = ratings;
}
public Set getGenres() {
return this.genres;
}
public void setGenres(Set genres) {
this.genres = genres;
}
public static java.util.List<Media> search(String name){
java.util.List list;
Session sess=mediaFactory.getCurrentSession();
sess.beginTransaction();
Criteria criteria=sess.createCriteria(Media.class);
criteria.add(Restrictions.like("name", "%"+name+"%"));
list= criteria.list();
Hibernate.initialize(list);
sess.getTransaction().commit();
//connection=sess.close();
return list;
}
public ArrayList<MediaInstance> availableInstances(){
//sess.beginTransaction();
Session sess=mediaFactory.openSession();
sess.beginTransaction();
Criteria criteria=sess.createCriteria(MediaInstance.class);
criteria.add(Restrictions.like("media", name));
sess.getTransaction().commit();
return (ArrayList<MediaInstance>)criteria.list();
/*MediaInstance[] instances=(MediaInstance[]) mediaInstances.toArray();
ArrayList<MediaInstance> mediaInstanceList=new ArrayList<MediaInstance>(Arrays.asList(instances));
for(int i=0;i<mediaInstanceList.size();i++){
MediaInstance instance=mediaInstanceList.get(i);
if(!instance.isAvailable()|!instance.isSellable()){
mediaInstanceList.remove(instance);
}
}
//sess.getTransaction().commit();
//sess.close();
return mediaInstanceList;*/
}
}
here is my second class mediaInstance:
public class MediaInstance implements java.io.Serializable {
private int id;
private MediaType mediaType;
private Media media;
private String price;
private boolean available;
private boolean sellable;
private Set rents = new HashSet(0);
private Set purchases = new HashSet(0);
public MediaInstance() {
}
public MediaInstance(int id, MediaType mediaType, Media media,
String price, boolean available, boolean sellable) {
this.id = id;
this.mediaType = mediaType;
this.media = media;
this.price = price;
this.available = available;
this.sellable = sellable;
}
public MediaInstance(int id, MediaType mediaType, Media media,
String price, boolean available, boolean sellable, Set rents,
Set purchases) {
this.id = id;
this.mediaType = mediaType;
this.media = media;
this.price = price;
this.available = available;
this.sellable = sellable;
this.rents = rents;
this.purchases = purchases;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public MediaType getMediaType() {
return this.mediaType;
}
public void setMediaType(MediaType mediaType) {
this.mediaType = mediaType;
}
public Media getMedia() {
return this.media;
}
public void setMedia(Media media) {
this.media = media;
}
public String getPrice() {
return this.price;
}
public void setPrice(String price) {
this.price = price;
}
public boolean isAvailable() {
return this.available;
}
public void setAvailable(boolean available) {
this.available = available;
}
public boolean isSellable() {
return this.sellable;
}
public void setSellable(boolean sellable) {
this.sellable = sellable;
}
public Set getRents() {
return this.rents;
}
public void setRents(Set rents) {
this.rents = rents;
}
public Set getPurchases() {
return this.purchases;
}
public void setPurchases(Set purchases) {
this.purchases = purchases;
}
}
When I try to call criteria.list() in method availableInstances() I get this exception.
May 27, 2014 1:22:56 PM org.hibernate.property.BasicPropertyAccessor$BasicGetter get
ERROR: HHH000122: IllegalArgumentException in class: Media, getter method of property: id
Exception in thread "main" org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of Media.id
at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:192)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:346)
at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:4746)
at org.hibernate.persister.entity.AbstractEntityPersister.isTransient(AbstractEntityPersister.java:4465)
at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:243)
at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:293)
at org.hibernate.type.EntityType.getIdentifier(EntityType.java:537)
at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:174)
at org.hibernate.loader.Loader.bindPositionalParameters(Loader.java:1994)
at org.hibernate.loader.Loader.bindParameterValues(Loader.java:1965)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1900)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1861)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838)
at org.hibernate.loader.Loader.doQuery(Loader.java:909)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
at org.hibernate.loader.Loader.doList(Loader.java:2553)
at org.hibernate.loader.Loader.doList(Loader.java:2539)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2369)
at org.hibernate.loader.Loader.list(Loader.java:2364)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:126)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1682)
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:380)
at MediaInstance.availableInstances(MediaInstance.java:125)
at Main.main(Main.java:24)
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:169)
... 23 more
I used JBoss tools to generate the classes and mapping files from my database.
so I don't think that the problem is in mapping files.
Your criteria query doesn't seem right. You are trying to filter by an instance of media entity but passing the name as parameter.
Try something like this:
criteria.add(Restrictions.eq("media", this));
The second argument passed to the static "like" method (or "eq" method, and so on) of the Restrictions static class must be of the same type of the field identified by the first string (first argument).
In your example:
criteria.add(Restrictions.like("media", name));
"name" is a String while "media" field of the MediaInstance class is a instance of Media. You should substitute "name" with a media instance, even the Media instance itself executing the "availableInstances" method, so:
criteria.add(Restrictions.like("media", this));

Categories