How to update a foreign key column? - java

I have below tables:
create table TABLE1 ( id int(10) unsigned NOT NULL AUTO_INCREMENT, deptId int(11) NOT NULL, DeptName varchar(32) NOT NULL, PRIMARY KEY (id), KEY Dept (deptId, DeptName))
create table TABLE2 ( id int(10) unsigned NOT NULL AUTO_INCREMENT, empId int(11) NOT NULL, DeptName varchar(32) NOT NULL, PRIMARY KEY (id), KEY DeptName (DeptName), CONSTRAINT T2FK FOREIGN KEY (DeptName) REFERENCES TABLE1 (DeptName))
TABLE1 has a MUL key defined with both dept id and dept name.
TABLE2 has a Foreign key which references only Dept name from TABLE1
The DTO for TABLE2 gets created like below:
#org.hibernate.annotations.NotFound(action = org.hibernate.annotations.NotFoundAction.IGNORE)
#javax.persistence.ManyToOne(targetEntity = org.amru.persistence.dto.TABLE1DTOImpl.class, fetch=javax.persistence.FetchType.EAGER)
#javax.persistence.JoinColumn(name = "deptName")
public org.amru.persistence.dto.TABLE1DTO getTABLE1() {
return TABLE1;
}
When I try to insert a row in TABLE2, it fails with foreign key constraint violation exception.
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`amru`.`TABLE2`, CONSTRAINT `T2FK` FOREIGN KEY (`DeptName`) REFERENCES `TABLE1` (`DeptName`))
I also see a EntityExistsException when I debug
What is possibly wrong? Is it recommended to refer a part of MUL key as foreign key in another table?
I am using jpa, hibernate, jboss, ejb and mysql

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Cannot add or update a child row: a foreign key constraint fails
What is possibly wrong?
This is very clear that, DeptName is foreign key in TABLE2, which is referring from TABLE1. So, you are not allowed to change the value in parent table as the data is being referenced in other table.
If you are supposed to do this, then you need to alter your table to apply cascade changes to child table as well for your Foreign Key
FOREIGN KEY (DeptName) REFERENCES TABLE1 (DeptName) ON DELETE CASCADE ON UPDATE CASCADE

Related

How to CREATE tables with foreign keys POSTGRESQL

I want to CREATE 4 tables that has FOREIGN KEYS of each other.
table students :
CREATE TABLE students
(
PRIMARY KEY (student_id),
student_id SERIAL,
student_name VARCHAR(100),
student_age INT,
entry_year INT,
graduate_year INT,
faculty_name VARCHAR(100),
group_id INT,
FOREIGN KEY (group_id) REFERENCES groups(group_id)
);
table groups :
CREATE TABLE groups
(
PRIMARY KEY (group_id),
group_id SERIAL,
group_name VARCHAR(100),
student_id INT,
FOREIGN KEY (student_id) REFERENCES students(student_id)
);
table lessons :
CREATE TABLE lessons
(
PRIMARY KEY (lesson_id),
lesson_id SERIAL,
lesson_name VARCHAR(100),
class_number INT,
date TIMESTAMP,
teacher_id INT,
group_id INT,
FOREIGN KEY(teacher_id) REFERENCES teachers(teacher_id),
FOREIGN KEY (group_id) REFERENCES groups(group_id)
);
table teachers :
CREATE TABLE teachers
(
PRIMARY KEY (teacher_id),
teacher_id INT,
teacher_name VARCHAR(100),
position VARCHAR(100)
);
And when I run this query in Java application, I gain an error with creation table students :
nested exception is org.postgresql.util.PSQLException: ERROR: relation "groups" does not exist
I know why It exception throwed.
Because I am creating table students with foreign key from table groups which has not yet been created.
But I have no idea how to fix It. Thanks in advance for response!
CREATE TABLE students
(
PRIMARY KEY (student_id),
student_id SERIAL,
student_name VARCHAR(100),
student_age INT,
entry_year INT,
graduate_year INT,
faculty_name VARCHAR(100),
group_id INT,
CONSTRAINT fk_group
FOREIGN KEY(group_id)
REFERENCES groups(group_id)
);
https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-foreign-key/

Interdependent tables

I am working on a project with Java, Spring Boot, JPA and H2 database.
However, I am confused with how the database tables have been designed.
There are 3 tables A,B and C.
Table A has Table B's primary key as foreign key.
Table B has Table C's primary key as foreign key.
Table C has Table A's primary key as foreign key.
Since each table is dependent on other tables, when I am creating the schema of all the three I am getting an error indicating Table B is not found
I have even tried using ALTER commands but still facing the same issue.
Here is my code
DROP TABLE IF EXISTS TEAMS;
CREATE TABLE IF NOT EXISTS TEAMS (
`team_id` int (11) NOT NULL AUTO_INCREMENT,
`name` varchar (100) NOT NULL DEFAULT '0',
`train_id` int (11) NOT NULL DEFAULT '0',
PRIMARY KEY (`team_id`),
CONSTRAINT `FK_teams_trains` FOREIGN KEY (`train_id`) REFERENCES TRAINS (`train_id`)
);
DROP TABLE IF EXISTS USERS;
CREATE TABLE IF NOT EXISTS USERS (
`user_id` int (11) NOT NULL AUTO_INCREMENT,
`team_id` int (11) DEFAULT NULL,
`reports_to` int (11) DEFAULT NULL,
PRIMARY KEY (`user_id`),
CONSTRAINT `FK_users_teams` FOREIGN KEY (`team_id`) REFERENCES TEAMS (`team_id`),
CONSTRAINT `FK_users_users` FOREIGN KEY (`reports_to`) REFERENCES USERS (`user_id`)
);
DROP TABLE IF EXISTS TRAINS;
CREATE TABLE IF NOT EXISTS TRAINS` (
train_id INT (11) NOT NULL AUTO_INCREMENT,
train_name varchar (100) NOT NULL DEFAULT '0',
team_coach INT (11) NOT NULL DEFAULT '0',
train_vp INT (11) NOT NULL DEFAULT '0',
PRIMARY KEY (`train_id`)
);
ALTER TABLE TRAINS ADD CONSTRAINT `FK_trains_users` FOREIGN KEY (`team_coach`) REFERENCES USERS (`user_id`);
ALTER TABLE TRAINS ADD CONSTRAINT `FK_trains_users_2` FOREIGN KEY (`train_vp`) REFERENCES USERS (`user_id`);
ALTER TABLE TEAMS ADD CONSTRAINT `FK_teams_trains` FOREIGN KEY (`train_id`) REFERENCES TRAINS (`train_id`);
ALTER TABLE USERS ADD CONSTRAINT `FK_users_teams` FOREIGN KEY (`team_id`) REFERENCES TEAMS (`team_id`);
ALTER TABLE USERS ADD CONSTRAINT `FK_users_users` FOREIGN KEY (`reports_to`) REFERENCES USERS (`user_id`);
How can I solve this issue?

Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'employee_ibfk_1' in the referenced table 'Address'

Created two tables namely Address and Employee.With relationship employee has a n address. The DB script as below.
create table address(addressid int,city varchar(10),pincode varchar(10));
insert into address(addressid,city,pincode) values(201,'Hosur',635109);
create table employee(empid int , firstname varchar(20),lastname varchar(20),department varchar(10),emailAddress varchar(50),baseLocation varchar(20),address int,FOREIGN KEY (Address) REFERENCES Address(addressId));
But I get the following error while trying to create the employee table:
Error Code: 1822. Failed to add the foreign key constraint. Missing
index for constraint 'employee_ibfk_1' in the referenced table
'Address' 0.117 sec
You should probably add a primary key on addressid in the Address table, this will create the index needed. In your current script there is no guarantee that addressid will be unique, hence if there would be duplicates a foreign key could never determine which row to refer to.
create table address(addressId int primary key not null, city varchar(10), pincode varchar(10));
because foreign key references primary key.
you don't have primary key in table address.
like this,
create table address(addressid int primary key,city varchar(10),pincode varchar(10));
create table employee(empid int , firstname varchar(20),lastname varchar(20),department varchar(10),emailAddress varchar(50),baseLocation varchar(20),address int ,FOREIGN KEY (address) REFERENCES address(addressid));
insert into address(addressid,city,pincode) values(201,'Hosur',635109);
You need to add the primary key constraint in the address table, inorder to add foreign key references in employee table
try with the following code:
create table address(addressid int primary key not null,city varchar(10),pincode varchar(10));
insert into address(addressid,city,pincode) values(201,'Hosur',635109);
create table employee(empid int , firstname varchar(20),lastname varchar(20),department varchar(10),emailAddress varchar(50),baseLocation varchar(20),address int,FOREIGN KEY (address) REFERENCES address(addressid));

Hibernate created an automatic breaking constraint

So I have 3 classes, Category, Question and Comment.
Both classes have a OneToMany relationship to Comment.
For some reason Hibernate has decided to put in a constraint on Comment resulting in the following exception:
ERROR: insert or update on table "comment" violates foreign key constraint "fknapu44p12w4v7wreaog7vgc80"
Detail: Key (q_comment)=(03f7ed17-4fa1-48d9-ac17-9842e233fde4) is not present in table "category".
Both Question and Category have to following bit of code:
#OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
#JoinColumn(name = "t_comment")
#LazyCollection(LazyCollectionOption.FALSE)
private List<Comment> comment;
And it seems as if I can correctly save the Category object with a new Comment in the list, but it breaks when I do the same to Question
So does anyone have any idea of what might cause this?
To clarify: the tables where created by hibernate which generated the following sql:
create table category (id varchar(255) not null, color varchar(7), name varchar(255), parent_questionnaire varchar(255), primary key (id))
create table comment (id varchar(255) not null, comment varchar(2048), timestamp int8, sent_by varchar(255), session varchar(255), t_recommendation varchar(255), t_comment varchar(255), primary key (id))
create table question (id varchar(255) not null, question varchar(255), type int4, parent_category varchar(255), primary key (id))
alter table if exists comment add constraint FKnapu44p12w4v7wreaog7vgc80 foreign key (t_comment) references category

.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails during signup and registration

I am following up a tutorial from this
url http://hellokoding.com/registration-and-login-example-with-spring-xml-configuration-maven-jsp-and-mysql/
I have three entities in my database namely user, role and role_user.
role_user has a foreign key to user and role tables respectively as shown in the picture below
Everything works fine but immediately I try to create a new user I have an error Cannot add or update a child row: a foreign key constraint fails
This is the full stacktrace
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`accounts`.`user_role`, CONSTRAINT `user_role_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `role` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.lang.reflect.Constructor.newInstance(Constructor.java:422)
com.mysql.jdbc.Util.handleNewInstance(Util.java:400)
com.mysql.jdbc.Util.getInstance(Util.java:383)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:973)
Please what could be wrong?
Have you made sure that the user_id & role_id are defined as primary keys and enable auto increment. As corrected below:
CREATE TABLE `user_role` (
`user_id` int(11) NOT NULL,
`role_id` int(11) NOT NULL,
PRIMARY KEY (`user_id`,`role_id`),
KEY `fk_user_role_roleid_idx` (`role_id`),
CONSTRAINT `fk_user_role_roleid` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_user_role_userid` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Above is the user_role table. If you try to insert another user_id 6 with role_id 1, it will fail with the below:

Categories

Resources