I have created a web application with google app engine.
I have a kind named userbean. It has details related to user such as name, age and email.
I have creater a bean class for it.
I have added and deleted entities to it.
But when I create a new kind called wordbean and tried to store data of this type to datastore, it doesn't save them in datastore. How to create a new kind and store it in google datastore?
Is there any rule that only one kind can exist in a datastore?
//controller class
//function which requests parameters from user through html, jquery
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Transaction txn=datastore.beginTransaction();
Entity Word = new Entity("WordBean");
Word.setProperty("word", "அறிவியல்");
Word.setProperty("length", "5");
Word.setProperty("start", "அ");
Word.setProperty("starttwo", "அறி");
Word.setProperty("Detail", "பாடங்களில் ஒன்று.");
datastore.put(Word);
txn.commit();
//end
Related
I am working on a springboot project and I am a total newbie in this. We are told to complete the project within a given time period and the deadline is in 3 days. I have a string which will contain the username. I am said that there will be an external database from where we have to fetch the data of that user and return that to the application. We are working on a web api.
Till now I have somehow extracted the username from the encoded data but now I am unable to proceed further. All the resources available online are related to building a repository and their own data and use that in the program but I have to use it from an external database. I don't know anything about this and is completely stuck.
The external database is a sample and includes an id , username and data. From the username we have to search the database and return all the three details as a JSON format of that user.
Well that was simple in SQL but I don't know how that can be performed from the point where I am now.
Thank You.
There is a special file called application.properties in Spring Boot, where you can define your authorization data to get connection with your remote database.
Usually, you should specify basic data:
spring.datasource.url=jdbc:mysql://url-to-your-external-db/name-of-db
spring.datasource.username=your_username
spring.datasource.password=your_pasword
After that, you could retrieve your data from database using JpaRepository for example. There is plenty of frameworks that will serialize/deserialize your Java objects/entities to JSON (Jackson for example).
Example of fetching users from a database using JpaRepository:
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByFirstName(String firstName)
}
where User could be your POJO which represents a table with users in database.
I'm in the middle of fumbling around with JPA. I've so far successfully created an entity representing the user data and a stateless bean for the access to the user data.
The data the users can work on is like this (SQLFiddle link):
CREATE TABLE data
(
email character varying(128) NOT NULL,
data character varying(128) NOT NULL,
lastchange timestamp NOT NULL,
CONSTRAINT email_data PRIMARY KEY (email,data)
);
The idea is to save the unaltered, current version for all users with an empty email key. Then, when a user alters the data and creates an auditable version, the email field is filled with the users email. This way, each user can alter their copy of the data. The merging is a problem for a later date and not part of my question.
Now, I have the entities already in place. I created a stateless bean to load/save/find the data records by using the EntityManager. The logic to load the user specific version first, then load the unaltered version if the user has no user specific version still eludes me.
Consider this part of the bean:
#Stateless
public class DataBean {
#PersistenceContext(unitName = "authPU")
private EntityManager em;
public List<DataEntry> findAll() {
TypedQuery<DataEntry> query = em.createQuery("SELECT d FROM data d", DataEntry.class);
List<DataEntry> list = query.getResultList();
return query.getResultList();
}
...
}
How do I inject the user information into this class? I need to get the data for the current user first, then get the data for all users if there's no user-specific data available.
You could use standard EJB authentication. Then you can call SessionContext.getCallerPrincipal() in your session bean to get a user ID. Use this user ID to query the database.
In this case you have to add another column to your table (containing the user ID), if the authentication user ID does not equal the email address.
Far simpler (but less elegant) is to add the email address to the arguments of your EJB service method: Just make it part of the public API.
in a school project we are using an EJB Session Bean,
this EJB offers simple services such as add, delete, modify, findAll, findbyId. Such methods are implemented using hibernate 4.0 (add -> saveOrUpdate, modify -> saveOrUpdate...) and are available for the client
I have two classes : Game (id, description, category) and Category (id, title).
A category has also a set of games.
The ids are generated using the identity generator. The databased used is mysql.
In the client
A form is used by the application user to fill out informations about a game (description and category ) In the controller I use the method findById to get the category that the user chose, then I create a new game with this category and I save it (using SaveOrUpdate)
first problem that I notice : the id is generated correctly in the EJB and the game passed is modified but back in the client the game doesn't have an id (I guess passing objects between a client and a EJB is not by reference) Can anyone confirm it ?
second problem : when the game is save I tried to add this game to the set of the category and update this category (using also saveOrUpdate). I get the exception org.hibernate.NonUniqueObjectException:
a different object with the same identifier value was already associated with the session
which I don't understand
Can anyone help me ?
For the first question, it sounds like the ID isn't being sent back to the client, or being stored with the controller .
You could send it back to the client by adding it to the URL, ie, in the return from the client call add "?id=" + newGameId
With this you can have the value populate back into the controller with setters and getters for an id field;
long id;
To upload data to the datastore I use this java code :
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
Entity entity = new Entity("mydetail");
entity.setProperty("entry", "entry");
ds.put(entity);
For uploading form based data is this the correct method of uploading data, ie using similar code above or is there another API I should be using ?
Yes, this the direct API to the AppEngine Datastore.
You can also use JDO interface which allows for directly storing a Java object without dealing with the Datastore API:
import javax.jdo.annotations.Persistent;
#PersistenceCapable
public class MyDetail {
// ...
#Persistent
private String entry;
// ...
There is also the JPA interface. Both of the interfaces are described on the App Engine website.
The Objectify interface is very easy and for many situations easier. It is not part of the official SDK.
You can use whichever makes more sense for you application.
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.