简体   繁体   中英

JDBC and mySQL converting related database tables to objects

I want to build an Java program that connects with a mySQL database that consists of tables that has different many-to-many and one-to-many table connections.

The program is suposed to handle books with different authors and reviews. The authors and books is related through a many-to-many connection. (as an author can write different books and a book can have different authors). The books and reviews are connected with an one-to-many connection.

On the program side i have made an Album object that stores its authors and reviews in separate array lists. The idea is to iterate through the different albums and pick upp that album data and then its authors and reviews.

The problem is that a can't figure out the best way to do this. I suppose it would be best if this was made in a closed transaction the make it more stable.

With my limited SQL and java experience i can only see 3 different way to preform this task:

  1. Should i do this on the program side with a loop that loops through each album based on the row number and then gets the authors seperalty with a separate stored procedure and revives through the foreign keys with another stored procedure

  2. Or should i make this whole action as an stored procedure on the DB side?

  3. Or should i fetch all the tables in a big join procedure and then iterate trough this result set with som Java functions?

Or is it an better way to do this?

BR

If I were you, I'd use an ORM for that. Java has the JPA2 standard which is implemented eg by Hibernate or Eclipselink and this allows you to easily read 1:n and n:m relationships between objects.

In most use-cases, you don't need to iterate, but start with a find query (eg user is searching for all books of a certain author). an ORM allows you to issue this query and get back a list of books, reviews are already a pre-filled list on each book.

I recommend you use an ORM (Object Relational Mapping) framework, that simplify the access to you relational data in MySQL, from Java Objects. See Hibernate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM