Suppose there is a File table with the id, fileName fields, it can be referenced by many other objects of the system. Is it possible to find all entities to which no one refers by regular means of Hibernate? Or at least all references to this entity?

PS I use Spring Data over Hibernate, if it somehow helps.

  • Only one by one check of associations with other types of entities will help to find entities to which no one refers. Depending on the type of association (many-to-one, one-to-many, etc.), the check is performed in different ways. - Sergey

3 answers 3

In his case, this problem was solved by specifying bilateral relations. In one class (dependent) -

@OneToMany(mappedBy = "avatar") private Set<Users> users; 

Referring to:

 @JoinColumn @ManyToOne private File avatar; 

Thus, the database structure does not change, but connections can be checked.

    There are no established tools in Hibernate for this. You should write a SQL query that will fetch from all referencing tables. The structure of the database is not presented in the question, so I will try to give an abstract example of such a query:

     SELECT * FROM File WHERE id NOT IN ( SELECT file_id FROM table1 UNION SELECT file_id FROM table2 UNION ... ) 

    You can execute a query using javax.persistence.EntityManager.createNativeQuery or org.hibernate.Session.createSQLQuery , depending on which API you use. Such a request can be very resource-intensive, so you should conduct performance tests, analysis of the request.

    If you fail to achieve the desired performance / speed of execution, issue a new question about this with a description of the structure of the tables, registering it with tags related to SQL, and not to Hibernate, and be sure to specify which DBMS is used (in the tags too).

      It is possible, but for this purpose, explicitly specify the relationship between tables in both DB and hibernate.

      Then, when generating classes-representations in them, either Set or List will be declared - lists with objects of dependent rows from other tables.

      PS In general, there is Restriction.isEmpty () for collections, but I have not found any clear examples of how to point to the collection of dependent rows. Need to test.

      • First of all, you did not answer the question (you wrote “ You can ”, but you didn’t write exactly how). Secondly, I think that the author meant searching for specific records in the database table, and not inspecting the data structure. - bobzer
      • I just explained that in principle, this is possible, but one thing, just brute force. I will not explain how to declare table links; This is a separate and shaggy topic (the tempo depends on the method of maping). PS In general, there is Restriction.isEmpty () for collections, but I have not found any clear examples of how to point to the collection of dependent rows. Need to test. - Riĥard Brugekĥaim