New table for Primary/Foreign key Relationship in ORMLite - orm

I have a User table with the following details in my android DB
username, password, email, mobile,
I have another table named Service with the following detail in my android DB
service name, service category, service description
Now, I want to associate the relationship for every user (eg: username) with his/her service (service name) using ORMLite.
I want to maintain a seperate table for this relationship. Now, my question goes like this
Is is possible for ORM that it generates a table if I specify the primary key and foreign key relation, such that it can populate the data for every service getting added ?
Do I have to create a bean maintaining the common fields between my user table and service table and do the insertion task manually whenever a new service is added ?
-Thanks
Srikant

Looks like you may have solved you own problem but I'll still answer for posterity. ORMLite calls this relationship between User and Service a "foreign object" fields. Here's the documentation for foreign objects. It sounds like User is associated with a service so your User class would have a Service service; field. Something like:
public class User {
...
#DatabaseField(canBeNull = false, foreign = true)
private Service service;
}
Now your questions:
Is is possible for ORM that it generates a table if I specify the primary key and foreign key relation, such that it can populate the data for every service getting added ?
ORMLite does not handle foreign key limitations although you can tune the schema yourself to add it. If you setup the foreign key then it will use the primary key from Service in your User table.
Do I have to create a bean maintaining the common fields between my user table and service table and do the insertion task manually whenever a new service is added ?
Not sure I understand the question. All you need to do is create your Service using the serviceDao and then add the server to your User before creating it using the userDao.

Related

Adding ASP.NET Identity to an existing project with already managed users table

I have an existing web api project with a users table. In general User is involved in some key business queries in the system (as other tables keep its 'UserId' foreign key).
These days I'm interested in adding Asp.net (core) identity. Basically I've already performed the required steps adding a separate Identity table, managing an additional db context (implementing IdentityDbContext), and also added a JWT token service. It looks that everything works fine. However I am now wondering how should I "link" between the authenticated user (which has logged in through the Identity module) and the user which is found on the other original "business related db".
What I was thinking of is that upon login, having the userId retrieved from the original Users table, based on the email which is used as the username and is found on both the original Users table and the new Identity table, and than have it kept as a Claim on the authenticated user. This way, each time the user is calling the API (for an Authorize marked action on the API relevant controller), assuming is authenticated I will have the relevant userId on hand and be able to address and query what ever is needed from the existing business table.
I guess this can work, however I'm not sure regarding this approach and I was wondering if there are any other options?
Regarding the option I've mentioned above, the main drawback I see is that upon the creation of a new user, this should be performed against 2 different tables, on 2 different DBs. In this case, in order to keep this in one unit of work, is it possible to create transaction scope consists of 2 different db contexts?
You're on the right track.
I faced similar problem
Imagine two different microservices.
Identity-Microservice(Stores identity information (Username, Password Etc...))
Employees-Microservice (Stores employee information (Name, Surname Etc...))
So how to establish a relationship between these two services?
Use queues(RabbitMq, Kafka etc...)
An event is created after User Registration(UserCreatedEvent {Id, Name etc..})
The workers microservice listens for this activity and records it in the corresponding table
This is the final state
Identity
Id = 1, UserName = ExampleUserName, Email = Example#Email Etc...
Employee
Id = 1, Name = ExampleName, Surname = ExampleSurname Etc...
Now both services are associated with each other.
Example
If i want to get the information of an employee who is logged in now.
var currentEmployeeId = User.Identity.GetById()
var employee = _db.Employee.GetById(currentEmployeeId)

Foreign key or boolean value in database

Let's say I have a database with two tables, User and Store.
Lets make the rules:
A User must belong to one Store
A Store may have one or more Users
A store though, may have a store manager. What is the best approach for this?
Adding a 'is_store_manager' boolean column at the Users table, or create a foreign key called something like manager_user_fk at the Store table? I guess that would create a many to many relationship though, which would be bad, but it would be a solid constraint to select a user I think. What would be the best approach?
Don't create a fk on the Store. It is somewhat redundant and will make some future SQL queries harder.
You could add another table, UserType with the Manager, and Non-Manager types. You'd then add a fk on the Users table pointing to the UserType.
Edit:
If you wanted a user to be allowed multiple roles, you'd need another join table:
Let's call the previous table table Role, instead of UserType, and add another table, UserRole that is a join between User and Role (it has only 2 columns: a foreign key to User, and a foreign key to Role. With this setup, you wouldn't have any fk on the User table, as this join table would hold all the information about the relationship. A user could have as many roles as you like then.
An alternative to the accepted solution which only allows a user to be of one type you can use what I've been doing to replace boolean status fields. Create a table called UserManager with a primary key also being a foreign key to User.
Any user with an entry in UserManager is a manager. To get the managers you just join the User table with the UserManager. This also lets you store more meta data (i.e. you could store when the user became a manager etc).
Then if you want an AdminUser table, you do the same thing. Any user in the AdminUser table is also an admin. You can have a user be both (or none, or one). Along with storing more meta data about the type.

Apply a not null constraint via a many-to-many relationship?

I need to make sure that every project in my database has a contact person. "projects" and "contacts" have a many-to-many relationship, specified in the table "projects_contacts". Could I create a table constraint within projects that will specify the project must exist within the join table? Or do I need to take a completely different approach?
(I need users to be able to manually enter contact data while in the middle of adding project data, so I'm worried that the NOT NULL will hang up their ability to create a project before there is a contact.)
Would this be better addressed in the build of the user interface?
Thanks!
CREATE TABLE projects(
id_project INTEGER PRIMARY KEY,
description text)
CREATE TABLE contacts(
id_contact integer PRIMARY KEY
firstname varchar(100) )
CREATE TABLE projects_contacts(
id_projects_contacts integer PRIMARY KEY,>
id_project integer,
id_contact integer
CONSTRAINT FOREIGN KEY project_fkey (id_project) REFERENCES projects ON UPDATE CASCADE ON DELETE CASCADE
CONSTRAINT FOREIGN KEY contact_fkey (id_contact) REFERENCES contacts ON UPDATE CASCADE ON DELETE CASCADE)
The only way you could implement this with a table-level constraint is for projects to contain a non-nullable foreign key reference to any entry in projects_contacts.
But this would be a circular reference, since projects_contacts also depends on `projects.
You said you don't want to force users to enter a contact while they're still creating a project, so basically you can't constrain a project with a non-nullable reference like that.
There is no constraint that means "I need this to be non-null, but later." It's in the definition of any constraint that it must be satisfied by the time you end the transaction.
Therefore most you can defer a constraint is until commit:
http://www.postgresql.org/docs/9.3/static/sql-set-constraints.html
I assume you will need the deferral to be longer than the length of one transaction.
So ultimately, these types of custom business rules end up being enforced by application code that you have to develop.
If including a contact on the project is mandatory, then your GUI should not send an add request unless the contact data (or key if already exists) is part of the transaction.
This way, you don't need the FK to allow nulls.
However, from business standpoint, what would you do when a contact is no longer a contact for the project and no substitute contact has been assigned?
In this case, your business should make the decision. If so, the FK has to allow nulls on update.
To combine both cases, your FK should allow nulls but your business layer should not accept create project transaction with null contact fk.
You also need to think about this business question: Could a contact exist without a project? The answer is important in your GUI design.
As per your statement "I need users to be able to manually enter contact data while in the middle of adding project data" - This makes sense to me only if the contacts would be directly added to the current project, but what if the user starts creating a project, create a contact then abandons the process of creating the project? How would you identify the added contact? So, may be you want to refine this requirement.

PostgreSQL - Storing multiple versions of a service description

I am maintaining a web application which allows a user to upload web service descriptions. The service table to store those descriptions looks roughly like this:
CREATE TABLE service(
id integer primary key,
name varchar(255)
targetNamespace varchar(255),
);
Now we want to enable the user to upload multiple versions of his web service. The question is how to reflect this in the database.
Here's my idea so far:
have a service table but only store the service id
CREATE TABLE service(
id integer primary key,
);
have a service_version table which stores version specific information and references the service table using a FK:
CREATE TABLE service_version(
id integer primary key,
service_id integer references service(id),
name varchar(255),
target_namespace varchar(255)
);
This should enable me to query for all versions associated with service. Is this a sane approach? Are there better solutions?
I'd suggest that you need attributes in the SERVICE table other than an ID, in order to be able to uniquely identify an individual web service in an effective manner. For example, would the name not stay the same, and hence be an attribute of the SERVICE rather than the SERVICE_HISTORY?
Only the elements that might change between versions should be in the versions table, you see.
To expand a bit on the correct answer by David Aldridge…
Your problem description is not perfectly clear. Are saying each web service is identified by a name, and over time each web service will have new versions developed where each version gets a new ID number and a possibly different namespace?
If so, this is precisely the same scenario as a book being published where the name remains the same while new editions may be published where each edition gets a new number and a possibly different subtitle.
This scenario would be a simple parent-child relationship. Define one table for the web services (the book), and a related child table for the versions (editions).
Diagrams
You will probably want one business rule to be enforced by your app programming and/or the database server's contstraints: Every parent (web service) must have at least one child, never zero. That first child of each parent represents the initial version.

Create a new record with an assigned PK - Castle ActiveRecord

I have a table with a GUID primary key. In ActiveRecord it is setup with a PrimaryKeyType.GuidComb. Is it possible to create this record with a manually assigned PK? If I set the primary key in the record and run Create() a new ID is assigned. If I run Save() I get an error (as one would expect).
The why:
This table is in two databases. Records need to be copied between these two databases on occasion. I would like to retain the ID as the record moves across the DBs.
No. A primary key is either generated (e.g. GuidComb) or manually assigned, it can't be both. You could create two classes that inherited from a base class defining all properties except the primary key, then each of these two classes would define their primary key as assigned or generated. But I'd recommend using SQL here, as a single INSERT INTO ... SELECT will be more efficient than using NHibernate/ActiveRecord.
I ended up setting the PrimaryKeyType to Assigned. Then I handled it with an overrided Create function:
public override void Create() {
if (ID == default(Guid)) ID = GUIDGenerator.Generate();
base.Create();
}
It would have been better to put this in OnSave, but the primary key cannot be modified in the interceptor. This works for my application, however this code will only be called if the object is explicitly created. It will not work if the object is created by cascade.