Java: Hibernate - Query to delete from multiple tables - java

I have two tables connected by a foreign key with a one to many relation.
In entity A I have the following:
#org.hibernate.annotations.Cascade( {
org.hibernate.annotations.CascadeType.ALL,
org.hibernate.annotations.CascadeType.DELETE_ORPHAN })
#OneToMany(mappedBy="monitoredFlight", fetch = FetchType.LAZY)
#OnDelete(action=OnDeleteAction.CASCADE)
private List<bTable> BTable = new ArrayList<BTable>();
Now I try to delete from table A with a bulk delete query:
Query query = em.createQuery("delete from A where originDateTime<:date");
and I get the foreign key constraint error. I decided to do the delete with a join just as I would in mysql, so I changed it to:
Query query = em.createQuery("delete from A join BTable where originDateTime<:date");
and I got a syntax error. I have tried several combination with or without join and nothing works; any ideas?
I am using mysql for the database and java for the language.

You can use a native query, the following should work in mysql:
delete a , b from a inner join b on a.id=b.a_id where ...

You can setup a foreign key with the parameter on delete cascade so that when the key it references is deleted all rows that it is a foreign key on are also deleted.

Related

How to view table relation in PostgreSQL Server?

How to view table relation in PostgreSQL server?
I have tried several times and more than 2 years ago to find table relation in PostgreSQL server but couldn't get any help.
So are there any way to find table relation same in SQL server or Access? Or is it possible to view table relation in PostgreSQL server?
If you want to list all the relationships that start from a table, you must search the foreign keys.
In Postgresql it means to search for constraints.
It is solved in this other question:
SQL to list table foreign keys
From the answer:
SELECT
tc.constraint_name, tc.table_name, kcu.column_name,
ccu.table_name AS foreign_table_name,
ccu.column_name AS foreign_column_name
FROM
information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
ON tc.constraint_name = kcu.constraint_name
JOIN information_schema.constraint_column_usage AS ccu
ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY' AND tc.table_name='mytable';
You could try using a UI like DataGrip or pgAdmin. I use DataGrip on my Postgres apps. You may simply try using the postgres interactive shell -- psql.
Best of luck
I know this question is not exactly about that, but I think lots of people land here looking for an easy way to see the relationships between tables using different data types (like parent id with bigint and child foreign key int, and vice versa).
Here's a quick way to spot all the columns with different types between parents and child tables:
SELECT
tc.constraint_name, tc.table_name, kcu.column_name,
ccu.table_name AS foreign_table_name,
ccu.column_name AS foreign_column_name,
cf.data_type AS child_data_type,
cp.data_type AS parent_data_type
FROM
information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
ON tc.constraint_name = kcu.constraint_name
JOIN information_schema.constraint_column_usage AS ccu
ON ccu.constraint_name = tc.constraint_name
JOIN information_schema.tables as t
on t.table_name = tc.table_name and t.table_catalog = tc.table_catalog and t.table_schema = tc.table_schema
JOIN information_schema.columns as cf
on cf.table_name = tc.table_name and cf.column_name = kcu.column_name and cf.table_catalog = tc.table_catalog and cf.table_schema = tc.table_schema
JOIN information_schema.columns as cp
on cp.table_name = ccu.table_name and cp.column_name = ccu.column_name and cp.table_catalog = ccu.table_catalog and cp.table_schema = ccu.table_schema
WHERE constraint_type = 'FOREIGN KEY'
and cf.data_type <> cp.data_type;
Enjoy!

Native insert JPA Spring

I have a many-to-many relationship between two entities:
Entity A
ID
NAME
Entity B
ID
NAME
Join Table A_B
A_ID
B_ID
I'm trying to do an insert based off of the secondary unique attributes (names). I want to avoid fetching each entity by their name and then saving (2 queries & 1 insert vs 1 insert). Effectively, I'm looking to do something like this:
#Query(nativeQuery = true, value = "INSERT INTO A_B(A_ID, B_ID) VALUES ((SELECT ID FROM A WHERE NAME = ?), (SELECT ID FROM B WHERE NAME = ?))")
void addToJoinTable(String nameA, String nameB);
I saw this post, but I'm getting exceptions because an insert doesn't return a result set. The post mentions setting nativeQuery to true would resolve the issue, but I've had no such luck... Is there another & better way to do this?
Disclaimer: I am new to JPA, so this might be a stupid question...

Delete rows from two tables with same primary key

I have two tables:
Table1: orders
idOrder,
Blockquote
idUser
Table2: ordersinfo
idOrder,
.......,
.......
idOrder is primary a key for two tables. I have to delete from this tables rows by idUser. I tried different ways, but nothing helped me.
My Questions: What query, I should use?
I have this exception
MySQLIntegrityConstraintViolationException
You will need to issue two delete statement
-- Delete OrderInfo table
DELETE FROM ordersinfo
WHERE EXISTS (SELECT 1
FROM orders
WHERE orders.idOrder = ordersinfo.idOrder
AND IdUser = ???)
-- Delete Orders
DELETE FROM Orders
WHERE IdUser = ???

How to delete Child Table record With parent key In hibernate Annotation.?

i am using hibernate annotation and Mysql for database.
I have Two Table One is Purchaser Table and Other one is CashReceipt. CashReciept has a reference key on Purchaser table.
so how can i delete a record of CashReceipt for specific Purchaser?
i have tried this query
session.createQuery("Delete FROM CashReceipt cr LEFT JOIN cr.purchase p WHERE p.id=:sid")
.setInteger("sid", purchase.getId()).executeUpdate();
I got my answer by trying this query.
session.createQuery("Delete FROM CashReceipt cr WHERE cr.purchase.id=:sid")
.setInteger("sid", purchase.getId()).executeUpdate();
Why are you doing it manually when you can use session.delete like :
SomeEntity ent = session.get(SomeEntity.class, '1234');
session.delete(ent);
Also you may want to look at CascadeType for your parent table. Set it to CascadeType.DELETE in your parent table.
#OneToMany(cascade = CascadeType.DELETE)
List<Child> childElements;
It will delete all child elements associated with that parent.

JoinColumn name not used in sql

I have a problem with mapping many-to-one relationship without exact foreign key constraint set in database. I use OpenJPA implementation with MySql database, but the problem is with generated sql scripts for insert and select statements.
I have LegalEntity table which contains RootId column (among others). I also have Address table which has LegalEntityId column which is not nullable, and which should contain values referencing LegalEntity's "RootId" column, but without any database constraint (foreign key) set.
Address entity is mapped:
#Entity
#Table(name="address")
public class Address implements Serializable {
...
#ManyToOne(fetch=FetchType.LAZY, optional=false)
#JoinColumn(referencedColumnName="RootId", name="LegalEntityId", nullable=false, insertable=true, updatable=true, table="LegalEntity")
public LegalEntity getLegalEntity() {
return this.legalEntity;
}
}
SELECT statement (when fetching LegalEntity's addresses) and INSERT statment are generated:
SELECT t0.Id, .., t0.LEGALENTITY_ID FROM address t0 WHERE t0.LEGALENTITY_ID = ? ORDER BY t0.Id DESC [params=(int) 2]
INSERT INTO address (..., LEGALENTITY_ID) VALUES (..., ?) [params=..., (int) 2]
If I omit table attribute from mentioned statements are generated:
SELECT t0.Id, ... FROM address t0 INNER JOIN legalentity t1 ON t0.LegalEntityId = t1.RootId WHERE t1.Id = ? ORDER BY t0.Id DESC [params=(int) 2]
INSERT INTO address (...) VALUES (...) [params=...]
So, LegalEntityId is not included in any of the statements.
Is it possible to have relationship based on such referencing (to column other than primary key, without foreign key in database)? Is there something else missing?
Thanks in advance.
Try changing your FetchType to eager. OpenJPA should not query for the LegalEntity until it's requested by calling getLegalEntity.
Also, the absence of constraints shouldn't matter (somebody please correct me if I'm wrong).

Categories

Resources