I have this piece of code:
public String getEventsForCalendar(#RequestParam("userId") Long userId){
Session session = NewHibernateUtil.getSessionFactory().getCurrentSession();
try{
session.beginTransaction();
JSONArray eventsArray = new JSONArray((List<Event>)(session.createCriteria(Event.class)
.add(Restrictions.eq("ownerid", userId))
.list()));
User user = (User)session.createCriteria(User.class)
.add(Restrictions.eq("id", userId)).uniqueResult();
for (Event event: (List<Event>) session.createCriteria(Event.class)
.add(Restrictions.ne("ownerid", userId))
.list()){
if (event.getInvited().contains(user)){
eventsArray.put(new JSONObject(event));
}
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
return null;
}
It, at first, should find Events created by User. Next, in loop it should get Events which User is invited. Each Events has List called invited and I think I have to iterate over all list and check if User is in invited list, but can I do something like?
List<Event> list = session(...)
.add(Restrictions.eq("invited", user);
In the other words, can I get from database Object which in list contains object? I will be very happy if anybody answers my question - thank you in advance.
You would use the Restrictions.in("colName", collection) method.
Edit:
If you want to do the inverse. If column is not in the collection then you can do:
Restrictions.not(Restrictions.in("colName", collection))
See http://docs.jboss.org/hibernate/orm/3.3/api/org/hibernate/criterion/Restrictions.html#in(java.lang.String, java.util.Collection)
Related
Im trying to use the findDistinct function from mongoTemplate but i always retrieve an empty result list.
Can you help me out to spot the problem ? Or maybe you have a simpliest way to do it
NB:
I do have data in my collection
(on a basic find, i fetch more than 300 results in the list but all of this result are the same excepting on one key, i want all the distinct object from their NAME value for instance )
I tryied this :
List<DiffusionListImpl> list = new ArrayList<>();
try{
query = new Query(Criteria.where("CUSTOMERNUMBER").is(1));
list = mongoTemplate.findDistinct(query, KeyWhereIWantTheDistinct, collectionName,
KlassResultModel.class);
} catch (MongoException e) {
logger.error("MongoException: " + e);
} catch (Exception e) {
logger.error("Error: " + e);
}
return list;
My bad, i misread the documentation.
But i find it akward to have this kind of comportement of this function.
I have to make a call to the DB to fetch a list of distinct value and then make another Call of the same DB to retrieve the object.
Is there any way to do it in one call? (Performance issue)
It can be done in one DB call, use below code.
final List<DiffusionListImpl> result =
IteratorUtils.toList(this.mongoTemplate.getCollection("collectionName")
.distinct("fieldName", query.getQueryObject(), DiffusionListImpl.class)
.iterator());
for IteratorUtils you can use apache
import org.apache.commons.collections4.IteratorUtils;
If we wanna get an object ID we should do this:
String objectId = gameScore.getObjectId();
but what if we wanna get an object ID by a query? Like this:
ParseQuery<ParseObject> query = ParseQuery.getQuery("mytable");
query.whereEqualTo("Title", "Adrians Book");
List<ParseObject> results = null;
try {
results = query.find();
if(!results.isEmpty()) {
String objectId = results.getObjectId();
}
} catch (com.parse4cn1.ParseException e) {
Dialog.show("Err", "Something went wrong.", "OK", null);
}
Sounds interesting don't you think? I wish it could be possible. As you can see in this example the query will get a value from a specific object in the table which could track for the object ID then returning it as well. ParseQuery class should be implemented with getObjectId(). Because by this way applications always could have access to object IDs from the query even after applications get restarted so in the first example the gameScore which is actually an instance of ParseObject would lost reference to the Database after restarting. Getting object IDs by the query it would be able to program applications to get object IDs automatically without the need of doing it manually nor depending on instances of ParseObject.
#Shai Almog: Thank you very much for taking your time to look at the ParseQuery documentation.
I accidentally figured out how to get this done!
ParseQuery<ParseObject> query = ParseQuery.getQuery("mytable");
query.whereEqualTo("Title", "Adrians Book");
List<ParseObject> results = null;
try {
results = query.find();
if(!results.isEmpty()) {
String objectId = results.get(0).getObjectId();
System.out.println(objectId);
}
} catch (com.parse4cn1.ParseException e) {
Dialog.show("Err", "Something went wrong.", "OK", null);
}
Yep, after adding the method .get(index) it allows you to access the method .getObjectId() since results is a list of a ParseObject, then the respective objectId of your query result will be printed in the console! I'm pretty glad it's working because I won't need to serialize each object for now which would be a pain.
Also if you wanna set an instance of ParseObject with an existing objectId in case you need to update something in your Database, you can use this example:
ParseObject po = ParseObject.create("mytable");
po.setObjectId(//YOUR DESIRED OBJECTID HERE, AS LONG AS IT EXISTS IN THE DATABASE);
As far as I know you need to get the whole object then query it's ID. I don't see a query id method here https://github.com/sidiabale/parse4cn1/blob/41fe491699e604fc6de46267479f47bc422d8978/src/com/parse4cn1/ParseQuery.java
I have different types of objects to update. All objects are set to a list and pass them to a method.
List list = new ArrayList();
list.add(mediaInfo); // Class MediaInfo
list.add(mediaMode); // Class MediaMode
list.add(paidCustomer); // Class paidCustomer
updateList ( l );
All above objects have loaded before and I have changed one field (called "position" : String value). Also above any object is not attached to any hb session. Those objects are loaded in another place. I just want to update them with updated data.
public boolean updateList(java.util.List <Object> dataList){
Session session = null;
Hbutility myHbutil = null;
try {
myHbutil = new Hbutility();
session = myHbutil.getSession();
Transaction tx = session.beginTransaction();
for(Object entity: dataList){
logger.info("Updating Objects : " + entity );
session.update( entity );
}
tx.commit();
} catch (Exception e) {
e.printStackTrace();
}finally{
session.close();
}
return updateStaus;
}
All objects have their id s. But they are not updated. Any one See any problem here ?
There are many samples of hibernate update in google. But all of them shows, loading a object inside the session, setting new values and simply updating. In my scenario, objects are loaded out of the session and all of them are different type of objects. Any help please.
To update the content, you can also use the merge method. Maibe it can help you ?
Try to get objet with the entities manager. Then modify the properties. And save change Exemple :
MediaInfo tmp = em.find(MediaInfo.class, mediaInfo.getId();
//Modify some properties
tmp.setMachin(....);
list.add(tmp);
updateList ( list );
Need to ensure that your mapping for 'position' is as per your expectation, ie it should'nt be transient and updatable should'nt be false
This is the DAO I have created:
public Poll updatePoll(int id){
Session s = factory.getCurrentSession();
Transaction t = s.beginTransaction();
Poll poll = (Poll) s.get(Poll.class, id);
Citizen citizen = (Citizen) s.get(Citizen.class, 1);
List<Poll> list = citizen.getPolledList();
boolean check = list.contains(poll);
if(!check){
Query q = s.createSQLQuery("update Poll set poll_count = poll_count + 1 where poll_id = id");
q.executeUpdate();
s.update(poll);
}else{
return poll;
}
s.close();
return poll;
}
This is the Action created:
public String submitVote(){
ServletContext ctx = ServletActionContext.getServletContext();
ProjectDAO dao = (ProjectDAO)ctx.getAttribute("DAO");
Poll poll = dao.updatePoll(poll_id);
String flag = "error";
if (poll != null){
ServletActionContext.getRequest().getSession(true).setAttribute("POLL", poll);
flag = "voted";
}
return flag;
}
I know I have been going horribly wrong and the code I'm posting might be utter rubbish. But I hope the intent is clear, thus if possible please lent me a helping hand. My project is mainly in JSP (Struts 2), jQuery and MySQL 5.1, so please do not suggest PHP codes as I've found earlier.
The framework is used to wrap the servlet stuff from user, you should use its features if you want doing something like
ServletActionContext.getRequest().getSession(true)
But
Map m = ActionContext.getContext().getSession();
I am trying to do some big lists of object saving using hibernate..
problem is before saving I need to confirm if a record with same field data already exists if yes then need to fetch its id and create an association in another table.. else make a new entry and a new insert in the association table for the same..
Please guide me how I can improve the save time..
following is how the save is done..
Session session = SchemaManager.getDatabaseSession("com.server.domin.PublicaccountBehavior");
try {
List<Post> posts = this.getAllPosts();
Transaction transaction = session.beginTransaction();
for (Post post : posts) {
Behavior behavior = new Behavior();
behavior.setElementValue(val);
behavior.setIsDeleted(false);
Date now = new Date();
behavior.setCreatedOn(now);
behavior.setModifiedOn(now);
PublicaccountType type = new PublicaccountType();
type.setId(3L);
behavior.setPublicaccountType(type);
PublicaccountBehavior publicaccountBehavior = new PublicaccountBehavior();
publicaccountBehavior.setBehavior(behavior);
publicaccountBehavior.setPublicAccount(account);
publicaccountBehavior.setTimeOfBookmark(post.getTimeAsDate());
publicaccountBehavior.setCreatedOn(now);
publicaccountBehavior.setModifiedOn(now);
try {
Behavior behav;
List list2 = session.createQuery("from Behavior where elementValue = :elementVal").setString("elementVal",
behavior.getElementValue()).list();
if (list2.size() > 0) {
behav = (Behavior) list2.get(0);
publicaccountBehavior.setBehavior(behav);
} else {
Long id = (Long) session.save(behavior);
behavior.setId(id);
publicaccountBehavior.setBehavior(behavior);
}
session.saveOrUpdate(publicaccountBehavior);
} catch (HibernateException e) {
e.printStackTrace();
}
}
transaction.commit();
When you are saving a new object - flush() and then clear() the session regularly in order to control the size of the first-level cache. which will enhance the performance.
example is explained in hibernate docs.