I have two objects, Customer and Store. I would like a user (from a user table) to be able to specify a customer or store as "preferred". I would then be able to see a list of users who prefer different stores or customers. Is this possible with a hibernate mapping?
What would the table structure look if a status of preferred could be set on either customer of store per user?
So, a User has many preferred Stores, and a Store is the preferred store of many users. This is thus a ManyToMany association between User and Store.
Just map it as explained in the documentation:
public class User {
#ManyToMany
private Set<Store> preferredStores = new HashSet<Store>(0);
}
public class Store {
// necessary only if you want the association to be bidirectional:
#ManyToMany(mappedBy = "preferredStores")
private Set<User> preferringUsers = new HashSet<User>(0);
}
Related
I have a database that keeps tracks of my (registered) users. Every user can be (and is by default) part of a team. A team groups together multiple users.
Since users can be part of multiple teams, I would like for them to be able to toggle on and off certain teams. When turned off, the team's data won't be shown to that user in the frontend. When multiple organizations are toggled on, all the data is shown simultaneously.
So my question is: How should I go about this architecturally? Is there a "right" way of doing things? I am using Prisma with a Planetscale (MySQL) database, however I do appreciate any theoretical answers as well.
In Prisma, my (simplified) schema currently looks like this:
model User {
id String #id #default(cuid())
name String?
teams Team[]
}
model Organization {
id String #id #default(cuid())
name String
users User[]
}
Technically, I would think that I would simply like to mark a team as "active" or "inactive", but I'm not seeing how to do that exactly. Simply adding an active Boolean attribute to the team wouldn't work, since I won't be able to tell which user that applies to, correct?
The only way that I know that works is to have both an ActiveTeam reference as well as an InactiveTeam reference on my user table instead of having just a teams reference. This does seem unnecessarily complicated though and I'm hoping there is an easier way of doing it.
As #Barmar said, you can use a juntion table to accomplish this.
The schema will look somthing like this:
model User {
id String #id #default(cuid())
name String?
userTeams User_Team[]
}
model Team {
id String #id #default(cuid())
name String?
userTeams User_Team[]
}
model User_Team {
userId String
user User #relation(fields: [userId], references: [id])
teamId String
team Team #relation(fields: [teamId], references: [id])
isActive Boolean
##id([userId, teamId])
}
// Your other models ...
I am looking for a spring based solution for this problem. I have solved this in crude way but looking for better solution.
I have a client server architecture application.
Based on user permission, I am able to :
get list of fields for loggedin user which he is not permitted to write.
get list of fields for loggedin user which he is not permitted to read.
Now, how can I verify that the object to be written into database is as per user permission in an efficient way. I can iterate over fields, check if its value is different from that stored in db and reject accordingly. Is there any effecient way ?
Example:
One domain entity "Account" which is stored in MongoDB.
class Account {
String name;
String email;
String mobile;
}
Corresponding DTO Object to be returned to client
class AccountDto {
String name;
String email;
String mobile;
}
Two User -> User A, User B
Scenario:
User A can edit [ name ] but not email, mobile.
User A can view [name, email] but not mobile.
How can I design to return only those field which he is permitted to view. I donot want to create numerous DTO based on every user permission.
How can I write a code to check that the Object to be written to database is valid as per permission assigned to loggedin user. I dont want to iterate over fields and check field permission and then discard. Expensive operation.
My solution: Whenever user is going to write to db, I can fetch the existing record , compare with the record he is going to write and reject if field value is changed if he has not that permission. But this adds DB read cost and is not that generic solution.
Hello i just realized how very confused i am by these relations, I have a question i need to ask. Assuming i have two table with records.
Roles
Administrator
Manager
Employee
Users
User 1
User 2
User 3
Now i want to create a relationship between these two tables, in this situation each user can have only one role but how do i express this relation?
To be more specific is it the user row in the table that can have only one role or the users table as a whole?
If it is the users table as a whole that can have only one role then in a situation where User 1 and User 2 are both administrators will the relationship then become many to many?
You might start by reviewing the documentation on relationships in Laravel/Eloquent: http://laravel.com/docs/5.1/eloquent-relationships
Your classes will look something like this:
class User extends Model
{
public function role()
{
return $this->hasOne('App\Role');
}
}
class Role extends Model
{
}
This means that each User has one Role - it doesn't prevent the same role from belonging to multiple users.
I seems it will become.
Role model
public function users()
{
return $this->hasMany('App\User');
}
User model
public function role()
{
return $this->belongsTo('App\Role');
}
so means, a Role can have many users and a user belongs to a role.
so User1 and User2 can be both Administrators. Check out laracast for additional info on relationship
I think, will be better, to use ManyToMany in Role-User reations, because, if you want now to use one role for one user, in future, probably, you will need to user more than one role to user. Also, ManyToMany not slower, than One-to-Many, but it more powerfull decision.
Role model
public function users()
{
return $this->belongsToMany('App\User');
}
User model
public function role()
{
return $this->belongsToMany('App\Role');
}
I have 2 classes named User.groovy and Employee.groovy and I used MYSQL to save the data. What I want is to create a new User account and save it to the User table and also save some of the data to Employee table. How can I do this? I've tried extending the user to Employee but the data only saved to User and not to Employee. But If I don't extend the User, the data is only saved to Employee. What should I do so that the data simultaneously saves to two database tables at the same time? Please help me.
Actually have this in my class user:
class User {
transient springSecurityService
String username
String password
boolean enabled
boolean accountExpired
boolean accountLocked
boolean passwordExpired
.....}
and employee:
class Employee {
String name
String email
String jobDesc
....}
So what should I do next? I'm sorry for this, I'm still starting to learn grails.
Grails paradigm (as far as scaffolding is concerned) is one form - one object. As long as you stick to this paradigm, you get all the goodies, such as input validation and error reporting for free (you may also consider using the Fields plugin here http://grails.org/plugin/fields).
However, sometimes you need to collect info and create two or more objects through single form. Usually this happens when you need to initiate new subscription and collect info for both subscription details (say, Subscription entity) and user info (User entity). This is where command objects come to rescue.
http://grails.org/doc/latest/guide/theWebLayer.html#commandObjects
So, instead of expanding/bending SubscriptionController or UserController (or UserController and EmployeeController, as per your example), you create SignUpController, which handles SignUpCommand object. The SignUpCommand object is not intended to be saved, it is used as a backing object for the SignUpController.create form. When it validates, you use the signUpCommand object data to initialize 2 domain objects (that is Subscription and User) and save these objects individually within the same transaction.
You can either delegate the save operation to a service say,
if (signUpCmd.validate()) {
SignUpService.save(signUpCmd))
}
or create and save both objects right on the spot within controller
if (signUpCmd.validate()) {
Subscription subscription = new Subscription(plan: signUpCmd.plan, ...)
subscription.save()
User user = new User(username: signUpCmd.username, ...)
user.save()
}
it is mostly matter of taste and style.
Instead of calling save() directly to your user instance, call a service class that saves both the user and the employee in one atomic operation. Like, for instance:
class UserController {
/*Injection of your service in the controller class*/
def userService
And then in the save action in this same controller:
userService.save(user) // userService.save(params)
And inside this service method you will extract the data (user or params, whatever floats your boat) you want to save in a different table as long as the usual user object.
I'm using LINQ to SQL to access my database but I'm only reading, I never insert, update or delete anything. Are there ways to optimize LINQ2SQL for this?
Yes there is. Linq 2 SQL will by default cache all data that you read from the DB. It needs to do this to track any changes you apply to your objects, so it can generate the necessary insert/update/delete statements when you call SubmitChanges()
If you're only reading data, this is unnessecary. You can turn off object tracking by setting the ObjectTrackingEnabled property to false on your DataContext.
One thing I've been told, is to avoid using the generated record class.
That is, if you have a Users table, L2S will create for you a User class, which is what it returns from the database. Instead of using that directly, you should create a "shadow" class --- all the same Properties, but nothing else, and immedaitely copy the data into those records for your use. In fact, if it's going to be exclusively read-only, you can assign them in the ctor, and only have public getters:
class myUser
{
public string FName {get; private set}
public string LName {get; private set}
public myUser(User user)
{
this.FName = user.FName;
this.LName = user.LName;
}
}
var users = from u in db.Users
where .....
select new myUsers(u);
This avoids a lot of overhead needed to deal with the possibility of writing the object out again.