简体   繁体   English

JDBC和mySQL将相关的数据库表转换为对象

[英]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. 我想构建一个与mySQL数据库连接的Java程序,该数据库由具有不同的多对多和一对多表连接的表组成。

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. 在程序方面,我制作了一个Album对象,该对象将其作者和评论存储在单独的数组列表中。 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: 以我有限的SQL和Java经验,我只能看到3种不同的方式来执行此任务:

  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? 还是应该在大型连接过程中获取所有表,然后使用som Java函数迭代该结果集?

Or is it an better way to do this? 还是做这件事的更好方法?

BR BR

If I were you, I'd use an ORM for that. 如果我是你,那么我将使用ORM。 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. Java具有JPA2标准,该标准由Hibernate或Eclipselink实现,因此您可以轻松读取对象之间的1:n和n:m关系。

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. ORM允许您发出此查询并获取书籍列表,评论已经是每本书的预填充列表。

I recommend you use an ORM (Object Relational Mapping) framework, that simplify the access to you relational data in MySQL, from Java Objects. 我建议您使用ORM(对象关系映射)框架,该框架简化了从Java Objects访问MySQL中的关系数据的过程。 See Hibernate 参见休眠

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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