Primary key is not generated in JPA with app engine Java - java

I have entity class "User" as shown below but its not generating primary key. I am using JPA in my app engine application and using app engine endpoints in my android client.
Enitty class:
#Entity
public class UserMaster {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;
private String userName;
private String fullName;
private String userAvtarUrl;
private String userAbout;
private String userGender;
public String getUserName() {
return userName;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getUserAvtarUrl() {
return userAvtarUrl;
}
public void setUserAvtarUrl(String userAvtarUrl) {
this.userAvtarUrl = userAvtarUrl;
}
public String getUserAbout() {
return userAbout;
}
public void setUserAbout(String userAbout) {
this.userAbout = userAbout;
}
public String getUserGender() {
return userGender;
}
public void setUserGender(String userGender) {
this.userGender = userGender;
}
}
Endpoint persistence code :
#ApiMethod(name = "insertUserMaster")
public UserMaster insertUserMaster(UserMaster usermaster) {
EntityManager mgr = getEntityManager();
try {
if (containsUserMaster(usermaster)) {
throw new EntityExistsException("Object already exists");
}
mgr.persist(usermaster);
} finally {
mgr.close();
}
return usermaster;
}
Android client
Userendpoint.Builder builder = new Userendpoint.Builder(
AndroidHttp.newCompatibleTransport(),
new JacksonFactory(), new HttpRequestInitializer() {
public void initialize(HttpRequest httpRequest) {
}
});
Userendpoint endpoint = CloudEndpointUtils.updateBuilder(
builder).build();
User objUser = new User();
objUser.setUserName(txtName.getText().toString());
objUser.setUserEmail(txtEmail.getText().toString());
Bitmap bmp = BitmapFactory.decodeFile(imagePath);
ByteArrayOutputStream out = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
byte[] imgByte = out.toByteArray();
String encodedImage = Base64.encodeToString(imgByte,
Base64.DEFAULT);
objUser.setImage(encodedImage);
User result = endpoint.insertUser(objUser).execute();
Please guide me where i am lacking. Thank you.

If using JPA and GAE/Datastore either use all JPA annotations, or all as a vendor-extension use all JDO annotations. You cannot mix and match.

May be your database server does not provide the auto id generation.
IDENTITY
IDENTITY, it is depend on the Database to auto generate.
Some DB Server Like, MySQL or Microsoft SQL Server do provide ID generation for the primary key field during insertion.
The common way is to use the IdGeneratorStrategy.TABLE. It is not depend on DB.

In my case problem was in method "containsUserMaster(usermaster)"
Method check existing in way like this:
UserMaster item = mgr.find(UserMaster.class, userId);
Problem that until add operation not complete, userId will be null, and because program stops with NullPointerExeption..
I'm add userId checkinq on null - and this solves the problem

Related

Save SQL's JPA in String column on BD

I'm using JPA with Hibernate, on my project i have a UI with so much options from filter on SQL, it's like a Profile to search, the user choose options and choose a nickname from this Profile and save on BD.
But i think not a good idea map/entity Class just for a save filter, then i thought, why i don't save the JPQL/SQL on String column on BD, and retrive when user can use this?
I try use Criteria for it, but can't extract JPQL from this, how i can use criteria, or better for this issue?
A little example:
#SuppressWarnings("unchecked")
public List<Empresa> filtrados(FilterEmpresa filtro) {
Session session = manager.unwrap(Session.class);
Criteria criteria = session.createCriteria(Empresa.class);
if (StringUtils.isNotBlank(filtro.getCodigo())) {
try {
Long longCodigo = Long.parseLong(filtro.getCodigo());
criteria.add(Restrictions.eq("id", longCodigo));
} catch (NumberFormatException ex) {
}
}
if (StringUtils.isNotBlank(filtro.getNome())) {
criteria.add(Restrictions.ilike("nome", filtro.getNome(),
MatchMode.START));
}
if (StringUtils.isNotBlank(filtro.getNomeResumido())) {
criteria.add(Restrictions.ilike("nomeResumido",
filtro.getNomeResumido(), MatchMode.START));
}
return criteria.addOrder(Order.asc("nome")).list();
}
And FilterEmpresa.class:
public class FilterEmpresa implements Serializable {
private static final long serialVersionUID = 1L;
private String codigo;
private String nome;
private String nomeResumido;
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getNomeResumido() {
return nomeResumido;
}
public void setNomeResumido(String nomeResumido) {
this.nomeResumido = nomeResumido;
}
}
Thanks for help.

AzureMobileService: Insert data in to table gives exception

I am new to implement Azure Mobile Service. I have refer the demo of ToDoItem given by Azure.
In same manner i have make class User for my own app. Then I am inserting the data in to the MobileServiceTable but it gives me error like below:
{"message":"The operation failed with the following error: 'A null store-generated value was returned for a non-nullable member 'CreatedAt' of type 'CrazyLabApp.Models.User'.'."}
I have not created any field like this as it is not created in ToDoItem demo as well. I have seen that there are 4 fields that are by Default created by the MobileServiceTable. createdAt is one of the field of that.
I am wonder about whats wrong i am doing.
Check my below Userclass:
public class User {
#com.google.gson.annotations.SerializedName("id")
private String ServiceUserId;
#com.google.gson.annotations.SerializedName("email")
private String Email;
#com.google.gson.annotations.SerializedName("firstname")
private String FirstName;
#com.google.gson.annotations.SerializedName("lastname")
private String LastName;
#com.google.gson.annotations.SerializedName("profilepic")
private String ProfilePic;
#com.google.gson.annotations.SerializedName("introduction")
private String Introduction;
#com.google.gson.annotations.SerializedName("website")
private String Website;
#com.google.gson.annotations.SerializedName("title")
private String Title;
#com.google.gson.annotations.SerializedName("_createdAt")
private Date CreatedAt;
#com.google.gson.annotations.SerializedName("coverimage")
private ArrayList<CoverImage> CoverImages;
/*public Date getCreatedAt() {
return CreatedAt;
}
public void setCreatedAt(Date createdAt) {
CreatedAt = createdAt;
}*/
#com.google.gson.annotations.SerializedName("followers")
private ArrayList<User> Followers;
#com.google.gson.annotations.SerializedName("likes")
private ArrayList<Likes> Likes;
#com.google.gson.annotations.SerializedName("collections")
private ArrayList<Collections> Collections;
#com.google.gson.annotations.SerializedName("comments")
private ArrayList<Comments> Comments;
#com.google.gson.annotations.SerializedName("stories")
private ArrayList<Story> Stories ;
//-------------- Methods
public ArrayList<Story> getStories() {
return Stories;
}
public void setStories(ArrayList<Story> stories) {
Stories = stories;
}
public ArrayList<com.promact.crazylab.model.Comments> getComments() {
return Comments;
}
public void setComments(ArrayList<com.promact.crazylab.model.Comments> comments) {
Comments = comments;
}
public ArrayList<com.promact.crazylab.model.Collections> getCollections() {
return Collections;
}
public void setCollections(ArrayList<com.promact.crazylab.model.Collections> collections) {
Collections = collections;
}
public ArrayList<com.promact.crazylab.model.Likes> getLikes() {
return Likes;
}
public void setLikes(ArrayList<com.promact.crazylab.model.Likes> likes) {
Likes = likes;
}
public ArrayList<User> getFollowers() {
return Followers;
}
public void setFollowers(ArrayList<User> followers) {
Followers = followers;
}
public ArrayList<CoverImage> getCoverImages() {
return CoverImages;
}
public void setCoverImages(ArrayList<CoverImage> coverImages) {
CoverImages = coverImages;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getWebsite() {
return Website;
}
public void setWebsite(String website) {
Website = website;
}
public String getIntroduction() {
return Introduction;
}
public void setIntroduction(String introduction) {
Introduction = introduction;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public String getProfilePic() {
return ProfilePic;
}
public void setProfilePic(String profilePic) {
ProfilePic = profilePic;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getServiceUserId() {
return ServiceUserId;
}
public void setServiceUserId(String serviceUserId) {
ServiceUserId = serviceUserId;
}
#Override
public boolean equals(Object o) {
return o instanceof User && ((User) o).ServiceUserId == ServiceUserId;
}
}
Also check below code the way i am inserting it:
final User u = new User();
u.setFirstName(mName);
u.setEmail(mEmail);
u.setProfilePic(mUrl);
mUserTable = mClient.getTable(User.class);
// Insert the new item
new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... params) {
try {
final User entity = mUserTable.insert(u).get();
} catch (Exception e){
//createAndShowDialog(e, "Error");
System.out.println("Error: "+e.toString());
}
return null;
}
}.execute();
Please help me in this.
The "_createdat" column will be populated automatically by Azure Mobile Services so there is no need to include it in your model. Delete this property from the User class. Its presence is probably overwriting the auto-populated value with a null.
you can solve this problem by just deleting createdAt column from your user table in azure.
Why this error is coming :
I am not sure But I guess this error is coming because createdAt is a non-nullable member and you cannot left it null.
EDIT :
Another aspect of the system columns is that they cannot be sent by the client. For new tables (i.e., those with string ids), if an insert of update request contains a property which starts with ‘__’ (two underscore characters), the request will be rejected. The ‘__createdAt’ property can, however, be set in the server script (although if you really don’t want that column to represent the creation time of the object, you may want to use another column for that) – one way where this (rather bizarre) scenario can be accomplished. If you try to update the ‘__updatedAt’ property, it won’t fail, but by default that column is updated by a SQL trigger, so any updates you make to it will be overridden anyway.
for more info take a look here :-http://blogs.msdn.com/b/carlosfigueira/archive/2013/11/23/new-tables-in-azure-mobile-services-string-id-system-properties-and-optimistic-concurrency.aspx

detached entity passed to persist for batch insert in JPA

For the following batch insert method, i get this exception "detached entity passed to persist". Could you take a look at this method and give me some hints?
Thank you so much.
if needed, I will provided the entities here, for the moment I provide Keyword entity :
public class Keyword implements Serializable {
private static final long serialVersionUID = -1429681347817644570L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="key_id")
private long keyId;
#Column(name="key_name")
private String keyName;
#ManyToOne
#JoinColumn(name="tweet_id")
private Tweet tweet;
public long getKeyId() {
return keyId;
}
public void setKeyId(long keyId) {
this.keyId = keyId;
}
public String getKeyName() {
return keyName;
}
public void setKeyName(String keyName) {
this.keyName = keyName;
}
public Tweet getTweet() {
return tweet;
}
public void setTweet(Tweet tweet) {
this.tweet = tweet;
}
}
Here Tweet Entity :
#Entity
#Table(name="tweets")
public class Tweet implements Serializable{
#Id
#Column(name="tweet_id")
private long tweetId;
#Column(name="tweet_text")
private String tweetText;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created_at")
private Date createdAt;
#Column(name="lang_code")
private String languageCode;
#ManyToOne
#JoinColumn(name = "user_id")
private User user;
#OneToMany(mappedBy="tweet")
//#JoinColumn(name="hashtag_id")
private List<Hashtag> hashtags;
#OneToMany(mappedBy="tweet")
//#JoinColumn(name="url_id")
private List<Url> urls;
public List<Keyword> getKeywords() {
return keywords;
}
public void setKeywords(List<Keyword> keywords) {
this.keywords = keywords;
}
#OneToMany(mappedBy="tweet")
//#JoinColumn(name="url_id")
private List<Keyword> keywords;
public long getTweetId() {
return tweetId;
}
public void setTweetId(long tweetId) {
this.tweetId = tweetId;
}
public String getTweetText() {
return tweetText;
}
public void setTweetText(String tweetText) {
this.tweetText = tweetText;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public String getLanguageCode() {
return languageCode;
}
public void setLanguageCode(String languageCode) {
this.languageCode = languageCode;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<Hashtag> getHashtags() {
return hashtags;
}
public void setHashtags(List<Hashtag> hashtags) {
this.hashtags = hashtags;
}
public List<Url> getUrls() {
return urls;
}
public void setUrls(List<Url> urls) {
this.urls = urls;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (tweetId ^ (tweetId >>> 32));
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Tweet other = (Tweet) obj;
if (tweetId != other.tweetId)
return false;
return true;
}
And here Url entity :
#Entity
#Table(name="tweet_url")
public class Url implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="url_id")
private int urlId;
#Column(name="url")
private String url;
#ManyToOne
#JoinColumn(name="tweet_id",referencedColumnName="tweet_id")
private Tweet tweet;
public int getUrlId() {
return urlId;
}
public void setUrlId(int urlId) {
this.urlId = urlId;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Tweet getTweet() {
return tweet;
}
public void setTweet(Tweet tweet) {
this.tweet = tweet;
}
And here is hashtag entity :
#Entity
#Table(name="tweet_hashtag")
public class Hashtag implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="hashtag_id")
private int hashtagId;
#Column(name="hashtag")
private String hashtag;
#ManyToOne
#JoinColumn(name="tweet_id",referencedColumnName="tweet_id")
private Tweet tweet;
public int getHashtagId() {
return hashtagId;
}
public void setHashtagId(int hashtagId) {
this.hashtagId = hashtagId;
}
public String getHashtag() {
return hashtag;
}
public void setHashtag(String hashtag) {
this.hashtag = hashtag;
}
public Tweet getTweet() {
return tweet;
}
public void setTweet(Tweet tweet) {
this.tweet = tweet;
}
And the method :
public void batchInsert(List<Keyword> results) throws HibernateException {
// chekeywordck if key exists
// try {
em=RunQuery.emf.createEntityManager();
em.getTransaction().begin();
for(Keyword result:results)
{
try{
em.persist(result.getTweet().getUser());
}
catch(ConstraintViolationException ce)
{
System.out.print("duplicated insert catched");
}
try{
em.persist(result.getTweet());
}
catch(ConstraintViolationException ce)
{
System.out.print("duplicated insert catched");
}
if(result.getTweet().getHashtags()!=null)
for(Hashtag hashtag:result.getTweet().getHashtags())
em.persist(hashtag);
if(result.getTweet().getUrls()!=null)
for(Url url:result.getTweet().getUrls())
em.persist(url);
em.persist(result);
em.flush();
em.clear();
//when I put these two line out of this loop, it still is the same.
}
em.getTransaction().commit();
// }
}
And here is the exception :
Exception in thread "Thread-3" javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: model.twitter.entities.Url
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1763)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1683)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1187)
at model.service.QueryResultService.batchInsert(QueryResultService.java:74)
at controller.ResultsController.save(ResultsController.java:125)
at controller.ResultsController.parse(ResultsController.java:89)
at main.TwitterStreamConsumer.run(TwitterStreamConsumer.java:41)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: model.twitter.entities.Url
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:139)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1181)
... 5 more
To answer your question: your model defines a one-to-many relationship between Tweet and URL without any cascading. When you are passing a Tweet instance for persisting, the URL objects have not yet been saved and your model does not mandate Tweet to cascade the persist operation to the URL instances. Therefore it can not create the relationship with them.
Cascading tells the hibernate, how to execute DB operations on related entities.
You can instruct it to pass/cascade the persist operation to the related entity, to cascade all operations or an array of operations.
That being said, your problem(1 of them) could be fixed if you modify the relationship with cascading info:
#OneToMany(mappedBy="tweet", cascade={CascadeType.PERSIST})
private List<Url> urls;
But your sample indicates other possible issues and I would encourage you to spent some more time reading Hibernate ORM documentation and practicing on sample model with less relationships.
One of the obvious issues seems to be the lack of understanding of relationship owner concept.
For example, in your Tweet-to-Url relationship, URL is the relationship owner(responsible for managing the relationship, e.g. managing the link via foreign key)
Please consult hibernate docs or one of hundreds of similar questions here on SO for more info.
Depending on how you fill the data, it is possible that you will run into constraint issues, or your entities will not be linked together, because you are not saving the owning side.
Also using try/catch for constraint violations is a very bad way of detecting duplicated entries. ConstraintViolationException can be have many causes and the reason you are getting them is related to the above mentioned relationship mapping issues.
ORM is complex subject and it is really beneficial to start with smaller examples, trying to understand the framework mechanics before moving to the more challenging models. Good Luck
For all the persist calls try using this instead:
if(result.getTweet().getUser().getId() == null) {
em.persist(result.getTweet().getUser());
} else {
result.getTweet().setUser(em.merge(result.getTweet().getUser()));
}
if(result.getTweet().getId() == null) {
em.persist(result.getTweet());
} else {
result.setTweet(em.merge(result.getTweet()));
}
if(result.getId() == null) {
em.persist(result);
} else {
result = em.merge(result);
}

get values from getter and setter methods in java for inserting into Mongodb?

How to get values from getter and setter methods in java to insert into Mongodb.I used the below code to insert in to mongodb
DBCollection coll = db.getCollection("mycol");
BasicDBObject doc = new BasicDBObject("id","Hello" ).
append("description", "database").
append("likes", 100).
append("url", "http://http://www.flowersofindia.net/").
append("by", "Rose");
coll.insert(doc);
The above given are some Hard code values.But i need to take the values from setter method thet i have wrote.This is my getter and setter class.
public class Encapsulation {
private String id;
private String product_name;
private String product_url;
private String product_image;
private String product_price;
private String product_src;
private String country;
private String date;
private String Category;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public String getProduct_url() {
return product_url;
}
public void setProduct_url(String product_url) {
this.product_url = product_url;
}
public String getProduct_image() {
return product_image;
}
public void setProduct_image(String product_image) {
this.product_image = product_image;
}
public String getProduct_price() {
return product_price;
}
public void setProduct_price(String product_price) {
this.product_price = product_price;
}
public String getProduct_src() {
return product_src;
}
public void setProduct_src(String product_src) {
this.product_src = product_src;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getCategory() {
return Category;
}
public void setCategory(String category) {
Category = category;
}
}
.Can anybody help?
Any help will be highly appreciated.I am new to this enviornment
Below is the code to insert into mongodb using setters and getters.
Note that
1) I have used the same Encapsulation class with getters and setters.
2) I have used mongo-java-driver-2.12.2.jar as mongo java driver.
3) mongodb is running at port 27017.
Code:
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
public class MongoInsert {
/**
* #param args
* #throws Exception
*/
public static void main(String[] args) throws Exception {
Encapsulation bean=new Encapsulation();
// Setting values
bean.setId("value1");
bean.setProduct_name("value2");
bean.setProduct_image("value3");
bean.setProduct_price("value4");
bean.setProduct_src("value5");
bean.setProduct_url("value6");
bean.setDate("value7");
bean.setCountry("value8");
bean.setCategory("value9");
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("Test");
DBCollection coll = db.getCollection("mycol");
//getting values and assigning to mongo field
BasicDBObject doc = new BasicDBObject("id", bean.getId()).
append("Product_name", bean.getProduct_name()).
append("Product_image", bean.getProduct_image()).
append("Product_price", bean.getProduct_price()).
append("Product_src", bean.getProduct_src()).
append("Product_url", bean.getProduct_url()).
append("Date", bean.getDate()).
append("Country", bean.getCountry()).
append("Category", bean.getCategory());
coll.insert(doc);
}
}
Hope it helps.
You want to map your POJO with MongoDB database. you can use ORM for that purpose. You can achieve CRUD and query operations easily in SQL manner using Kundera. Kundera is a JPA 2.1 compliant object-datastore mapping library for NoSQL datastores. You can find more about Kundera on below mentioned link.
https://github.com/impetus-opensource/Kundera/wiki
Hope that Helps...:)

How to join non primary key in google app engine

How to get data of non primary key column userId using java in google app engine
List<UserAddress> list = (List<UserAddress>) pmf.getObjectById(UserAddress.class, Long.valueOf(userId));
System.out.println(list.size());
When I fetch the data the following error occur in console
NestedThrowablesStackTrace:
Could not retrieve entity of kind UserAddress with key UserAddress(4)
org.datanucleus.exceptions.NucleusObjectNotFoundException: Could not retrieve entity of kind UserAddress with key UserAddress(4)
Tried below code also, to fetch the data of non primary key column userId but it shows empty list.
#SuppressWarnings("unchecked")
public List<UserAddress> getUserAddressFind(String userId) {
List<UserAddress> returnList = new ArrayList<UserAddress>();
PersistenceManager pmf = PMF.get().getPersistenceManager();
try {
Query query = pmf.newQuery(UserAddress.class);
query.setFilter("userId == userIdParam");
query.declareParameters("Long userIdParam");
returnList = (List<UserAddress>) query.execute(userId);
System.out.println(returnList.size());
if (returnList != null && returnList.isEmpty()) {
System.out.println("No results for userAddresses");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
pmf.close();
}
return returnList;
}
UserAddress.java
package com.rrd.up2me.datastore;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
#PersistenceCapable(identityType = IdentityType.APPLICATION)
public class UserAddress {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.SEQUENCE)
private Long userAddressId;
#Persistent
private Long userId;
#Persistent
private Long addressId;
#Persistent
private Boolean isPrimary;
public Long getUserAddressId() {
return userAddressId;
}
public void setUserAddressId(Long userAddressId) {
this.userAddressId = userAddressId;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getAddressId() {
return addressId;
}
public void setAddressId(Long addressId) {
this.addressId = addressId;
}
public Boolean getIsPrimary() {
return isPrimary;
}
public void setIsPrimary(Boolean isPrimary) {
this.isPrimary = isPrimary;
}
}
In UserAddress.java class userId is long when execute the query passed variable type is Stringso data is not fetching. AfterType cast the userId String to Long problem solved.
Ex: Long.valueOf(userId).
Query query = pmf.newQuery(UserAddress.class);
query.setFilter("userId == userIdParam");
query.declareParameters("Long userIdParam");
returnList = (List<UserAddress>) query.execute(Long.valueOf(userId));
System.out.println(returnList.size());

Categories