INSERT data into tables in java - java

There are two tables:
CREATE TABLE A(
id INT NOT NULL AUTO_INCREMENT,
softwareId VARCHAR(50) NOT NULL,
version VARCHAR(50) NOT NULL,
releaseDate TIMESTAMP NOT NULL,
PRIMARY KEY (id)
);
and
CREATE TABLE UPDATE_FILE(
id INT NOT NULL AUTO_INCREMENT,
updateId INT,
FOREIGN KEY (updateId) REFERENCES SOFTWARE_UPDATE(id) ON DELETE CASCADE ON UPDATE CASCADE,
osName VARCHAR(50) NOT NULL,
osArch VARCHAR(50) NOT NULL,
filePath VARCHAR(2048) NOT NULL,
fileName VARCHAR(50) NOT NULL,
PRIMARY KEY (id)
);
they have relationship on updateId.
I know how to add data into a table with no relationships.
getConnection().prepareStatement("INSERT INTO table(c1,c2,c3) VALUES(?,?,?)");
pStatement.setString(1, version);
pStatement.setString(2, path);
pStatement.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
pStatement.executeUpdate();
I'm not sure if adding new data into tables with relationship is the same?

It is the same. But may I suggest you use JPA instead of JDBC for this? I think that will be really easy when it comes to complex foreign key mappings. Make sure the database you are using is JPA compatible though.

Related

Cannot delete or update a parent row: spring problem without cascade

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

MYSQL update with inner join performance

The join is done on the primary key column of both these tables.
I have a doubt if I should fire a select query before the update or will this query be a good alternative?(in terms of performance)
order item table
order_item_id
order_id
quantity
unit_price
shipping_price
business_id
workflow_id
delivery_id
item_id
Orders table
billing_address_id
shipping_address_id
payment_mode
total_price
shipping_price
customer_id
order_id
Following is the query I fire from my Java service (using jdbc) :
UPDATE order_items t1
INNER
JOIN Orders t2
ON t2.order_id = t1.order_id
SET t1.workflow_id = ?
WHERE t1.order_item_id = ?
and t2.order_id = ?
and t2.customer_id = ?
and t1.delivery_id = ?
UPDATE : Adding show create table order_items
'CREATE TABLE `order_items` (
`order_item_id` int(20) NOT NULL AUTO_INCREMENT,
`quantity` int(10) unsigned NOT NULL,
`unit_price` int(10) unsigned NOT NULL,
`shipping_price` int(10) unsigned NOT NULL,
`pickup_date` datetime DEFAULT NULL,
`create_TS` datetime DEFAULT CURRENT_TIMESTAMP,
`update_TS` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
`business_id` int(10) NOT NULL,
`order_id` int(11) NOT NULL,
`item_id` int(10) unsigned NOT NULL,
`delivery_id` int(11) NOT NULL,
`workflow_id` int(11) DEFAULT NULL,
PRIMARY KEY (`order_item_id`),
KEY `fk_business_id` (`business_id`),
KEY `fk_order_id` (`order_id`),
KEY `fk_item_id` (`item_id`),
KEY `fk_delivery_id` (`delivery_id`),
CONSTRAINT `fk_business_id` FOREIGN KEY (`business_id`) REFERENCES `business` (`MID`),
CONSTRAINT `fk_delivery_id` FOREIGN KEY (`delivery_id`) REFERENCES `delivery_mode` (`delivery_id`),
CONSTRAINT `fk_item_id` FOREIGN KEY (`item_id`) REFERENCES `item_business` (`item_id`),
CONSTRAINT `fk_order_id` FOREIGN KEY (`order_id`) REFERENCES `Orders` (`order_id`)
)
Talking in theory
You should have the minimum set of data before you do the join, so the join will actually be performed only on the data you need, and that is the case even with the update that is internally a special select and "write this data on the select"
Talking in practice
One of the job of any dbms is to perform an agressive level of optimization using database algebra and other stuff, so most of the time the time you spend in optimizing your query is actually futile because your dbms will perform the same level of optimization
So what
I would try to have the table the slimmest as possible but without getting too crazy, I performed on a aws db2.micro machine an update query on like 100k rows and it took it like 4 seconds, so in my opinion, try and see if you're getting the real result you need.
tl;dr just try and see if the speed increase

Derby: Referencing Multiple Foreign Keys From Different Tables

Good day!
I have been searching the Internet for an answer to my problem but I have not been able to get one.
How do I reference foreign keys from different tables in a Derby database?
This is my current SQL code:
CREATE TABLE class_t
(course_id VARCHAR(6) NOT NULL,
semester VARCHAR(6) NOT NULL CONSTRAINT sem_constraint CHECK (semester IN ('1st','2nd','module')),
school_year DATE NOT NULL,
course_name VARCHAR(70) NOT NULL,
CONSTRAINT class_pk PRIMARY KEY (course_id, semester, school_year)
);
CREATE TABLE student_t
(id_number INT NOT NULL,
fullname VARCHAR(35) NOT NULL,
contact_num VARCHAR(35),
email VARCHAR(25),
CONSTRAINT student_pk PRIMARY KEY (id_number)
);
CREATE TABLE student_list
(course_id VARCHAR(6) NOT NULL,
semester VARCHAR(6) NOT NULL CONSTRAINT sem_constraint2 CHECK (semester IN ('1st','2nd','module')),
school_year DATE NOT NULL,
id_number INT NOT NULL,
CONSTRAINT student_list_pk PRIMARY KEY (course_id, semester, school_year, id_number),
CONSTRAINT student_list_FK FOREIGN KEY (course_id, semester, school_year, id_number)
REFERENCES class_t (course_id, semester, school_year), student_t (id_number) #this is my problem
);
Your help is very much appreciated! Thanks in advance.
Nevermind, I've figured it out myself. Had a clue at the solution when I looked at http://db.apache.org/derby/docs/10.2/ref/rrefsqlj13590.html in the examples part. There should be different constraints for each foreign keys from different tables. It should be like this:
CREATE TABLE student_list
(course_id VARCHAR(6) NOT NULL,
semester VARCHAR(6) NOT NULL CONSTRAINT sem_constraint2 CHECK (semester IN ('1st','2nd','module')),
school_year DATE NOT NULL,
id_number INT NOT NULL,
CONSTRAINT student_list_pk PRIMARY KEY (course_id, semester, school_year, id_number),
CONSTRAINT student_list_fk1 FOREIGN KEY (course_id, semester, school_year)
REFERENCES class_t (course_id, semester, school_year),
CONSTRAINT student_list_fk2 FOREIGN KEY (id_number)
REFERENCES student_t (id_number)
);
Thanks for all your help stackoverflow.com community! :)

My Insert Into Statement is not working

I was working with UIs where the user will click the add button to add employees, but when I do it, it gives me an error like this
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`finalpayroll`.`personal_info`, CONSTRAINT `personal_info_ibfk_1`
How would I fix this?? I know I am using a parent key, and its foreign key is the User, and also take note that the parent key has already a data, but it seems my query won't work, why is that? I am using a foreign key with delete cascade and on update cascade so that when I delete a data, all of the child table rows will be deleted, vice versa. here's my key for adding or inserting statements
public void addEmployee(Personal p ,Contact c,Employee e) {
Connection conn = Jdbc.dbConn();
Statement statement = null;
String insert1 = "INSERT INTO personal_info (`First_Name`, `Middle_Initial`, `Last_Name`, `Date_Of_Birth`, `Marital_Status`, `Beneficiaries`) VALUES ('"+p.getFirstName()+"', '"+p.getMiddleInitial()+"'" +
" , '"+p.getLastName()+"', '"+p.getDateOfBirth()+"', '"+p.getMaritalStatus()+"', '"+p.getBeneficiaries()+"')";
try {
statement = conn.createStatement();
statement.executeUpdate(insert1);
statement.close();
conn.close();
JOptionPane.showMessageDialog(null, "Employee Added!!");
} catch(Exception ex) {
ex.printStackTrace();
}
}
Users table:
CREATE TABLE `users` (
`idusers` int(11) NOT NULL AUTO_INCREMENT,
`emp_id` varchar(45) DEFAULT NULL,
`emp_pass` varchar(45) DEFAULT NULL,
PRIMARY KEY (`idusers`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
Personal_info table:
CREATE TABLE `personal_info` (
`idpersonal_info` int(11) NOT NULL AUTO_INCREMENT,
`First_Name` varchar(45) DEFAULT NULL,
`Middle_Initial` varchar(45) DEFAULT NULL,
`Last_Name` varchar(45) DEFAULT NULL,
`Date_Of_Birth` varchar(45) DEFAULT NULL,
`Marital_Status` varchar(45) DEFAULT NULL,
`Beneficiaries` varchar(45) DEFAULT NULL,
PRIMARY KEY (`idpersonal_info`),
CONSTRAINT `personal_info_ibfk_1`
FOREIGN KEY (`idpersonal_info`)
REFERENCES `users` (`idusers`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
You are trying to insert a record with 6 fields: First_Name, Middle_Initial, Last_Name, Date_Of_Birth, Marital_Status and Beneficiaries. Your schema is currently unknown but none of these fields seem to be a candidate foreign key to id of User table you mentioned. Thus I think there is a default value for that foreign key column and that default value is missing in User table.
Needless to say, you shouldn't have a default value for a foreign key of any table..
I am adding these information regarding your questions in comments and update on your question:
A foreign key is a link between a child table and parent table, personal_info and users tables in your case respectively. Child table's foreign key column must reference to a key value in parent table which means that for every value in child table's FK column, there must be a value in parent table's linked column.
Now, in your case when you try to insert a new personal_info record MySQL assigns a idpersonal_info to it, since you defined it as auto increment. But since there is a link to users table, MySQL searchs for the new idpersonal_info to be inserted in users table's idusers column. And as you are getting this exception, you surely don't have that value in the users table.
You can change your table structure as follows:
CREATE TABLE `personal_info` (
`idpersonal_info` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
... OTHER FIELD DEFINITIONS,
PRIMARY KEY (`idpersonal_info`),
CONSTRAINT `user_id_fk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`idusers`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB
And your query will need to include user_id field as well. So it will be something like this:
INSERT INTO personal_info
(`user_id`, `First_Name`, `Middle_Initial`, `Last_Name`, `Date_Of_Birth`, `Marital_Status`, `Beneficiaries`)
VALUES ( .... SET YOUR VALUES HERE. DON'T FORGET TO SET A VALID USER_ID
Looks like in your Personal_Info table you have a column called "finalpayroll", that points to a column in another table (a foreign key) and it's required (not nullable). In your insert you're not giving it a value. So what you could do is make that column nullable.
Or could be the other way around as #Konstantin Naryshkin is saying
What the error means is that you are trying to insert a value into a column with a foreign key a value that is not in the remote table.
I assume that there is a user column that we are not seeing. Since you are not explicitly setting the value, I assume that it is getting a default. The default value is not in the parent table.

No relations in entity classes created with NetBeans from database

I'm using Netbeans to create entity class from database, I select all table in my database and the classes are created without any information about relations, like #OneToMany, #ManyToOne etc...
This is an example of two tables I have in my DB, is there anything else I need to specify in the tables creation?
CREATE TABLE `Indicator` (
`ID` int(11) NOT NULL,
`Number` int(11) NOT NULL,
`ApplicablePeriodTypeID` int(11) NOT NULL,
`IndicatorSourceID` int(11) DEFAULT NULL,
PRIMARY KEY (`ID`),
KEY `IndicatorSourceID` (`IndicatorSourceID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1$$
CREATE TABLE `IndicatorSource` (
`ID` int(11) NOT NULL,
`CollectionName` varchar(255) NOT NULL,
`URL` varchar(1000) DEFAULT NULL,
`Number` int(11) NOT NULL,
`SourceName` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1$$
You might need to add a foreign key constraint, e.g. on IndicatorSourceID. Otherwise there's no hint that IndicatorSourceID refers to IndicatorSource.ID.
Changing the ENGINE to InnoDB and adding the foreign keys solved the problem. some db engine different from InnoDB dont support foreign key and when trying to add one, it doesn't generate any error.
As a side note: It seems the create entity classes from database feature in Netbeans 6.9 doesn't add relationships for foreign keys migrated from alternate keys -- only those migrated from primary keys.
Which database are you using?? Are you sure you have configure the database connection using
compatible driver to your database and jdk version...

Categories