How to retrieve object from database to put as foreign key - jpa

In my database, I have table "User" and "Role" and I search to put a role in a user when the user sign up. The problem is that when I retrieve the role from database and post the user, a new role is create and I don't want it. I want the a existing role are put as foreign key.

In JPA you don't think as foreign keys. What you model is an Object which can have relations to other objects, such as a class User may have a list of Role references.
You'd then annotate it with the according JPA annotations to map this relation to your database tables. You may check the Oracle Java EE tutorial on JPA to learn how to do that.
Then, when putting a new Object (meaning one with a new ID) into the list, it will result in getting a new entry in the referring table when persisting it.

Related

Entity Framework: auto-generate primary keys after initializing tables

I'm using Entity Framework (6) in a code-first arrangement to create a database and pre-populate it from a set of CSV files. Because the tables are coming from another application, they already have primary keys, and relationships embedded in the data make reference to those keys.
For that reason I've been using [DatabaseGenerated(DatabaseGeneratedOption.None)] when defining these tables, so that the PKs already in place get used.
However, after the data have been imported, I want to be able to add new records to the tables. How do I get the DB to assign new sequential PKs for the new records?

JPA Multiple relationships on one field in an entity

I am a beginner to using JPA 2.0 and databases in general and I was just confused about a few concepts.
So I have a total of 3 tables. One is the UserTable, which contains all the information about my user. It has a primary key field called user_Id. My other two tables are ExercisesTable and FoodIntakeTable, and they each have a foreign key field called user_Id to reference the user_Id in my UserTable. I want a one-to-many relationship from my user_Id table to each of the two tables so I can find pull out exercise information or food information for a user.
Pretty much like this:
FoodIntakeTable <-> UserTable <-> ExercisesTable
I need a bidirectional mapping from UserTable to FoodIntakeTable and also a bidirectional mapping from UserTable to ExercisesTable from the field user_Id.
The problem is, when I try to write my code like this in my Usertable class:
#OneToMany(mappedBy="ExercisesTable.userId")
#OneToMany(mappedBy="FoodIntakeTable.userId")
public long userId;
It's illegal because I can't have two #OneToMany annotations on the same field. I think it's supposed to be legal in a normal relational database and I'm just confused about how you translate this into JPA. I'm very new to the whole concept of databases and entities in general, so any help would be appreciated.
In JPA you can directly reference entity objects instead of the ids that they are mapped by. Try something like this:
You should have an entity type for each of your tables, say Exercise for ExercisesTable, FoodIntake for FoodIntakeTable, and User for your UserTable.
Then your User entity is the owning side of the relationships, having one field per relationship like this:
#OneToMany(mappedBy=...)
private List<Exercise> exercises;
#OneToMany(mappedBy=...)
private List<FoodIntake> foodIntakes;

How to clear many to many relationship without loading from database in EF?

I have the following entities (pocos using Entity Framework 5):
Company: Id, Name, Applications, etc.
Application: Id, Name, etc.
There's a many-to-many relationship between companies and applications.
Having a company (without the apllications relationship loaded from the database) and a collection of application ids, I would like to clear the applications from the company and add the applications with ids specified in the collection.
I can attach applications using their ids, without loading them from the database, like this:
foreach (int id in selectedApplications)
{
Application application = new Application() { Id = id };
_context.Applications.Attach(application);
company.Applications.Add(application);
}
_context.SaveChanges();
But I need to clear the applications relationship first. Is there any way to clear a many-to-many relationship without loading it from the database first?
This is only way. company.Applications must be loaded when you add or remove items from it, otherwise the change tracker will never be aware of any changes.
Also, the junction table is not an entity in the conceptual model, so there is no way to set primitive foreign key properties as is possible in foreign key associations. You have to access the associations by the object collections.

In Entity Framework, how do I specify a condition on an association?

I have a relational model with an associative table. But in addition to the related keys, this table also has a flag. I would like to define two associations: one where the flag is true and another where it is false. The EF designer can add a condition to an entity, but not to an association.
The associative table looks like this:
UserPrivilege
-------------
UserId int (FK1)
PrivilegeId int (FK2)
IsGranted bit
I would like to create two associations between the User entity and the Privilege entity: PrivilegesGranted and PrivilegesDenied.
You can't do this directly through the designer.
But this is possible in the XML using DefiningQuery and Create and Delete sprocs. See this old post on my blog for more: Associations with Payloads.
The only thing that is a bit interesting is I assume the PK is just UserId and PrivilegeId, which means a user can't be granted and denied for a particular privilege at the same time.
So if you write code like this:
Privilege p = user.Granted.First();
user.Granted.Remove(p);
user.Denied.Add(p);
ctx.SaveChanges();
Update ordering is important. because you are using a DefiningQuery for both associations, the EF doesn't know they are related, and that it needs to do the delete before it can do the update.
So you might end up with PK violations.
A way to address this issue is in the Insert and Delete sprocs for each association, you can essentially make them change the current row for the User and Privilege pair, if it exists update it with the correct IsGranted value, if not create it, i.e. make it an upsert.
Let me know how you go here
Alex

Adding a property to an Entity Framework Entity from another table

I'm just starting out with the Entity Framework and ADO.NET Data Services and I've run into an issue that I can't seem to figure out. I have two tables, one that has user information and the other that has a created by field. Within the database, there isn't a foreign key between these tables. The user table contains an arbitrary Id, a username, and a display name. The created by field contains the user's username. In my entity I would like to have the user's display name since this is what I need to display and expose over the ADO.NET Data Service? I'm aware that I could restructure the database, but I was hoping that I could do the join using the username as I would in a SQL statement.
Thanks in advance,
-Damien
You can make a view using a join of both tables, and then use this object to display the user's name.
There's some info on mapping custom queries here.