I'd like to store my Android application's data in a Parse.com database, but I'm having trouble right now. I'm trying to save my own 'Parent' class. The Parent class has different attributes. Right now I'd like to store these:
private String email;
private String password;
There are more attributes, but atm I'm not filling em up during runtime, will do so later when I know the whole idea works.
I am aware of the classes ParseUser and ParseObject, a user and an object class of Parse, which can be used to store data to their DB. Now my first approach was to let my own Parent class inherit from Parse's ParseUser or ParseObject. That way my class would have access to the Parse's methods, while maintaining my own attributes and methods. I tried that and I don't think it works. It gave a vague error, with no clear error message. (click on the next link for a pic http://i.imgur.com/orkmjXO.png )
Right now my Userr class inherits from ParseObject. Well not directly, but it has access to ParseObejct's methods. the hierarchy goes like this ParseObject -> (mine) User -> (mine) Parent. Below I pasted the code I use at the point of saving.
Parent user = new Parent();
user.setEmail(mEmail);
user.setWachtwoord(mPassword);
user.put(mEmail, user);
user.saveInBackground();
Could anyone help me and tell me how I can store my own classes in Parse? Any kind of help would be appreciated, like possible causes and such. Thanks!
as per the parse docs, looks like ParseObject is like a Map.
refer: https://www.parse.com/apps/quickstart#parse_data/mobile/android/native/new
ParseObject testObject = new ParseObject("TestObject");
testObject.put("foo", "bar");
testObject.saveInBackground();
so I guess, in you case this would translate to:
user.put("mEmail", "user1");
user.saveInBackground();
Related
I'm creating a website for a school project which uses spring for the backend. I'm trying to insert data into the database when new data is saved to a specific table.
I've tried using #HandleAfterCreate and #PrePersist, but neither worked. I'm not very experienced with spring. The teacher told us to use it and now I don't know what do.
#HandleAfterCreate
public void handlePersonBeforeCreate(Person person){
logger.info("Inside Person Before Create....");
Set<Qualifikation> qualifikationen = new HashSet<>();
kompetenzRepository.findAll().forEach(kompetenz -> {
Qualifikation qualifikation = new Qualifikation();
qualifikation.setAusmass(0);
qualifikation.setKompetenz(kompetenz);
qualifikation.setPerson(person);
});
person.setQualifikationen(qualifikationen);
System.out.println(person.getDisplayName());
}
The code should set a person's "Qualifikation" to a default value when the person is inserted (via OAuth login). It should have every "Kompetenz" with a value of 0 by default. Kompetenz has a 1 to n relation to Qualifikation. If you need more information please ask me.
It looks like you're trying to have access to the repository layer of your application inside an entity. This is generally not a good idea, as the entities should only know about the data they hold, not the other application components.
In this particular case it would be wise to use a #Service class with a method that you can call to insert the data into the database. In the method you could then insert any other entities as well. Let your repositories be fields of the service and make them #Autowired.
I think you need to enable JPA auditing . It can be enabled in Spring by add #EnableJpaAuditing to your persistence configuration. This tells Spring to listen JPA entity lifecycle events and call the annotated methods in appropriate places.
Also I think you should make the callback method private if it is meant to be called only when persisted (#PrePersist).
See details here. In this article is also presented entity listeners which might also be a good solution when dealing with multiple entities having a need for same pre-persist functionality.
I think you should create a service class, a repository class and an entity which will be stored through repository. The logic of getting all inner elements and filling it with default value is to be written in service and not a good idea to write in entity class.
If you need any help regarding it, let me know .
Welcome to community!!
I have a couple of domain classes which all inherit a BaseDomain class.
In this BaseDomain class I have a field that is public final String name;
The value of name is set in the constructor.
public class BaseDomain {
public final String name;
public BaseDomain() {
this.name = this.getClass().getCanonicalName();
}
}
This BaseDomain is extended by a few classes
public class Trip extends BaseDomain {
private int id;
public Trip(int id){
this.id = id;
}
}
So far so good.
I want to get the value of the field "name" in an object instance of Trip of a with the help of JXPath but can't. I can access the "id" field but not the "name" field.
JXPathContext jxPathContext = JXPathContext.newContext(trip);
jxPathContext.setLenient(true);
int id = (int)jxPathContext.getValue("/#id"); // This works.
String name = (String)jxPathContext.getValue("/#name"); // This does not work.
Is it possible to get the value of "name" with this setup and JXPath?
The code might have some syntax errors and/or other errors. I hope you all get the idea and understand my question.
Any help or pointer are welcome.
First of: I want to thank Kelly S. French for his quick replay.
It made me realize that I have to explain some more.
I want to use jxpath because I will eventually do a deeper search. For example: The Trip might hold a list of Locations which also extends the BaseDomain. Each Location can hold a list of PointOfInterest that extends BaseDomain.
Via reflection in other part of the code I want to be able to get a list of BaseDomain based on their type (class.getCanonicalName())
The object-tree is not based on xml, it is pure POJO.
As far as I have figured out, there is no way of writing a jxpath-query for finding a list of objects based on their type, class name and so on.
Is this correct?
Does some one know of a way to do that?
The easiest way out, even if it's ugly, is to have a field in the super class that holds the class-name. That is why I have done this ugly solution.
Eventually I want to create a jxpath-query that based on the trip returns an iterator of which ever object that is an instance of BaseDomain at any depth and not depending on which branch in the object tree the node is located, as long as I can get the class-name of the object I'm looking for.
Does any one know if it is possible to achive this with a jxpath-query?
Code example, links to blogs or other documentation is welcome and appreciated.
As before, I'm very grateful for any help.
if you have the trip instance, why can't you do this
string n = trip.name;
I can see that you have an XML representation of the trip, but using XPath would be for when you only have the XML for 'trip'.
If you still need to get name using XPath, post the XML that is generated. I would be willing to bet that the name attribute is not part of Trip, but part of the enclosing BaseDomain. If you are basing the jxPathContext on the Trip, you've already passed the nodes for the BaseDomain. You'd have to navigate back up somehow (like node.parent) or do that when you create the context,
// not sure about this approach
JXPathContext jxPathContext = JXPathContext.newContext(trip.super);
After looking at the JXPath manual on parent/child relationships why don't you try this:
String name = (String)jxPathContext.getValue("/Trip/../#name");
// or use "../#name", not sure it wouldn't need to be "/../#name"
I have two following domains:
User {
UserData userData
}
UserData {
static belongsTo = [user: User]
}
and at some point I want to merge two users into one. I mean delete one instance of User and attache userData to another user.
I've tried:
User zombieUser
User liveUser
UserData data = zombieUser.userData
zombieUser.delete()
liveUser.userData = data
userData.user = liveUser
userData.save()
liveUser.save()
Actually I've tried different variants, different order, seems that all possible ways. But it always fails with an exceptions. Current code will fail with:
deleted object would be re-saved by cascade (remove deleted object from associations): [UserData#1]
If i've put zombie.delete() to bottom, after *.save(), I will get:
Field error in object 'User' on field 'userData': rejected value [UserData : 1]; codes ... default message [Property [{0}] of class [{1}] with value [{2}] must be unique]
Are there any way to reconnect existing object from one object to another?
Working code:
UserData userData = zombieUser.userData
userData.user = null
zombieUser.userData = null
zombieUser.save(flush: true)
userData.save()
liveUser.userData = userData
userData.user = liveUser
liveUser.save()
userDate.save(flush: true)
The problem is that because of your belongsTo declaration, and according to cascading rules, userData is deleted from the database as soon as zombieUser is deleted. When liveUser.save() is called, userData would be saved again. By the way, you call to userData.save() is not needed as again, because of this belongsTo declaration, liveUser.save() is cascaded to userData.
I see two options for solving your problem:
Perform a deep copy of userData to a new UserData object, and attach this object to liveUser, like this:
withTransaction {
UserData data = new UserData(prop: zombieUser.userData.prop)
liveUser.userData = data
zombiUser.delete()
liveUser.save()
}
The old UserData object will be deleted by cascade when deleting zombieUser and a new one will be created when saving liveUser.
Remove belongsTo from userData. You won't benefit of cascading anymore, and will have to manage saving userData yourself, and make sure user.userData is deleted from the database when no user reference it (don't forget to make transactions for that, as always when you have several call to save or delete in your method).
Which approach you choose depends on how coupled your objects are. Typically, if they are very coupled, you will benefit of cascading (through belongsTo) and may go for 1. If they are not very coupled, (i.e. there may be several users with the same userData), then belongsTo is wrong and you should choose approach 2.
The concepts presented in GORM gotchas will greatly help you if you have a GORM model with complicated dependencies.
You need to add a mapping to your domain class to tell it what to do when you delete an object. For example, should deleting a parent also delete all its children??
static mapping = {
userData cascade: "all-delete-orphan"
}
I'm trying to save a UserOnline object, which has a OneToOne relationship with User, in the database. I want to create a new one if it doesn't exist, and if it does exist, simply change the room.
This is the code I'm using:
UserOnline uo = (UserOnline) UserOnline.find("byUser",
getConnectedUser()).first();
if (uo == null) {
uo = new UserOnline(getConnectedUser(), room);
room.save();
} else {
uo.currentRoom = room;
uo.save();
}
For some reason, even though the uo is actually null, the object isn't actually saved. Any ideas why that is? It's not giving me an error, it just isn't creating the record. I'm also wondering how I could create a UserOnline object starting from the User object.
Something like
User user = User.findById(1);
user.onlineStatus.room = room.
user.save();
Can related objects be (created if they don't exist and otherwise edited) saved this way?
User.java
#OneToOne(mappedBy="user")
public UserOnline onlineStatus;
The save() method is from the play framework.
I guess this question is related to Play Framework. If so, it would be better to mark it as such, since use of Hibernate in Play Framework has some pecularities, see Explicit save.
Regarding the question, Play Framework's save() is cascaded on relationships that have cascade=CascadeType.ALL on them. If your relationship in question is configured this way, it should work fine.
I am building an app based on google app engine (Java) using JDO for persistence.
Can someone give me an example or a point me to some code which shows persisting of multiple entities (of same type) using javax.jdo.PersistenceManager.makePersistentAll() within a transaction.
Basically I need to understand how to put multiple entites in one Entity Group so that they can be saved using makePersistentAll() inside transaction.
This section of the docs deals with exactly that.
i did this:
public static final Key root_key = KeyFactory.createKey("Object", "RootKey");
...
so a typical datastore persistent object will set the id in the constructor instead of getting one automatically
public DSO_MyType(string Name, Key parent)
{
KeyFactory.Builder b = new KeyFactory.Builder(parent);;
id = b.addChild(DSO_MyType.class.getSimpleName() , Name).getKey();
}
and you pass root_key as the parent
i'm not sure if you can pass different parents to objects of the same kind
Thanks for the response Nick.
This document only tells about implicit handling of entity groups by app engine when its a parent-child relationship. I want to save multiple objects of same type using PeristentManager.makePersistentAll(list) within a transaction. If objects are not same Entity Group this throws exception. Currently I could do it as below but think there must be a better and more appropriate approach to do this -
User u1 = new User("a");
UserDAO.getInstance().addObject(user1);
// UserDAO.addObject uses PersistentManager.makePersistent() in transaction and user
// object now has its Key set. I want to avoid this step.
User u2 = new User("x");
u2.setKey(KeyFactory.createKey(u1.getKey(),User.class.getSimpleName(), 100 /*some random id*/));
User u3 = new User("p");
u3.setKey(KeyFactory.createKey(u1.getKey(), User.class.getSimpleName(), 200));
UserDAO.getInstance().addObjects(Arrays.asList(new User[]{u2, u3}));
// UserDAO.addObjects uses PersistentManager.makePersistentAll() in transaction.
Although this approach works, the problem with this is that you have to depend on an already persistent entity to create an entity group.
Gopi, AFAIK you don't have to do that... this should work (haven't tested it):
List<User> userList = new ArrayList<User>();
userList.add(new User("a"));
userList.add(new User("b"));
userList.add(new User("c"));
UserDAO().getInstance().addObjects(userList);
Again, AFAIK, this should put all these objects in the same entity group. I'd love to know if I am wrong.