JPA Generated Values - jpa

I generated a web CRUD application following this page
But the wizard does not annotate primary key autoincrement field in the table(s) with #GeneratedValue.
And of course, when run the UI does not populate the autoincrement ID field with value.
So I tried looking at this page
I tried annotating the ID field(s) with #GeneratedValue but with no success.
Do I need to create table with autoincrement column first?

http://www.binarytides.com/create-autoincrement-columnfield-in-apache-derby/
CREATE TABLE students
(
id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
name VARCHAR(24) NOT NULL,
address VARCHAR(1024),
CONSTRAINT primary_key PRIMARY KEY (id)
) ;
this works...
then in UI remove the field for ID.

Related

postgresql, key is not present in table error, but key present in the table

I have tables providers, and provider_groups.
providers:
create table providers
(
id integer not null constraint providers_pkey primary key,
available boolean not null,
);
and provider_groups
create table provider_groups
(
id integer not null provider_groups_pkey primary key,
provider_id integer not null constraint fk_237d25c5d3e1ebb8
references providers on delete cascade,
type varchar(100) not null
);
create index idx_237d25c5d3e1ebb8
on provider_groups (provider_id);
and my application (which using of doctrine ORM) trying to update data for some provider and his related group. I'm sure both provider and group exists in database, but for some reason it's failing with error
SQLSTATE[23503]: Foreign key violation: 7 ERROR: insert or update on table "provider_groups" violates foreign key constraint "fk_237d25c5d3e1ebb8"\n
DETAIL: Key (provider_id)=(28007) is not present in table "providers".
but as I mentioned it's there, I can see it through database UI.
What I'm doing wrong??? Can it be related to some cache on DB side, as it's a pretty old logic running for a while and that error apears only now... Thanks in advice!

Entity Framework won't detect foreign key from database

I've got two tables - Appointment and User. Appointments can be linked to two different Users - a student and a member of staff. The Appointment table contains two foreign keys: StaffUsername and ExternalID. These reference columns in the User table named Username (the User table's PK) and ExternalID (a UNIQUE index). Here are the table definitions:
CREATE TABLE [dbo].[Appointment]
(
[ID] INT NOT NULL IDENTITY(1,1),
[AppointmentTypeID] INT NOT NULL,
[StartTime] DATETIME NOT NULL,
[EndTime] DATETIME NOT NULL,
[AppointmentSlotID] INT NULL,
[StaffUsername] NVARCHAR(200) NOT NULL,
[ExternalID] NVARCHAR(10) NULL,
[BookedBy] NVARCHAR(200) NOT NULL,
[BookedTimestamp] DATETIME NOT NULL,
[ReminderEmailSentTimestamp] DATETIME NULL,
[CancelledBy] NVARCHAR(200) NULL,
[CancelledTimestamp] DATETIME NULL,
[StudentDidNotAttend] BIT NULL,
[LastModifiedTimestamp] DATETIME NOT NULL,
[LastModifiedBy] NVARCHAR(200) NOT NULL,
CONSTRAINT [PK_Appointment] PRIMARY KEY CLUSTERED ([ID] ASC),
CONSTRAINT [FK_Appointment_AppointmentType] FOREIGN KEY ([AppointmentTypeID]) REFERENCES [dbo].[AppointmentType]([ID]),
CONSTRAINT [FK_Appointment_AppointmentSlot] FOREIGN KEY ([AppointmentSlotID]) REFERENCES [dbo].[AppointmentSlot]([ID]),
CONSTRAINT [FK_Appointment_User_StaffUsername] FOREIGN KEY ([StaffUsername]) REFERENCES [dbo].[User]([Username]),
CONSTRAINT [FK_Appointment_User_ExternalID] FOREIGN KEY ([ExternalID]) REFERENCES [dbo].[User]([ExternalID])
)
CREATE TABLE [dbo].[User]
(
[Username] NVARCHAR(200) NOT NULL,
[FirstName] NVARCHAR(200) NULL,
[LastName] NVARCHAR(200) NULL,
[EmailAddress] NVARCHAR(200) NULL,
[IsStaff] BIT NOT NULL DEFAULT 0,
[ExternalID] NVARCHAR(10) NOT NULL,
[LastLogin] DATETIME NULL,
CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED ([Username] ASC),
CONSTRAINT [UQ_ExternalID] UNIQUE ([ExternalID])
)
Unfortunately, when I use the Update model from database option in the EDMX model designer, it will not pick up the foreign key on the ExternalID columns. It remains looking like this (highlighted in green are the properties relating to the relationship which is modelled correctly, in yellow are the properties which should relate to a second relationship but are being ignored):
I know from experience that the EDMX designer can be quirky at times, especially when detecting changes to objects, so I've tried all the usual tricks. I've checked in Web.config that my connection string is pointing to the correct database. I've deleted the Appointment and User tables in the designer completely and run the Update command again. I've tried that with a save and restart of Visual Studio between deletion and update, too.
To check the relationship is correct in the database I've created a database diagram in SSMS which shows the troublesome relationship correctly:
I've also created a brand new project and added a new Entity Data Model pointing to the same database with the same credentials, just in case the issue was related to the fact that I'm updating an existing model, but no dice. Even in the new project, the relationship isn't detected.
I also tried to create the Navigation Property manually, but as you can see from this screenshot, the foreign key I'd need to select isn't available in the dropdown list:
I don't know if the issue somehow relates to the fact that the ExternalID column isn't the primary key of the User table, or maybe its NVARCHAR(10) data type. I've no idea, to be honest.
Any suggestions as to why this foreign key isn't being detected? And how I can fix it? My project targets .NET Framework 4.6 and I'm using EF6. Obviously I'm using Database First.
In EF6 an Entity only has one key, and so all Navigation Properties must use a Foreign Key that references the same key. EF Core supports Alternate Keys, and supports a Database-First workflow with Reverse Engineering.

Weak Entity postgresql

I want to create a table with primary key email,nro being nro a sequential number for each email ex:
user1#e.com, 1
user1#e.com, 2
user2#e.com, 1
create table proposta_de_correcao(
email varchar(255) not null,
nro serial not null,
unique(nro,email),
PRIMARY KEY(nro, email),
FOREIGN KEY (email) REFERENCES Utilizador(email),
);
But I get the following error:
ERROR: there is no unique constraint matching given keys for referenced table "proposta_de_correcao"
I have already tried:
unique(nro,email)
contraint keys unique(nro,email)
Two things here, to help with your problem:
Why nro is serial if is not a sequential field in your database? serial type is used when you want that the field be incremented automatically (as in single integer primary keys). Maybe is better that you put an int type here.
You have in your table no unique constraints. If you create a fiddle, you can see that code runs fine:
CREATE TABLE proposta_de_correcao(
email VARCHAR(255) not null,
nro SERIAL not null,
UNIQUE(nro, email),
PRIMARY KEY(nro, email)
-- FOREIGN KEY (email) REFERENCES Utilizador(email)
);
INSERT INTO proposta_de_correcao VALUES ('user1#e.com', 1);
INSERT INTO proposta_de_correcao VALUES ('user1#e.com', 2);
INSERT INTO proposta_de_correcao VALUES ('user2#e.com', 1);
So, I can conclude that when you want to add the constraint, your database already have duplicated data in those two columns. Try to create in a test database the data mentioned above and you will see that runs perfectly.
I just removed the foreign key constraint to allow to run the code as we don't have the referenced table in example and we can consider that the referenced table don't have influence on the problem cited on answer.
Here's the fiddle.

How do I create a check to make sure a value exists in another table?

Right now I have two tables, one that contains a compound primary key and another that that references one of the values of the primary key but is a one-to-many relationship between Product and Mapping. The following is an idea of the setup:
CREATE TABLE dev."Product"
(
"Id" serial NOT NULL,
"ShortCode" character(6),
CONSTRAINT "ProductPK" PRIMARY KEY ("Id")
)
CREATE TABLE dev."Mapping"
(
"LookupId" integer NOT NULL,
"ShortCode" character(6) NOT NULL,
CONSTRAINT "MappingPK" PRIMARY KEY ("LookupId", "ShortCode")
)
Since the ShortCode is displayed to the user as a six character string I don't want to have a another table to have a proper foreign key reference but trying to create one with the current design is not allowed by PostgreSQL. As such, how can I create a check so that the short code in the Mapping table is checked to make sure it exists?
Depending on the fine print of your requirements and your version of Postgres I would suggest a TRIGGER or a NOT VALID CHECK constraint.
We have just discussed the matter in depth in this related question on dba.SE:
Disable all constraints and table checks while restoring a dump
If I understand you correctly, you need a UNIQUE constraint on "Product"."ShortCode". Surely it should be declared NOT NULL, too.
CREATE TABLE dev."Product"
(
"Id" serial NOT NULL,
"ShortCode" character(6) NOT NULL UNIQUE,
CONSTRAINT "ProductPK" PRIMARY KEY ("Id")
);
CREATE TABLE dev."Mapping"
(
"LookupId" integer NOT NULL,
"ShortCode" character(6) NOT NULL REFERENCES dev."Product" ("ShortCode"),
CONSTRAINT "MappingPK" PRIMARY KEY ("LookupId", "ShortCode")
);
Your original "Product" table will allow this INSERT statement to succeed, but it shouldn't.
insert into dev."Product" ("ShortCode") values
(NULL), (NULL), ('ABC'), ('ABC'), ('ABC');
Data like that is just about useless.
select * from dev."Product"
id ShortCode
--
1
2
3 ABC
4 ABC
5 ABC

Unique Field - no unique constraint matching given keys

I have three tables in a postgresql database, namely tec_configurations, tep_cores and tep2tec_bindings. The table tec2tep_bindings references to the primary key fields of the first two tables. The related create statements per table are listed in below sql snippets 2,3 and 4. I get the error indicated in the 1st snippet below. Could you please tell me how I can fix this error? The 'id' field in table TEC_CONFIGURATIONS is already unique since it is a primary key. So, I don't see a reason to get this error message.
SNIPPET 1 (Error message):
ERROR: there is no unique constraint matching given keys for referenced table
"tec_configurations"
SNIPPET 2 (TABLE tec_configurations):
CREATE TABLE IF NOT EXISTS TEC_CONFIGURATIONS (
ID SERIAL PRIMARY KEY,
TEC_ID INT NOT NULL,
HANDLER_MAC TEXT NOT NULL,
PRIMARY_MAC TEXT,
SECONDARY_MAC TEXT,
TERTIARY_MAC TEXT,
EXPECTED_FLOWS INT DEFAULT 0,
VERSION INT DEFAULT 0,
UUID TEXT DEFAULT NULL );
SNIPPET 3 (TABLE tep_cores):
CREATE TABLE IF NOT EXISTS TEP_CORES (
ID SERIAL PRIMARY KEY,
MAC TEXT,
UUID TEXT,
CORE_NO INT DEFAULT 0);
SNIPPET 4 (TABLE tec2tep_bindings)
CREATE TABLE IF NOT EXISTS TEC2TEP_BINDINGS (
ID SERIAL PRIMARY KEY,
TEC_ID_FK INT NOT NULL REFERENCES TEC_CONFIGURATIONS(ID),
TEP_CORE_ID_FK INT NOT NULL REFERENCES TEP_CORES(ID),
REPLICA_RANK INT DEFAULT 0);
Wild guess, since you're issuing create table if not exists rather than create table: one of the tables exists without the needed unique key (e.g. from lack of a primary key).
(If correct, I'd add this note. Some Postgres core devs were hostile to the idea of adding if exists and if not exists constructs, objecting thus: "What is supposed to happen when you create table if not exists, silently "succeed", and the existing table has a schema different from the one you were hoping for?")