I am developing a sample project between users and products. A user can sell multiple products and a product can be sold by multiple users. So I designed my db with a many to many relationship. Below are my tables:
create table `users` (
`id` bigint(20) not null auto_increment,
`first_name` varchar(100) not null,
`last_name` varchar(100) not null,
`email` varchar(100) not null,
`password` varchar(255) not null,
`phone_number` varchar(20),
`created_at` timestamp default CURRENT_TIMESTAMP,
`updated_at` timestamp default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
primary key(`id`),
unique(`email`)
);
create table `products` (
`id` bigint(20) not null auto_increment,
`name` varchar(255) not null,
primary key(`id`),
unique(`name`)
);
create table `users_products` (
`user_id` bigint(20) not null,
`product_id` bigint(20) not null,
`quantity`int not null,
`price` DECIMAL(5, 2) not null,
`description` text not null,
`created_at` timestamp default current_timestamp,
`updated_at` timestamp default current_timestamp on update current_timestamp,
primary key (`user_id`, `product_id`),
foreign key(`user_id`) references `users`(`id`) on delete cascade,
foreign key(`product_id`) references `products`(`id`) on delete restrict
);
As you can see above, the products table name is unique because users can sell the same products.
Now I ask the question how this can be achieved using spring boot with JPA. I have seen tutorials with many to many with extra columns but the tutorials have just had an extra column with date time. But I want to perssit with the extra columns as mentioned above in the users_products table.
And also is the schema designed ok?
Related
java.sql.SQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (hrms.employees, CONSTRAINT FKe4i9i8vu1j96m71g4v98kqirb FOREIGN KEY (designation_id) REFERENCES designations (id))
I just land on this problem, I try to delete an entity, but the entity have a relation with another entity and another entity have another relation to imagine the picture this is the tables
How to detach employee and designation from department when I want to delete department. I can delete designations in the code, but I don't want to delete the employee with foreign key associated to the department and designation.
CREATE TABLE `departments` (
`id` bigint NOT NULL AUTO_INCREMENT,
`name` varchar(150) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
CREATE TABLE `designations` (
`id` bigint NOT NULL AUTO_INCREMENT,
`department_name` varchar(40) DEFAULT NULL,
`name` varchar(140) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
CREATE TABLE `employees` (
`id` bigint NOT NULL AUTO_INCREMENT,
`address` varchar(255) NOT NULL,
`dob` varchar(255) DEFAULT NULL,
`email` varchar(35) NOT NULL,
`employee_number` varchar(255) NOT NULL,
`first_name` varchar(40) NOT NULL,
`full_name` varchar(100) NOT NULL,
`gender` varchar(255) DEFAULT NULL,
`join_date` varchar(255) NOT NULL,
`last_name` varchar(40) NOT NULL,
`password` varchar(40) NOT NULL,
`phone_number` varchar(255) NOT NULL,
`username` varchar(255) NOT NULL,
`department_id` bigint DEFAULT NULL,
`designation_id` bigint DEFAULT NULL,
`avatar_image` varchar(64) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FKgy4qe3dnqrm3ktd76sxp7n4c2` (`department_id`),
KEY `FKe4i9i8vu1j96m71g4v98kqirb` (`designation_id`),
CONSTRAINT `FKe4i9i8vu1j96m71g4v98kqirb`
FOREIGN KEY (`designation_id`)
REFERENCES `designations` (`id`),
CONSTRAINT `FKgy4qe3dnqrm3ktd76sxp7n4c2`
FOREIGN KEY (`department_id`)
REFERENCES `departments` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
Spring is completely irrelevant to your question. Its all about the MySQL database and the way you have defined the tables in your DDL.
You cannot delete a Parent row if a Child row exists on your database because of how you defined that constraint.
There is a ON DELETE .... syntax which tells MySQL what to do when a parent row is deleted, by default MySQL will reject the delete, you can change this in a number of ways, as specified in the MySQL manual, of all the odd places.
In your case as you want to NOT DELETE the Employee when you delete the Department, and you have the column
`department_id` bigint DEFAULT NULL,
defined as DEFAULT NULL then change your CONSTRAINT as below
CONSTRAINT `FKgy4qe3dnqrm3ktd76sxp7n4c2`
FOREIGN KEY (`department_id`)
REFERENCES `departments` (`id`)
ON DELETE SET NULL
You could of course also do
CONSTRAINT `FKgy4qe3dnqrm3ktd76sxp7n4c2`
FOREIGN KEY (`department_id`)
REFERENCES `departments` (`id`)
ON DELETE SET DEFAULT
both would do the same thing in this case as your default is NULL for that column
There is a lot of questions about collation mixup in SELECT and INSERT * SELECT statements. Mine is a simple INSERT with nothing added to it but the data.
The error spawned in the process is:
Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='
All field names and table names have been simplified. The query being executed is:
INSERT INTO table1 (`a`,`b`,`c`,`d`,`e`,`f`,`g`,`h`,`i`,`j`) VALUES (?,?,?,?,?,?,?,?,?,?);```
It has been prepared to receive some data that is brought in by the Java process with JDBI.
The underlying tables have nothing odd about them. Their DDLs look as follows.
CREATE TABLE `table1` (
`a` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`b` varchar(6) COLLATE utf8_unicode_ci DEFAULT NULL,
`c` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`d` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`e` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`f` int(11) DEFAULT NULL,
`g` text COLLATE utf8_unicode_ci,
`h` bigint(20) DEFAULT NULL,
`i` bigint(20) DEFAULT NULL,
`j` datetime DEFAULT NULL,
`k` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`a`,`e`),
KEY `c` (`c`,`d`),
CONSTRAINT `fk_1` FOREIGN KEY (`a`) REFERENCES `table2` (`a2`),
CONSTRAINT `fk_2` FOREIGN KEY (`c`, `d`) REFERENCES `table3` (`a3`, `b3`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
CREATE TABLE `table2` (
`a2` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`b2` varchar(32) COLLATE utf8_unicode_ci DEFAULT NULL,
`c2` mediumtext COLLATE utf8_unicode_ci,
`d2` mediumtext COLLATE utf8_unicode_ci,
`e2` bigint(11) DEFAULT '0',
PRIMARY KEY (`a2`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
CREATE TABLE `table3` (
`a3` varchar(32) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`b3` varchar(32) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`a3`,`b3`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
As can be seen, there is absolutely nothing about the collation that I can understand. Is it possible that the data coming in from the java world is causing this? Could it be related to the current connection session variables?
UPDATE
I forgot to add the MySQL version: 5.6
I have solved this issue in my test runs moving all field collations to DEFAULT and the table collation to utf8_general_ci on table1. However, this is an unacceptable solution to the problem and it does not come close to answering how can there be a collation mixup in a simple INSERT statement?
I found the culprit. There is a TRIGGER on this table that references another table from another schema. The conflict exists in the trigger statements which does not help that the error message makes no allusion to such fact.
That answers
how can there be a collation mixup in a simple INSERT statement?
There is a TRIGGER accompanying the INSERT
I am running this Query on MySQL workbench with the latest version of MySQL installed on MacOS.
My SQL Query is:
CREATE DATABASE IF NOT EXISTS `imdb`;
USE `imdb`;
DROP TABLE IF EXISTS `rating`;
DROP TABLE IF EXISTS `media`;
CREATE TABLE `media` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(70) DEFAULT NULL,
`year` varchar(70) DEFAULT NULL,
`rated` varchar(70) DEFAULT NULL,
`released` varchar(70) DEFAULT NULL,
`runtime` varchar(70) DEFAULT NULL,
`genre` varchar(70) DEFAULT NULL,
`director` varchar(70) DEFAULT NULL,
`writer` varchar(70) DEFAULT NULL,
`actors` varchar(70) DEFAULT NULL,
`plot` varchar(7000) DEFAULT NULL,
`language` varchar(70) DEFAULT NULL,
`country` varchar(70) DEFAULT NULL,
`awards` varchar(70) DEFAULT NULL,
`poster` varchar(270) DEFAULT NULL,
`metascore` varchar(70) DEFAULT NULL,
`imdb_rating` varchar(70) DEFAULT NULL,
`imdb_votes` varchar(70) DEFAULT NULL,
`imdb_id` varchar(70) NOT NULL,
`type` varchar(70) DEFAULT NULL,
`dvd` varchar(70) DEFAULT NULL,
`box_office` varchar(70) DEFAULT NULL,
`production` varchar(70) DEFAULT NULL,
`website` varchar(70) DEFAULT NULL,
`response` varchar(70) DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `rating` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`source` varchar(70) DEFAULT NULL,
`value` varchar(70) DEFAULT NULL,
`imdb_id` varchar(70) NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (`imdb_id`)
REFERENCES `media`(`imdb_id`)
ON DELETE SET NULL
);
SET FOREIGN_KEY_CHECKS = 1;
The create Query on table rating is failing. I don't know why, any help would be appreciated.
The exact error response is:
10:12:44
CREATE TABLE `rating` ( `id` int(11) NOT NULL AUTO_INCREMENT, `source` varchar(70) DEFAULT NULL, `value` varchar(70) DEFAULT NULL, `imdb_id` varchar(70) NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`imdb_id`) REFERENCES `media`(`imdb_id`) ON DELETE SET NULL )
Error Code: 1215.
Cannot add foreign key constraint
0.123 sec
I am building a Spring REST application that uses one too many relationships for building a local copy of the IMDB database or something similar.
A foreign key in MySQL doesn't actually have to reference a primary key column, but it does have to reference a column which is unique. So, one possible fix here would be to add a unique constraint on the imdb_id column:
ALTER TABLE media ADD CONSTRAINT cstr_imdb UNIQUE (imdb_id);
A foreign key is a column or group of columns in a relational database table that provides a link between data in two tables. It acts as a cross-reference between tables because it references the primary key of another table, thereby establishing a link between them.
'id' is the primary key in your table 'media' and not 'imdb_id'. Hence, you can't make a reference to 'imdb_id'.
imdb_id is not a key on the media table - foreign keys must reference keys (or, at least, unique constraints). If imdb_id on the media table should be unique, then you could put a UNIQUE CONSTRAINT on it and will be able to reference it with a foreign key.
Also, you have on delete set null on a column that cannot be null
I am trying to get the stop_name of the last inserted row in the table with preparedStatement. How can I get the last inserted one?
I appreciate any help.
behavoiur table:
CREATE TABLE IF NOT EXISTS behaviour(
behaviour_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
mac VARCHAR(30) NOT NULL,
stop_name VARCHAR(30) NOT NULL,
stop_distance INT(11) NOT NULL,
speed INT(11) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
You may try this query:
select stop_name from behaviour where created_at in (select max(created_at) from behaviour)
Another solution:
select stop_name from behaviour order by behaviour_id desc limit 1;
I have two tables
CREATE TABLE `cb_jobs` (
`JOB_IDENTIFIER` INT(11) NOT NULL,
`CB_CREDENTIAL_TYPE_IDENTIFIER` INT(11) NOT NULL
`IS_DELETED` TINYINT(1) NULL DEFAULT '0',
PRIMARY KEY (`JOB_IDENTIFIER`),
INDEX `FK_cb_jobs_cb_credential_type` (`CB_CREDENTIAL_TYPE_IDENTIFIER`)
CONSTRAINT `FK_cb_jobs_cb_credential_type` FOREIGN KEY (`CB_CREDENTIAL_TYPE_IDENTIFIER`) REFERENCES `cb_credential_type` (`CB_CREDENTIAL_TYPE_IDENTIFIER`) ON UPDATE CASCADE ON DELETECASCADE)COLLATE='latin1_swedish_ci'
ENGINE=InnoDB;
CREATE TABLE `cb_credential_type` (
`CB_CREDENTIAL_TYPE_IDENTIFIER` INT(11) NOT NULL AUTO_INCREMENT,
`CB_CREDENTIAL_CODE` VARCHAR(50) NULL DEFAULT NULL,
`CB_CREDENTIAL_TYPE_NAME` VARCHAR(1000) NULL DEFAULT NULL,
`CREATED_DATE` DATETIME NULL DEFAULT NULL,
`CREATED_BY_USER` INT(11) NULL DEFAULT NULL,
`UPDATED_DATE` DATETIME NULL DEFAULT NULL,
`UPDATED_BY_USER` INT(11) NULL DEFAULT NULL,
`IS_DELETED` TINYINT(1) NULL DEFAULT '0',
PRIMARY KEY (`CB_CREDENTIAL_TYPE_IDENTIFIER`)
)COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=8;
I would like to get the details of 2nd table based on the credential type id.
How to write Hibernate mapping classes with one to one relationship using hibernate annotations.Anybody please help me.......
Check this tutorial this might help you
http://www.dzone.com/tutorials/java/hibernate/hibernate-example/hibernate-mapping-one-to-one-1.html
check the hibernate one-one annotated tutorial
http://www.dzone.com/tutorials/java/hibernate/hibernate-example/hibernate-mapping-one-to-one-using-annotations-1.html