I want to create entity group in GAE Datastore such that one city have contain multiple suburbans. Following is my code :-
//city.java
#JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="#id")
#Entity
public class City
{
#Id
private String name;
#OneToMany(mappedBy="city", cascade=CascadeType.ALL)
private Suburban[] suburbans;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Suburban[] getSuburbans()
{
return suburbans;
}
public void setSuburbans(Suburban[] suburbans)
{
this.suburbans = suburbans;
}
}
//suburban.java
#JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="#id")
#Entity
public class Suburban
{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Key id;
private String name;
#ManyToOne(fetch = FetchType.LAZY)
private City city;
public City getCity()
{
return city;
}
public void setCity(City city)
{
this.city = city;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Key getId()
{
return id;
}
}
I am auto-generating cityendpoint class using google-plugin for eclipse option "Generate Cloud Endpoint Class".
//CityEndpoint.java
#Api(name = "cityendpoint", namespace = #ApiNamespace(ownerDomain = "zestbuds.com", ownerName = "zestbuds.com", packagePath = "android"))
public class CityEndpoint
{
/**
* This method lists all the entities inserted in datastore.
* It uses HTTP GET method and paging support.
*
* #return A CollectionResponse class containing the list of all entities
* persisted and a cursor to the next page.
*/
#SuppressWarnings({ "unchecked", "unused" })
#ApiMethod(name = "listCity")
public CollectionResponse<City> listCity(#Nullable #Named("cursor") String cursorString, #Nullable #Named("limit") Integer limit)
{
EntityManager mgr = null;
Cursor cursor = null;
List<City> execute = null;
try
{
mgr = getEntityManager();
Query query = mgr.createQuery("select from City as City");
if (cursorString != null && cursorString != "")
{
cursor = Cursor.fromWebSafeString(cursorString);
query.setHint(JPACursorHelper.CURSOR_HINT, cursor);
}
if (limit != null)
{
query.setFirstResult(0);
query.setMaxResults(limit);
}
execute = (List<City>) query.getResultList();
cursor = JPACursorHelper.getCursor(execute);
if (cursor != null)
cursorString = cursor.toWebSafeString();
// Tight loop for fetching all entities from datastore and accomodate
// for lazy fetch.
for (City obj : execute)
;
} finally
{
mgr.close();
}
return CollectionResponse.<City> builder().setItems(execute).setNextPageToken(cursorString).build();
}
/**
* This method gets the entity having primary key id. It uses HTTP GET method.
*
* #param id the primary key of the java bean.
* #return The entity with primary key id.
*/
#ApiMethod(name = "getCity")
public City getCity(#Named("id") String id)
{
EntityManager mgr = getEntityManager();
City city = null;
try
{
city = mgr.find(City.class, id);
} finally
{
mgr.close();
}
return city;
}
/**
* This inserts a new entity into App Engine datastore. If the entity already
* exists in the datastore, an exception is thrown.
* It uses HTTP POST method.
*
* #param city the entity to be inserted.
* #return The inserted entity.
*/
#ApiMethod(name = "insertCity")
public City insertCity(City city)
{
EntityManager mgr = getEntityManager();
try
{
if (containsCity(city))
{
throw new EntityExistsException("Object already exists");
}
mgr.persist(city);
} finally
{
mgr.close();
}
return city;
}
/**
* This method is used for updating an existing entity. If the entity does not
* exist in the datastore, an exception is thrown.
* It uses HTTP PUT method.
*
* #param city the entity to be updated.
* #return The updated entity.
*/
#ApiMethod(name = "updateCity")
public City updateCity(City city)
{
EntityManager mgr = getEntityManager();
try
{
if (!containsCity(city))
{
throw new EntityNotFoundException("Object does not exist");
}
mgr.persist(city);
} finally
{
mgr.close();
}
return city;
}
/**
* This method removes the entity with primary key id.
* It uses HTTP DELETE method.
*
* #param id the primary key of the entity to be deleted.
*/
#ApiMethod(name = "removeCity")
public void removeCity(#Named("id") String id)
{
EntityManager mgr = getEntityManager();
try
{
City city = mgr.find(City.class, id);
mgr.remove(city);
} finally
{
mgr.close();
}
}
private boolean containsCity(City city)
{
EntityManager mgr = getEntityManager();
boolean contains = true;
try
{
City item = mgr.find(City.class, city.getName());
if (item == null)
{
contains = false;
}
} finally
{
mgr.close();
}
return contains;
}
private static EntityManager getEntityManager()
{
return EMF.get().createEntityManager();
}
}
Initally, I was not using #JsonIdentityInfo, and hence I was getting java.io.IOException: com.google.appengine.repackaged.org.codehaus.jackson.map.JsonMappingException: Infinite recursion (StackOverflowError). After reading thread, I recognized my error is due to jackson.
After reading Thread, I decided to use #JsonIdentityInfo. Now I am getting
java.io.IOException: com.google.appengine.repackaged.org.codehaus.jackson.map.JsonMappingException: You have just attempted to access field "suburbans" yet this field was not detached when you detached the object. Either dont access this field, or detach it when detaching the object. (through reference chain: com.google.api.server.spi.response.CollectionResponse["items"]->com.google.appengine.datanucleus.query.StreamingQueryResult[0]->com.zestbuds.android.City["suburbans"])
why am I getting suburban is not detached, even though I am using Cascade.ALL?
Finally solved issue.
There is no need of using #JsonIdentityInfo . I just needed to remove getter and setter method for class member having #ManyToOne annotation(In my case, I removed getCity() and setCity()).
Here is the example provided by datanucleus for bidirectional one-to-many mapping.
Related
I have added Hibernate filters on my entities . These filters are applied on queries which fetch Collection of entity but not applied on queries which fetch single entity. Below is my code.
AOrganization.java
#MappedSuperclass
#FilterDef(name = "OrgFilter", parameters = { #ParamDef(name = "allowedOrgIdList", type = "long") })
#Filter(name = "OrgFilter", condition = "org_id in (:allowedOrgIdList)")
public class AOrganization implements Serializable {
#ManyToOne()
#JoinColumn(name = "org_id", nullable = true)
private Organization organization;
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
}
Site.java
#Data
#Entity
#Table(name = "site")
public class Site extends AOrganization{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private long id;
#Column(name = "site_name")
private String siteName;
#Override
public String toString() {
return "Site [id=" + id + ", siteName=" + siteName + "]";
}
}
SiteService.java
public interface SiteService {
public List<Site> getAllSites();
public List<Site> getSiteBySiteName(String siteName);
public Site updateSiteName(Long id, String siteName);
}
SiteRepository.java
#Repository
public interface SiteRepository extends AOrganizationRepository<Site, Long> {
public List<Site> findBySiteName(String siteName);
public List<Site> findByOrganization_Id(Long orgId);
}
AOrganizationRepository.java
#NoRepositoryBean
public interface AOrganizationRepository<T, ID extends java.io.Serializable> extends CrudRepository<T, ID> {
}
SiteServiceImpl.java
#Service
public class SiteServiceImpl implements SiteService {
#Autowired
private EntityManager entityManager;
#Autowired
private SiteRepository siteRepository;
#Override
public List<Site> getAllSites() {
Iterable<Site> sites = siteRepository.findAll();
List<Site> allSites = new ArrayList<>();
sites.forEach(allSites::add);
return allSites;
}
#Override
public List<Site> getSiteBySiteName(String siteName) {
List<Site> allSites = siteRepository.findBySiteName(siteName);
return allSites;
}
#Override
public Site updateSiteName(Long id,String siteName) {
Site site = siteRepository.findById(id).get();
if(site == null)
return null;
site.setSiteName(siteName);
siteRepository.save(site);
return site;
}
}
AOrganizationAspect.java
#Aspect
#Component
#Slf4j
public class AOrganizationAspect {
#PersistenceContext
private EntityManager entityManager;
#Pointcut("execution(public * com.harshal.springboot.springfilter.repository.AOrganizationRepository+.*(..))")
protected void aOrganizationRepositoryRepositoryMethod() {
log.info("aOrganizationRepositoryRepositoryMethod");
}
#Around(value = "aOrganizationRepositoryRepositoryMethod()")
public Object enableOwnerFilter(ProceedingJoinPoint joinPoint) throws Throwable {
// Variable holding the session
Session session = null;
try {
// Get the Session from the entityManager in current persistence context
session = entityManager.unwrap(Session.class);
// Enable the filter
Filter filter = session.enableFilter("OrgFilter");
// Set the parameter from the session
List<Long> orgList = getAllowedOrgIdList();
filter.setParameterList("allowedOrgIdList", orgList);
} catch (Exception ex) {
// Log the error
log.error("Error enabling OrgFilter : Reason -" + ex.getMessage());
}
// Proceed with the joint point
Object obj = joinPoint.proceed();
// If session was available
if (session != null) {
// Disable the filter
session.disableFilter("OrgFilter");
}
// Return
return obj;
}
private List<Long> getAllowedOrgIdList() {
return Arrays.asList(2l);
}
}
So , hibernate filters are applied if method getSiteBySiteName is called and filters are not applied if findById method is called.
Below are queries :
For getSiteBySiteName :
select site0_.id as id1_2_, site0_.org_id as org_id3_2_,
site0_.site_name as site_nam2_2_ from site site0_ where site0_.org_id
in (?) and site0_.site_name=?
Please help . Thanks in advance.
For findById
select site0_.id as id1_2_0_, site0_.org_id as org_id3_2_0_,
site0_.site_name as site_nam2_2_0_, organizati1_.id as id1_1_1_,
organizati1_.address as address2_1_1_, organizati1_.org_name as
org_name3_1_1_ from site site0_ left outer join organization
organizati1_ on site0_.org_id=organizati1_.id where site0_.id=?
findById is using the EntityManager.find method and do not create a query.
Plus Hibernate Filters only work on queries.
You should write a query instead of using findById
I have a DynamoDB table with a primary key (id : integer) and secondary key (dateTo : String). I've made a Class that utilizes DynamoDBMapper:
#DynamoDBTable(tableName="MyItems"
public class MyItemsMapper {
private int id;
private String dateTo;
private String name;
#DynamoDBHashKey(attributeName="id")
public void setId(int id) { this.id = id; }
public int getId() { return id; }
#DynamoDBAttribute(attributeName="dateTo")
public void setDateTo(String dateTo) { this.dateTo = dateTo; }
public String getDateTo() { return dateTo; }
#DynamoDBAttribute(attributeName="name")
public void setName(String name { this.name = name; }
public String getName() { return name; }
public boolean saveItem(MyItemsMapper item) {
try {
DynamoDBMapper mapper = new DynamoDBMapper(client); //<-- This connects to the DB. This works fine.
item.setId(generateUniqueNumber()); //<-- This generates a unique integer. Also seems to work fine.
mapper.save(item);
logger.info("Successfully saved item. See info below.");
logger.info(item.toString());
return true;
} catch (Exception e) {
logger.error("Exception while trying to save item: " + e.getMessage());
e.printStackTrace();
return false;
}
}
}
I then have a manager class that uses the bean above, like so:
public class MyManager {
public boolean recordItem(
int id,
String dateTo,
String name,
) {
MyItemsMapper myItemsMapper = new MyItemsMapper();
myItemsMapper.setId(id);
myItemsMapper.setDateTo(dateTo);
myItemsMapper.setName(name);
myItemsMapper.saveItem(myItemsMapper);
}
}
I am running the manager class in a JUnit test:
public class MyManagerTest {
#Test
public void saveNewItemTest() {
MyManager myManager = new MyManager();
myManager.recordItem(1234567, "2018-01-01", "Anthony");
}
}
When I use the saveItem method above via my manager by running my JUnit test, I get the following error:
com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException: MyItemsMapper; no mapping for HASH key
Not really sure what it's pertaining to, as I definitely have a primary key for my table and my secondary key always has a value as well.
How do I get this to work?
More Info:
It's worth noting that I can record data into my DynamoDB table via the Item object. If I do the below, my data gets recorded into the database:
DynamoDB dynamoDB = new DynamoDBClient().connectToDynamoDB(); //<--
Connection. Works fine.
Table table = dynamoDB.getTable("MyItems");
item.withPrimaryKey("id", 1234567);
item.withString("dateTo", "2018-01-01");
item.withString("name", "Anthony");
PutItemOutcome outcome = table.putItem(item);
However, I'm trying to use DynamoDBMapper because I'm reading that it is a more organized, better way to access data.
Im not sure if this is causing the problem, but you are creating the myItemsMapper object, then passing a reference to this object to itself.
I would suggest removing your saveItem method. The MyItemsMapper class should be a plain old java object. Then make MyManager like this
public class MyManager {
public boolean recordItem(
int id,
String dateTo,
String name,
) {
MyItemsMapper myItemsMapper = new MyItemsMapper();
myItemsMapper.setId(id);
myItemsMapper.setDateTo(dateTo);
myItemsMapper.setName(name);
DynamoDBMapper mapper = new DynamoDBMapper(client);
mapper.save(myItemsMapper);
}
}
If you particularly want to keep the saveItem method make it like this
public boolean saveItem() {
try {
DynamoDBMapper mapper = new DynamoDBMapper(client);
mapper.save(this);
logger.info("Successfully saved item. See info below.");
logger.info(this.toString());
return true;
} catch (Exception e) {
logger.error("Exception while trying to save item: " + e.getMessage());
e.printStackTrace();
return false;
}
}
And then in MyManager do
MyItemsMapper myItemsMapper = new MyItemsMapper();
myItemsMapper.setId(id);
myItemsMapper.setDateTo(dateTo);
myItemsMapper.setName(name);
myItemsMapper.saveItem();
I created an API to delete an Entity by its key however I'm gettin Http 204 and Entity does not delete from data-store.
This is my API,
#ApiMethod(name = "deleteContact", path = "contact", httpMethod = ApiMethod.HttpMethod.DELETE)
public void deleteContact(final #Named("id") long contactId)
{
ofy().delete().type(Contact.class).id(contactId).now();
}
and my Contact class is like this:
#Entity
#Cache
public class Contact
{
#Id
private long id;
#Index
private String cName;
private Email cEmail;
private PhoneNumber cPhoneNumber;
// private key, to connect this Entity to Profile Entity
#Parent
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
private Key<Profile> profileKey;
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
private String profileId;
// default constructor is private
private Contact()
{
}
public Contact(final long id, final String profileId, final ContactForm contactForm)
{
Preconditions.checkNotNull(contactForm.getUserName(), "The name is required");
this.id = id;
this.profileKey = Key.create(Profile.class, profileId);
this.profileId = profileId;
updateWithContactForm(contactForm);
}
/**
* Updates the Contact with ContactForm.
* This method is used upon object creation as well as updating existing Contact.
*
* #param contactForm contains form data sent from the client.
*/
public void updateWithContactForm(final ContactForm contactForm)
{
this.cName = contactForm.getUserName();
this.cEmail = contactForm.getUserEmailAddress();
this.cPhoneNumber = contactForm.getUserPhoneNumber();
}
public long getId() {
return id;
}
public String getcName() {
return cName;
}
public Email getcEmail() {
return cEmail;
}
public PhoneNumber getcPhoneNumber() {
return cPhoneNumber;
}
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
public Key<Profile> getProfileKey() {
return profileKey;
}
// Get a String version of the key
public String getWebSafeKey()
{
return Key.create(profileKey, Contact.class, id).getString();
}
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
public String getProfileId() {
return profileId;
}
#Override
public String toString() {
return "Contact{" +
"id=" + id +
", cName='" + cName + '\'' +
", cEmail=" + cEmail +
", profileId='" + profileId + '\'' +
", cPhoneNumber=" + cPhoneNumber +
'}';
}
}
Any idea would be appreciated.
You've got a parent associated with your class Contact.
// private key, to connect this Entity to Profile Entity
#Parent
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
private Key<Profile> profileKey;
In datastore, Contact entities are stored as:
/User1Profile/SomeContact1
/User1Profile/SomeContact2
Datastore can't search any entity with just the ID of contact (i.e. "SomeContact1") but it can search if you provide parent as well. The right way to delete would be:
ofy().delete().type(Contact.class).parent(profileKey).ids(contactId).now();
Read this for more details: https://code.google.com/p/objectify-appengine/wiki/BasicOperations#Deleting
im trying to build a google app engine projekt with JPA, JAX-RS and JAX-B. My POST and GET Methods work, but my DELETE method doesn't delete the data.
Resource
#DELETE
#Path("card/{id}")
public void deleteCardById (#PathParam ("id") Long id) {
Service.removeCard(id);
}
Service
public static void removeCard(Long id) {
EntityManager em = EMFService.get().createEntityManager();
Card emp = findCard(id);
if (emp != null) {
em.remove(emp);
}
em.close();
}
public static Card findCard(Long id) {
EntityManager em = EMFService.get().createEntityManager();
Card card = em.find(Card.class, id);
em.close();
return card;
}
Entity
#XmlRootElement
#Entity
public class Card {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
String begriff;
String tabu1;
String tabu2;
String tabu3;
public Card(String begriff, String tabu1, String tabu2, String tabu3) {
super();
Begriff = begriff;
Tabu1 = tabu1;
Tabu2 = tabu2;
Tabu3 = tabu3;
}
public Card() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getBegriff() {
return Begriff;
}
public void setBegriff(String begriff) {
Begriff = begriff;
}
public String getTabu1() {
return Tabu1;
}
public void setTabu1(String tabu1) {
Tabu1 = tabu1;
}
public String getTabu2() {
return Tabu2;
}
public void setTabu2(String tabu2) {
Tabu2 = tabu2;
}
public String getTabu3() {
return Tabu3;
}
public void setTabu3(String tabu3) {
Tabu3 = tabu3;
}
#Override
public String toString() {
return "Card [Begriff=" + Begriff + ", Tabu1=" + Tabu1 + ", Tabu2="
+ Tabu2 + ", Tabu3=" + Tabu3 + "]";
}
When i Debug the app it gives the correct Object to the remove function. But it just don't remove the data ...
You mean you're using v1 of the GAE JPA plugin, and you don't bother putting a transaction around your remove (so the remove is delayed until the next transaction ... which never happens)?
Obviously you could either put a transaction around the remove, or better still you use v2 of the GAE JPA plugin
I was facing similar issue too. the JPA delete actually deletes the entity in the datastore,but it doesn't delete the entity from the JPA Cache.. You page is actually using the JPA Cached result list to display..
The way I used to resolve the issue is to have the JPA Cache cleared every time after a delete.
Sample Code would be something like this:
EM.getTransaction().begin();
EM.remove(current_record);
EM.getTransaction().commit();
EM.getEntityManagerFactory().getCache().evictAll();
ok i think i should write it like this
*edit the problem was the findCard function, i think because of the secone instance of the EntityManager. I chnaged it without using this method to this and now it works.
public static void removeCard(Long id) {
EntityManager em = EMFService.get().createEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
Card card = em.find(Card.class, id);
if (card != null) {
em.remove(card);
}
tx.commit();
} finally {
if (tx.isActive()) {
tx.rollback();
}
em.close();
}
}
I'm worring about JDO in GAE (Google App Engine). (GWT 2.4 and GAE 1.6.3 SDK and JDO 2.3)
I have a class "Users" which should save a Collection of "User" in a List, but it doesn't work.
When i save my Users-Class, then it creates the "Users"-Object in the Datebase and it also creates the User-Object in the List users. But when i load the Users-Object from the Database, the List users is empty...
Do i have to load the list by my self? I guess that JDO schould load the list directy, when i load the Users-Object.
I need your Help here! Thanks in previous!
Could it be a Problem that i create the Key in abstract class PersistentUser and PersistentUsers?
Could the LinkedList be the Problem?
My Code:
#PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
#Version(strategy=VersionStrategy.VERSION_NUMBER)
public class Users extends PersistentUsers implements Serializable{
/**
*
*/
private static final long serialVersionUID = -21666269538993247L;
/**
* Mapped from Operator X
*/
#Persistent
private String operatorId;
#Persistent(mappedBy="userlist")
#Element(dependent = "true")
private List<User> users;
/**
*
* List of Ids of Users
*
*/
#Persistent(serialized = "true")
#Element(dependent = "true")
private List<String> userIds;
/**
* #return the users
*/
public List<User> getUsers() {
return users;
}
/**
* #param users the users to set
*/
public void setUsers(List<User> users) {
this.users = users;
}
...
}
The User Class:
#PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
#Version(strategy=VersionStrategy.VERSION_NUMBER)
public class User extends PersistentUser implements Serializable{
/**
*
*/
private static final long serialVersionUID = 6899284258473985914L;
#Persistent
private String emailAddress;
#Persistent
private UserRole role;
/**
*
* Mapped from Userlist X from Operator Y
*/
#Persistent
private Users userlist;
public User(String email, UserRole role){
this.emailAddress = email;
this.role = role;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public UserRole getRole() {
return role;
}
public void setRole(UserRole role) {
this.role = role;
}
/**
* #return the userlist
*/
public Users getUserlist() {
return userlist;
}
/**
* #param userlist the userlist to set
*/
public void setUserlist(Users userlist) {
this.userlist = userlist;
}
}
PersistentUser and PersistentUsers Class are the same content (but because of JDO-AppEngine Inheritance Problem two seperate classes:
#PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
#Inheritance(strategy = InheritanceStrategy.SUBCLASS_TABLE)
#Version(strategy=VersionStrategy.VERSION_NUMBER)
public abstract class PersistentUsers implements IPersitentObject {
/**
* Id
*
* Autogenerated String id of the Database
*
*/
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
protected Key encodedKey;
#Persistent
protected String username;
#Override
public String getId() {
if(encodedKey == null) return null;
return KeyFactory.keyToString(encodedKey);
}
/*public void setId(String id) {
this.encodedKey = id;
}*/
/**
* Helper function - get Version from DB
*/
#Override
public Long getVersion(){
...
}
/**
* Helper function - will save this instance in DB
*/
public void persist(){
...
}
/**
* Helper function - will remove this instance from DB
*/
public void delete(){
...
}
#Override
public final boolean checkUsername() {
...
}
}
Create User Code:
...
if(RequestFactoryServlet.getThreadLocalRequest().getUserPrincipal() != null){
//Create New User
String email = RequestFactoryServlet.getThreadLocalRequest().getUserPrincipal().getName();
User u = UserFactory.getUser(email, UserRole.ADMINISTRATOR);
//u.persist();
//Create New Userlist
Users users = UserFactory.getUsers();
//Get Uids (normally empty)
LinkedList<String> uids = (LinkedList<String>) users.getUserIds();
if(uids==null){
uids = new LinkedList<String>();
}
uids.add(u.getId());
//Get DB-Userlist of current User-List
LinkedList<User> userlist = (LinkedList<User>) users.getUsers();
if(userlist==null){
userlist = new LinkedList<User>();
}
userlist.add(u);
users.setUserIds(uids);
users.setUsers(userlist);
u.setUserlist(users);
//Persit Userlist and Persist User
users.persist();
this.userlistId = users.getId();
}
...
Persistence Code:
public static void persist(IPersitentObject o){
PersistenceManager pm = Pmf.get().getPersistenceManager();
try{
pm.makePersistent(o);
} catch (Exception e) {
e.printStackTrace();
}finally {
pm.close();
}
}
I found the problem/solution
It's my stupid brain thinking i could fetch it while debugging.
My code is correct, but the information is not in the object while debugging!
Test it in a TestCase showed, that it works.
public class UsersTest {
private PersistenceManager pm;
private final LocalServiceTestHelper helper =
new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
private String userlistId;
private String userId;
#Before
public void setUp() throws Exception {
helper.setUp();
pm = ch.zhaw.ams.server.core.persistance.Pmf.get().getPersistenceManager();
}
#After
public void tearDown() throws Exception {
}
#Test
public void testNewUsers() {
//New UserList
//Create New Userlist
Users users = UserFactory.getUsers();
//Create New User
String email = "ss";
User u = UserFactory.getUser(email, UserRole.ADMINISTRATOR);
users.getUsers().add(u);
users.persist();
this.userlistId = users.getId();
this.userId = users.getUsers().get(0).getId();
//Test Users
pm = ch.zhaw.ams.server.core.persistance.Pmf.get().getPersistenceManager();
Users ul= pm.getObjectById(Users.class, this.userlistId);
assertNotNull(ul);
assertNotNull(ul.getUsers().get(0));
assertTrue(ul.getUsers().get(0).getId().equals(this.userId));
pm.close();
}
}