Create entity and return ID - jpa

Using Open JPA 2.0, and database is DB2 9.7. I would like to like to create an entity which includes ID which is Primary Key, and auto generated Identity column and after creating the entity I need to display the ID generated. For this after persisting the entity, I am calling entity.getId().
In the database, I see below query getting executed
select ID from final table
(INSERT INTO WEB.USER (NAME, LOCATION) VALUES (?, ?))
Is there any alternate / better way to create an entity and return the generated ID? I would like to avoid "Select ID from final table", as this is expected to have performance impact.

This is how you retrieve auto generated ID from DB2 and there is nothing you can do about it. Other databases often require extra SQL query, so it's actually even better with DB2, which returns ID immedaitely. I don't think there is a faster way to so this.
Check out OPENJPA-736 where this optimization was implemented.

I am using Database sequence (#SequenceGenerator) to avoid "select ID from final table". This worked fine and #TableGenerator would also have sorted this issue.

Related

If a Postgres DB has unique IDs across its tables, how do you find a row using its ID without knowing its table?

Following the blog of Rob Conery I have set of unique IDs across the tables of my Postgres DB.
Now, using these unique IDs, is there a way to query a row on the DB without knowing what table it is in? Or can those tables be indexed such that if the row is not available on the current table, I just increase the index and I can query to the next table?
In short - if you did not prepared for that - then no. You can prepare for that by generating your own uuid. Please look here. For instance PG has uuid that preserve order. Also uuid v5 has something like namespaces. So you can build hierarchy. However that is done by hashing namespace, and I don't know tool to do opposite inside PG.
If you know all possible tables in advance you could prepare a query that simply UNIONs a search with a tagged type over all tables. In case of two tables named comments and news you could do something like:
PREPARE type_of_id(uuid) AS
SELECT id, 'comments' AS type
FROM comments
WHERE id = $1
UNION
SELECT id, 'news' AS type
FROM news
WHERE id = $1;
EXECUTE type_of_id('8ecf6bb1-02d1-4c04-8875-f1da62b7f720');
Automatically generating this could probably be done by querying pg_catalog.pg_tables and generating the relevant query on the fly.

mvc Entity Framwork, insert using select max() from table

I am developing an App using MV5 and Entity Frameowrk to connect to SQL Server Database
I need to do an Insert where the is getting ID like this.
Select max(id)+1 from table where field_id = #ID.
The idea is to do it in one transaction.
Is that Posible to do it in Entity Framework or I should use a Store Procedure?
EF compiles the C# expressions you provide it into SQL, and then executes the resulting SQL. So you can write such a query in LINQ, which will in-fact be computed during a single "call" to the database:
long id = MyDbContext.MyDbSet.Max(entity => entity.Id) + 1;
Do note, that if you are doing this so that you can assign a non existing ID to a new entry- there's no need. EF takes care of this for you, so long as the field is named Id and it is of type long. Just do not assign it any value.

Inserting into postgres database

I am working trying to write an insert query into a backup database. I writing place and entities tables into this database. The issue is entities is linked to place via place.id column. I added a column place.original_id in the place table to store it's original 'id'. so now that i entered place into the new database it's id column changed but i have the original id stored so I can still link entities table to it. I am trying to figure out how to write entities to get the new id
so far i am at this point:
insert into entities_backup (id, place_id)
select
nextval('public.entities_backup_id_seq'),
(select id from places where original_id = (select place_id from entities) as place_id
from
entities
I know I am missing something because this does not work. I need to grab the id column from places when entity.place_id = places.original_id. Any help would be great.
I think this is what you want
insert into entities_backup (id, place_id)
select nextval('public.entities_backup_id_seq'), places.id
from places, entities
where places.original_id = entities.place_id;
I am working trying to write an insert query into a backup database. I writing place and entities tables into this database. The issue is entities is linked to place via place.id column. I added a column place.original_id in the place table to store it's original 'id'. so now that i entered place into the new database it's id column changed but i have the original id stored so I can still link entities table to it.
It would be simpler to not have this problem in the first place.
Rather than trying to fix this up after the fact, the better solution is to dump and load places and entities complete with their primary and foreign keys intact. Oracle's EXPORT or a utility such as ora2pg should be able to do it.
Sorry I can't say more. I know Postgres, not Oracle.

EF 6 Migration: How to execute sql SELECT?

In our project we have necessity of adding some predefined data to DB. I think the best way and concept is using for that EF Migrations (not Seed method).
But we have a big troubles with adding related data to DB:
For Example:
Suppose we have 2 tables:
Users:
Id (PK auto increment)
Name
RoleId
Roles:
Id (PK auto increment)
Name
Let's suppose that we need to add User(Name = 'John', RoleId = (Id of role that name is 'Admin')).
How can we do it? It would be great if we find a solution that allows us to execute pure SQL SELECT script which not uses Entities of Code First because they can be modified or removed.
For DELETE, INSERT, UPDATE can be used Sql(...) method but what about SELECT?
You cannot have a context into the migration.
Logically first are ran the migrations to Update the DB Schema, then you can have a context to work with the data via it. If your DB does not match the model, or even the table is still not there, you cannot use it in EF.
I had to look into the EF code (and also because was curious). Practically the Sql() method in the DbMigration class in several levels below just adds the SQL string into a list of queries that should be executed into the transaction and moves on. It does not executes it when it is called. So in short EF just fills in a list of codes lines that should be executed in the end at once. And it seems correct if you try to walk in all paths of what you can do with the C# code in the migration code.
The question is quite good actually, unfortunately still I didn't found any better solution rather than using pure ADO.
Another option is to generate more custom SQL queries, and use T-SQL more widely.
For your case as you want to insert the user and set the groupId looking by the name, it can be used with inner select:
INSERT INTO Users (Name, GroupId)
VALUES ('John', RoleId = (SELECT Id FROM Roles WHERE Name = 'Admin')).
For my issue, I had to a bit do more sophisticated execution - the following does the same as the AddOrUpdate method of the DbSet, using the IF statement:
IF EXISTS (SELECT * FROM Table1 WHERE Column1='SomeValue')
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
ELSE
INSERT INTO Table1 VALUES (...)
I found it here: http://blogs.msdn.com/b/miah/archive/2008/02/17/sql-if-exists-update-else-insert.aspx
I'm using good old LINQ for this:
public override void Up()
{
using (var dc = new DbContext("your connection string or name"))
{
var ids = dc.Database.SqlQuery<int>("SELECT id FROM sometable WHERE somefield={0}", 42).ToArray();
...
}
}
Using LINQ is better, even for usual migrations, because, there is a bug in DbMigration.Sql method, it ignores arguments: How to pass parameters to DbMigration.Sql() Method

Unique IDs over database globally using Entity Framework

I want to have unique object ids over whole database. Is there any built-in feature in EF?
Or may be there are some practices/patterns?
thanks in advance.
If you are using SQL Server as the backend, you could look into using a UNIQUEIDENTIFIER column rather than an IDENTITY column, which means you can use GUIDs for your IDs across the entire database.
See "GUID Property Values" in the following MSDN article for EF4
http://msdn.microsoft.com/en-us/library/dd283139.aspx
1) Create table to store last id (int, bigint) (identifier domain)
2) Add stored procedure to retrieve the next id (int, bigint).
3) You may implement Custom Data Class EntityObject and ComplexObject (or maybe assign to every entity manualy in code)
4) Use this id in your custom class as primary key
--
If you using GUID...EF(4) has build-in feature to do this. But GUID as primary key with CLUSTERED INDEX is bad solution for the many insertion of course.