how to select a user id and merge the updated user inputs in respective fields - spring

i have a controller with #SessionAttributes("user_email") now i wish to do a merge operation for this particular user_email in session
i have a dao implementation class which performs merge operation as follows:
#Override
public boolean mergeusers(Users users) {
session.getCurrentSession().merge(users); //saves or updates the lawyer details //
return true;
}
but even though i give session.getcurrentSession it merges the new user input as a new user in the database instead of merging/updating the fiel that matches the session's user_email
im new to this could someone please tell me what im doing wrong

two options
populate the Id of the user before merging or
find the user from the database (findById) and update the data and merge it

Related

Create indirect relationships and return the sum of two relationships

I have a program to share services between people. Basically I am facing a problem trying to get the conversations between users. Here is the idea:
My program allows users to offer services to other users, but also to acquire services from other users. Each user can register an unlimited number of services.
When a user finds a service that he/she wants to get, he creates a deal and starts a conversation with the counterpart.
The structure of my tables is the following (I am only including the relationship columns):
Users table
id // This is the user identifier
Services table
id // This is the service identifier
user_id // This is the identifier of the user who created the service
Deals table
id // This is the deal identifier
user_id // This is the identifier of the user acquiring the service
service_id // This is the identifier of the service being acquired in this deal
Conversations table
id // This is the identifier of the conversation
deal_id // This is the identifier of the deal that the conversation belongs to
Here is my problem:
I want to be able to retrieve the conversations for each user, both as applicant and as a seller.
I created this relationship (in User.php) for conversations in which the user is acquiring the service:
public function conversationsApplicant(){
return $this->hasManyThrough( Conversations::class, Deal::class );
}
I would like to create also the conversationsSeller() function
public function conversationsSeller(){
return $this->????;
}
I am guessing I should add some kind of relationship between a Conversation and a Service in Service.php. It would be something like $this->services()->with( 'deals' )->with( 'conversations' );
The final goal would be to have a method that returns both relationships in one $user->conversations()->get().
public function conversations(){
return $this->conversationsApplicant() + $this->conversationsSeller();
}
To retrieve the relationship I was thinking that maybe there is a workaround using a SQL query, but I am not sure if that will return the relationship as I need it. Here is the query that I need to perform:
SELECT
conversations.*
FROM
mydb.conversations, mydb.services, mydb.users, mydb.deals
WHERE
users.id = services.user_id AND
services.id = deals.service_id AND
deals.id = conversations.deal_id AND
users.id = $user->id;
Here is how you implement merged relationship simply
public function getCombinedChats($value)
{
// There two calls return collections
// as defined in relations.
$Applicant= $this->conversationsApplicant;
$Seller= $this->conversationsSeller;
// Merge collections and return single collection.
return $Applicant->merge($Seller);
}

Does Eloquent handle caching of related entities?

I'm exploring Laravel's Eloquent as a drop-in replacement for my project's current, home-grown active record data layer. Currently, I have a class User that supports a many-to-many relationship with another class, Group. My current implementation looks something like:
class User {
protected $_groups; // An array of Group objects to which this User belongs
public function __construct($properties = []){
...
}
public function groups() {
if (isset($_groups))
return $_groups;
else
return $_groups = fetchGroups();
}
private function fetchGroups() {
// Lazily load the associated groups based on the `group_user` table
...
}
public function addGroup($group_id) {
// Check that the group exists and that this User isn't already a member of the group. If so, insert $group_id to $_groups.
...
}
public function removeGroup($group_id) {
// Check that the User is already a member of the group. If so, remove $group_id from $_groups.
...
}
public function fresh() {
// Reload user and group membership from the database into this object.
...
}
public function store() {
// Insert/update the user record in the `user` table, and insert/update/delete records in `group_user` based on the contents of `$_group_user`.
...
}
public function delete() {
// If it exists, delete the user record from the `user` table, and delete all associated records in `group_user`.
...
}
}
As you can see, my class:
Performs lazy loading of related groups, caching after the first time they're queried;
Maintains an internal representation of the User's relationship with their Groups, updating in the database only when store is called;
Performs sanity checks when establishing relationships, making sure that a Group exists and is not already related to the User before creating a new association.
Which, if any of these things, will Eloquent automatically take care of for me? Or, is my design flawed in some way that Eloquent can solve?
You can assume that I will re-implement User as User extends Illuminate\Database\Eloquent\Model and use Eloquent's belongsToMany as a replacement for my current fetchGroups method.
Eloquent caches the results of relationships internally, yes. You can see that in action in the Model::getRelationValue() method.
Eloquent also provides you with methods to help you manage the many-to-many relationship. You could implement this functionality inside your existing API. However, here are some things to look out for:
When using attach(), detach(), etc., the queries are performed immediately. Calling the parent User::save() method would only save the User's details, not the many-to-many relationship information. You could work around this by storing the IDs passed to your API temporarily, and then act upon them when you call User::store().
No sanity checks are performed when using attach/detach/etc. It would be good to apply these in your API if they're needed.
Adding or removing an ID to/from a many-to-many relationship will not affect the cached results of the initial relationship query. You would have to add in logic to insert or remove the related models into the collection.
For example, let's say a User has two Groups. When I load the user, I can access those groups using $user->groups. I now have a Collection of Groups cached inside the User model. If I call for $user->groups again, it will returned this cached Collection.
If I remove one Group using $user->detach($groupId), a query will be performed to update the join table, but the cached Collection will not change. Same goes for adding a group.

Check if User object exists in #DBRef List<User>

I'm making use of MongoDB, Spring Data and Spring MVC.
I have a user model which has a list of contacts:
class User {
#DBRef
private List<User> contacts = new ArrayList<User>();
public List<User> getContacts() {
return contacts;
}
}
I currently have 4 users inside my database. 1 user has a particular contact (who is referred to the same collection by id).
Now, I want to check whether a user has a particular contact. I use the following code:
User userLoggedIn = userService.getLoggedInUser(); //user object
User contact = userService.findById(contactId); //contact
if(userLoggedIn.getContacts().contains(contact)) {
System.out.println("Has this contact.");
}
This output message is not shown. However, if I print the list of contacts of the user and their id's, I clearly see that the contact is inserted inside the list of the user.
I noticed that if I print the hashCode of the contact object and the one that is inside the list, I get a different value, so I assume that even though the details are the same, the object itself isn't.
How can I approach this problem by simply checking whether he is inside the list. Or should I just compare by id?
Otherwise stated: how can I check whether an object exists in the contacts list?
You should override an equals method in User.
From JavaDoc:
boolean contains(Object o)
Returns true if this list contains the specified element. More
formally, returns true if and only if this list contains at least one
element e such that (o==null ? e==null : o.equals(e)).
With equals you must override and hashCode
http://docs.jboss.org/hibernate/core/4.0/manual/en-US/html/persistent-classes.html#persistent-classes-equalshashcode

Parse Android: update ParseObject containing an array of ParseUsers throws UserCannotBeAlteredWithoutSessionError

im working on an Android App.
I have a custom class which has relations with TWO ParseUsers and other fields. As suggested by the docs, I used an array (with key "usersArray") to store the pointers for the two ParseUsers, because I want to be able to use "include" to include the users when i query my custom class. I can create a new object and save it successfully.
//My custom parse class:
CustomObject customObject = new CustomObject();
ArrayList<ParseUser> users = new ArrayList<ParseUser>();
users.add(ParseUser.getCurrentUser());
users.add(anotherUser);
customObject.put("usersArray", users);
//I also store other variable which i would like to update later
customObject.put("otherVariable",false);
customObject.saveInBackground();
Also, i can query successfully with:
ParseQuery<CustomObject> query = CustomObject.getQuery();
query.whereEqualTo("usersArray", ParseUser.getCurrentUser());
query.whereEqualTo("usersArray", anotherUser);
query.include("usersArray");
query.findInBackground( .... );
My problem is when trying to UPDATE one of those CustomObject.
So after retrieving the CustomObject with the previous query, if I try to change the value of the "otherVariable" to true and save the object, I am getting a UserCannotBeAlteredWithoutSessionError or java.lang.IllegalArgumentException: Cannot save a ParseUser that is not authenticated exceptions.
CustomObject customObject = customObject.get(0); //From the query
customObject.put("otherVariable", true);
customObject.saveInBackground(); // EXCEPTION
I can see this is somehow related to the fact im trying to update an object which contains a pointer to a ParseUser. But im NOT modifying the user, i just want to update one of the fields of the CustomObject.
¿There is any way to solve this problem?
Maybe late but Parse users have ACL of public read and private write so you should do users.isAuthenticated() to check if its true or false.
If false then login with the user and retry. Note: you cannot edit info on two users at the same time without logging out and relogging in.
Another thing you can do is use Roles and define an admin role by using ACL which can write over all users.

Entity Framework saves duplicates of one side in a one to many

I am having a problem with Entity Framework in my MVC 3 application. I have a users table, which is only ever populated with a new user row when a machine entity is created by a user that hasn't created any machines before, i.e. it only creates users it hasn't seen before. Each user belongs to a sector (division of the company) which also must be set before the user and the machine are saved. I have a default sector that new users are assigned to (so that this may be changed later on).
I have some code in my machine controller class for the creation of new machines that looks like this:
[HttpPost]
public ActionResult Create(Machine machine)
{
if (ModelState.IsValid)
{
// work out if the user exists in the database already
var users = userRepository.All.Where(u => u.Username == machine.User.Username);
if (users.Count() == 0)
{
// if the user entry doesn't exist we have to create it assigning a default sector
Sector defaultSector = null;
var defaultSectors = sectorRepository.All.Where(s => s.IsDefaultForNewUsers);
if (defaultSectors.Count() == 0)
{
// jebus! no default sector, so create one
defaultSector = new Sector() { Name = "Default", IsDefaultForNewUsers = true };
sectorRepository.InsertOrUpdate(defaultSector);
sectorRepository.Save();
}
else
{
defaultSector = defaultSectors.First();
}
machine.User.Sector = defaultSector;
}
else
{
machine.User = users.First();
}
machineRepository.InsertOrUpdate(machine);
machineRepository.Save();
return RedirectToAction("Index");
}
else
{
ViewBag.PossibleInstalledOS = installedosRepository.All;
ViewBag.PossibleLicenceTypes = licencetypeRepository.All;
ViewBag.PossibleUsers = userRepository.All;
return View();
}
}
[Edit] Here is the body of the InsertOrUpdate method from my Machine repository:
public void InsertOrUpdate(Machine machine)
{
if (machine.MachineId == default(int)) {
// New entity
context.Machines.Add(machine);
} else {
// Existing entity
context.Entry(machine).State = EntityState.Modified;
}
}
The problem I'm having with this code is that when I save the machine, it keeps creating a new user even though that user is already in the system. The line that finds the user works and retrieves the user as I would expect but entity framework doesn't seem to understand that I wish to use this user that I've found and not create a new one. So at the moment I have multiple identical users (except ID of course) in my users table. I want a one to many here so that multiple machines are owned by the same user.
Does anyone have any idea how I force entity framework to respect that there is already a user there that I want to tie the new machine to?
You didn't post the code for your InsertOrUpdate method but I suspect that that is where the problem is. I bet in that method at some point you do something equivalent to:
context.Machines.Add(machine);
When you call DbSet.Add (or change the state of an entity to Added) you are actually adding the whole graph to the context. This process will stop when it encounters an object that is being tracked by the context. So if you have a machine object that references a user object and neither of these objects are being tracked by the context, then both the machine object and the user object will be added to the context and end up in an Added state. EF will then insert them both as new rows in the database.
What you need to do, which was alluded to in the other answer, is make sure than EF knows that an existing user object does exist in the database by making sure it's state is Unchanged (or possibly Modified) and not Added when you save.
There are various ways that you could accomplish this and it's hard to know which is best for you without seeing more of how your app and repository work. One way is to make sure that the context used to query for the user is the same context as is used to save. This way EF will already be tracking the existing user object and will know not to add it when you call Add.
Another way is to let your repository know somehow whether or not the user object is new. Often people use the primary key to determine this--a zero key indicates a new object, non-zero indicates an existing object. You could also pass a flag into your repository.
You can then call Add to add the graph, but then set the state of the User object to Unchanged (or Modified if it might have been changed since it was queried) if it is an existing user. This will prevent EF from inserting a new user into the database.
Can you double check that your repositories are using the same data context? If not, you are essentially adding a new User entity to the machineRepository. Alternatively you could attach the user to the context for the machine repository, but you'll likely keep running into bugs like this.

Resources