Spring boot cannot create session - sql-server

I am getting the following exception when creating the session.
INSERT INTO SPRING_SESSION
(
SESSION_ID,
CREATION_TIME,
LAST_ACCESS_TIME,
MAX_INACTIVE_INTERVAL,
PRINCIPAL_NAME
)
VALUES (?, ?, ?, ?, ?)];
Cannot insert the value NULL into column 'PRIMARY_ID'
Following are my schema details :
CREATE TABLE SPRING_SESSION (
PRIMARY_ID CHAR(36) NOT NULL,
SESSION_ID CHAR(36) NOT NULL,
CREATION_TIME BIGINT NOT NULL,
LAST_ACCESS_TIME BIGINT NOT NULL,
MAX_INACTIVE_INTERVAL INT NOT NULL,
EXPIRY_TIME BIGINT NOT NULL,
PRINCIPAL_NAME VARCHAR(100),
CONSTRAINT SPRING_SESSION_PK PRIMARY KEY (PRIMARY_ID)
);
CREATE UNIQUE INDEX SPRING_SESSION_IX1 ON SPRING_SESSION (SESSION_ID);
CREATE INDEX SPRING_SESSION_IX2 ON SPRING_SESSION (EXPIRY_TIME);
CREATE INDEX SPRING_SESSION_IX3 ON SPRING_SESSION (PRINCIPAL_NAME);
CREATE TABLE SPRING_SESSION_ATTRIBUTES (
SESSION_PRIMARY_ID CHAR(36) NOT NULL,
ATTRIBUTE_NAME VARCHAR(200) NOT NULL,
ATTRIBUTE_BYTES IMAGE NOT NULL,
CONSTRAINT SPRING_SESSION_ATTRIBUTES_PK PRIMARY KEY
(SESSION_PRIMARY_ID, ATTRIBUTE_NAME),
CONSTRAINT SPRING_SESSION_ATTRIBUTES_FK FOREIGN KEY
(SESSION_PRIMARY_ID) REFERENCES SPRING_SESSION(PRIMARY_ID) ON DELETE CASCADE
);
CREATE INDEX SPRING_SESSION_ATTRIBUTES_IX1
ON SPRING_SESSION_ATTRIBUTES (SESSION_PRIMARY_ID);

The solution to this problem is simple , Inside of spring-session jar file , there is org/springframework/session/jdbc folder , you can view this in eclipse.
Under this folder you can get schema-sqlserver.sql file , you need to execute this file only for proper schema of spring session.

You are setting the Column PRIMARY_ID as Primary key
CONSTRAINT SPRING_SESSION_PK PRIMARY KEY (PRIMARY_ID)
and since it is not a computed column or Auto Incremented one, you must specify a value for this column on each insert.
But wish not to populate the column for all Rows, then Change the design and Remove the PRIMARY KEY from that Column.
Then Probably you may add a New Column with IDENTITY so that it will be automatically assigned.
You can drop the Constraint Using this
ALTER TABLE SPRING_SESSION
DROP CONSTRAINT SPRING_SESSION_PK
Then add New Primary Key
ALTER TABLE SPRING_SESSION
ADD SeqNo INT IDENTITY(1,1) CONSTRAINT SPRING_SESSION_PK PRIMARY KEY

Related

Update/Delete violate foreign key on either side

I have two tables, below are the strutures
CREATE TABLE IF NOT EXISTS nl_address (
id int NOT NULL GENERATED BY DEFAULT AS IDENTITY,
address_text varchar(100),
pincode varchar(6),
city_id int NOT NULL,
state_id int NOT NULL,
country_id int NOT null,
is_active boolean default true,
PRIMARY KEY (id),
CONSTRAINT fk_city_id FOREIGN KEY(city_id) REFERENCES nl_city(id),
CONSTRAINT fk_state_id FOREIGN KEY(state_id) REFERENCES nl_state(id),
CONSTRAINT fk_country_id FOREIGN KEY(country_id) REFERENCES nl_country(id)
);
CREATE TABLE IF NOT EXISTS nl_customer (
cust_id int NOT NULL,
prefix varchar(10) default 'CUST-',
suffix varchar(2),
org_name varchar(100) NOT NULL,
domain_name varchar(100) NOT NULL,
pan_number varchar(10) NOT null,
pri_contact varchar(10) NOT NULL,
pri_number varchar(10) NOT NULL,
pri_email varchar(30) NOT NULL,
sec_contact varchar(10),
sec_number varchar(10),
sec_email varchar(30),
is_active boolean default true,
addr_id int not null,
created_date date,
created_by varchar(10),
updated_date date,
updated_by varchar(10),
PRIMARY KEY (cust_id),
CONSTRAINT fk_address_id FOREIGN KEY(addr_id) REFERENCES nl_address(id)
);
The problem is, neither I am able to update or delete
If i am trying to update record in nl_address, I got an violation error that the field is used inside `nl_customer.
If i tried to update from nl_customer, then I got an violation error that the field is used inside nl_address
It was originated, when JPA trying to persist the data, I have inserted a dummy data with id 1, when JPA trying to insert another record then it throws
.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "nl_address_pkey"
Detail: Key (id)=(1) already exists.
It seems there is something wrong with the table structure, any help appreciated
Actually this is common that you cannot update or delete that belong to primary/foreign key if you generate duplicates, as all values should be unique (i.e. if you have already id=1 and update id=2 to id=1, you will get the error you mentioned) and because a foreign key construct is a specific relationship it should be clarified what will happen with this relationship.
In case of 'nl_address' you used 'GENERATED BY DEFAULT AS IDENTITY' which have the same purpose as SERIAL (i.e. auto increment), but it is more compliant with SQL standard. (I assume you are also aware of difference between GENERATED BY DEFAULT and GENERATED ALWAYS)
However, you can specify the sequence in order to ensure the proper auto increment functionality.
ALTER TABLE nl_address
ALTER COLUMN "id"
DROP IDENTITY IF EXISTS;
ALTER TABLE nl_address
ALTER COLUMN "id"
ADD GENERATED BY DEFAULT AS IDENTITY (START WITH 1 INCREMENT 1);
If you use UPDATE or DELETE on FOREIGN KEY construct ensure what should happen with relationship:
[CONSTRAINT fk_name]
FOREIGN KEY(fk_columns)
REFERENCES parent_table(parent_key_columns)
[ON DELETE delete_action]
[ON UPDATE update_action]
/* as delete_action or update_action you can use e.g. SET NULL, RESTRICT or CASCADE;
so ensure what happen with records in related table*/

Can I auto-increment the Foreign Key column in my db table so that it matches the main table's auto-incrementing Primary Key column in SQL Server?

Create statement for my first table: 'users':
CREATE TABLE users
(
uid INT NOT NULL IDENTITY PRIMARY KEY,
firstName VARCHAR(50) NOT NULL,
lastName VARCHAR(50) NOT NULL,
middle VARCHAR(50) NOT NULL,
ssn VARCHAR(12) NOT NULL,
dob DATE NOT NULL,
phone VARCHAR(10) NOT NULL,
email VARCHAR(255) NOT NULL
)
Create statement for my second table: 'ds':
CREATE TABLE ds
(
dsu VARCHAR(50) NOT NULL,
dsp VARCHAR(50) NOT NULL,
dsImage VARCHAR(50) NOT NULL,
dsid INT NOT NULL,
Name nvarchar(50),
CONSTRAINT PK_dsid
PRIMARY KEY NONCLUSTERED (dsid),
CONSTRAINT FK_users_uid
FOREIGN KEY (dsid) REFERENCES users (uid)
ON DELETE CASCADE
ON UPDATE CASCADE
);
The first table's uid column will auto-increment with each new row I insert. I want to setup the ds table's dsid column value in each new row to automatically update to match the users table uid column value.
When I try to INSERT INTO values into the ds table:
INSERT INTO ds (dsu, dsp, dsImage)
VALUES ('john.smith', '1234567', 'Tiger')
I get the following error:
Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'dsid', table 'company.dbo.ds'; column does not allow nulls. INSERT fails.
So, I'm trying to figure out if I'm setting up the primary key and foreign key create statements correctly to achieve the desired result, and also why I'm getting the error, and if I'm even approaching this task/problem correctly.
Any help is greatly appreciated, thank you!

SQL Server : foreign key references invalid table

I'm not sure what I'm doing wrong, but I'm getting a foreign key references invalid table message telling me that dbo.ValueStream is an invalid table.
Edit: I originally posted my code in the incorrect order. Fixed in the edit to reflect the order it was done in SSMS
CREATE TABLE dbo.ValueStream
(
ValueStreamKey int IDENTITY(1,1) NOT NULL
CONSTRAINT PK_ValueStream_ValueStreamKey PRIMARY KEY,
ValueStream nvarchar(20),
)
CREATE TABLE dbo.NonConformance
(
NonConformanceKey int IDENTITY(1,1) NOT NULL
CONSTRAINT PK_NonConformance_NonConformanceKey PRIMARY KEY,
CustomerVendorKey int NOT NULL
CONSTRAINT FK_NonConformance_CustomerVendorKey_CustomerVendor_CustomerVendorKey
FOREIGN KEY REFERENCES dbo.CustomerVendor(CustomerVendorKey),
ValueStreamKey int NOT NULL
CONSTRAINT FK_NonConformance_ValueStream_Key_ValueStream_ValueStreamKey
FOREIGN KEY REFERENCES dbo.ValueStream(ValueStreamKey),
RepairOrder nvarchar(50) NOT NULL,
WorkOrder nvarchar(8) NOT NULL,
PartNumber nvarchar(50) NOT NULL,
SerialNumber nvarchar(50) NOT NULL,
PartDescription nvarchar(50) NOT NULL,
InductionDate datetime NOT NULL,
TriageStartDate datetime NOT NULL,
TriageCompletionDate datetime NOT NULL,
RequiresRRCA Bit NOT NULL,
NonConformanceSummary nvarchar(max) NOT NULL
);
taking out the CONSTRAINT FK_NonConformance_CustomerVendorKey_CustomerVendor_CustomerVendorKey
FOREIGN KEY REFERENCES dbo.CustomerVendor(CustomerVendorKey)
(we don't have that one)
and running the scripts seperately - first the first table and then the creation of the referencing table - this works for me.
No code errors.
You are creating dbo.NonConformance first in the script that you have posted. You need to move the CREATE TABLE dbo.ValueStream statement so that it is created first, ensuring there is a GO statement still between the two CREATE TABLE statements.
As it stands you are trying to create a foreign key to a table that does not exist.

SQL Relation MORE on MORE

I have a question about this relation betweed SpelerTeam and Toernooi, i get a error, can someone help me with it all the other relations do work:
Msg 1776, Level 16, State 0, Line 2 There are no primary or candidate
keys in the referenced table 'SpelerTeam' that match the referencing
column list in the foreign key 'FK__Toernooi__team__1A14E395'. Msg
1750, Level 16, State 0, Line 2 Could not create constraint. See
previous errors.
CREATE TABLE dbo.LoginGegevens
(
Username varchar(25) NOT NULL,
Wachtwoord varchar(25) NOT NULL,
LoginDatum date NOT NULL,
)
CREATE TABLE dbo.NawGegevensKind
(
KindSpeler varchar(25) NOT NULL,
NawKind varchar(50) NOT NULL,
)
CREATE TABLE dbo.NawGegevensProfspeler
(
Profspeler varchar(25) NOT NULL,
NawProfspeler varchar(50) NOT NULL,
)
CREATE TABLE dbo.SpelerTeam
(
Team int NOT NULL,
Kindspeler varchar(25) NOT NULL,
Profspeler varchar(25) NOT NULL,
)
CREATE TABLE dbo.Toernooi
(
team int NOT NULL,
score int NOT NULL,
games int NOT NULL,
rondes int NOT NULL,
)
-- primary keys
ALTER TABLE LoginGegevens
ADD primary KEY (Username)
ALTER TABLE NawGegevensKind
ADD primary KEY (KindSpeler)
ALTER TABLE NawGegevensProfspeler
ADD primary KEY (ProfSpeler)
ALTER TABLE SpelerTeam
ADD primary KEY (Team,KindSpeler,ProfSpeler)
ALTER TABLE Toernooi
ADD primary KEY (Team,Rondes,Games)
-- relation
ALTER TABLE SpelerTeam
ADD FOREIGN KEY (Kindspeler)
REFERENCES NawGegevensKind(Kindspeler);
ALTER TABLE SpelerTeam
ADD FOREIGN KEY (Profspeler)
REFERENCES NawGegevensProfspeler(Profspeler);
ALTER TABLE Toernooi
ADD FOREIGN KEY (Team)
REFERENCES SpelerTeam(Team);
The Primary Key of SpelerTeam is Team,KindSpeler,ProfSpeler.
That means that any foreign key that references that table has to reference all three of those columns. You can't create a foreign key that uses only team.
You need an index on a colum so that it can be referenced as a foreign key efficiently. Add an index on SpelerTeam.Team and on all other columns with the same problem. Try CREATE INDEX IX_SpelerTeam_Team_Team ON SpelerTeam (Team);
Add below after all tables have been created:
CREATE UNIQUE NONCLUSTERED INDEX IX_SpelerTeam_Team
ON dbo.SpelerTeam (Team);
GO
As it was pointed in another answer you cannot reference to non unique column, to make column unique you can make this column primary key or create index for this column.
It is not enough that your "Team" column is part of composite key.

SQL Server Foreign Key references invalid Table 'employees'

I try to run this SQL Server query:
USE DB_UBB;
CREATE TABLE dept_emp (
emp_no INT NOT NULL,
dept_no CHAR(4) NOT NULL,
from_date DATE NOT NULL,
to_date DATE NOT NULL,
FOREIGN KEY (emp_no) REFERENCES employees(emp_no) ON DELETE CASCADE, -- Error here
FOREIGN KEY (dept_no) REFERENCES departments(dept_no) ON DELETE CASCADE, -- And here
PRIMARY KEY (emp_no, dept_no)
);
CREATE INDEX (emp_no);
CREATE INDEX (dept_no);
and I get these errors:
Foreign key 'FK__dept_emp__8bc6840bee39d6cef4bd' references invalid table 'employees'.
Foreign key 'fk__dept_emp__99bc0b2304d3f32059a9' references invalid table 'departments'.
even though I have these tables:
What do I do wrong?
EDIT:
Added Whole DB:
SQL ‘hides’ the columns from the Key of the Clustered Index in Nonclustered Indexes.
You have created a composite primary on both emp_no,dept_no
cluster index of primary will hide both columns from indexes in following queries and will generate error
CREATE INDEX (emp_no);
CREATE INDEX (dept_no);
If you are specifying the foreign key after the column specifications, try using the CONSTRAINT clause instead:
to_date DATE NOT NULL,
CONSTRAINT fk_dept_emp_dept FOREIGN KEY (emp_no) REFERENCES employees(emp_no) ON DELETE CASCADE,
CONSTRAINT fk_dept_emp_emp FOREIGN KEY (dept_no) REFERENCES departments(dept_no) ON DELETE CASCADE,
Aparently, I even though the tables were created, it didn't recognize them.
I added an <if not exist, create tables>
I also removed the CREATE INDEX (emp_no); and CREATE INDEX (dept_no); as #Muhammad Nasir said, but it didn't fix the referencing issue.
Solution:
USE DB_UBB;
IF NOT EXISTS (SELECT * FROM SYSOBJECTS WHERE name='employees' and xtype='U')
CREATE TABLE employees (
emp_no INT NOT NULL,
birth_date DATE NOT NULL,
first_name VARCHAR(14) NOT NULL,
last_name VARCHAR(16) NOT NULL,
gender VARCHAR(1) NOT NULL CHECK (gender IN('M', 'F')),
hire_date DATE NOT NULL,
PRIMARY KEY (emp_no)
);
GO
IF NOT EXISTS (SELECT * FROM SYSOBJECTS WHERE name='departments' and xtype='U')
CREATE TABLE departments (
dept_no CHAR(4) NOT NULL,
dept_name VARCHAR(40) NOT NULL,
PRIMARY KEY (dept_no),
UNIQUE (dept_name)
);
GO
IF NOT EXISTS (SELECT * FROM SYSOBJECTS WHERE name='dept_emp' and xtype='U')
CREATE TABLE dept_emp (
emp_no INT NOT NULL,
dept_no CHAR(4) NOT NULL,
from_date DATE NOT NULL,
to_date DATE NOT NULL,
FOREIGN KEY (emp_no) REFERENCES employees(emp_no) ON DELETE CASCADE,
FOREIGN KEY (dept_no) REFERENCES departments(dept_no) ON DELETE CASCADE,
PRIMARY KEY (emp_no, dept_no)
);
GO

Resources