有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在db中更新邮件列表的最佳方法

我有下面的数据库模式

SQL> describe USERS;
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 user_id                                   NOT NULL NUMBER(38)
 name                                      NOT NULL VARCHAR2(50)
 password                                  NOT NULL VARCHAR2(50)
 score                                              NUMBER(38)
 notify_before_expiration                           NUMBER(38)
 is_admin                                  NOT NULL NUMBER(1)

SQL> describe EMAIL;
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 email_id                                  NOT NULL NUMBER(38)
 email                                     NOT NULL VARCHAR2(50)
 user_id                                   NOT NULL NUMBER(38)

所以一个用户有很多电子邮件。 用户可以访问一个表单,在那里他们可以添加/删除他们的电子邮件。 问题是:哪种更新db的方式更好,因为db拥有从该表单获得的邮件列表

我在想:(java伪代码)

//List of mails in db.
ArrayList<String> emailsInDB = getAllMailsFromDB(user);

//List of mails from the form
ArrayList<String> emailsInForm = form.getAllMails();

//Iterates all emails gotten from the form.
for (String email : emailsInForm) {
  if (emailsInDB.contains(email) {
    //Already in the db
    emailsInDB.remove(email, user);
  }  else {
    //New mail! Add it in the db!
    db.insertMail(email, user);
}

//All emails that were in the db, but not in the form,
//were deleted. Delete them from the db.
for (String email : emailsInDB) {
  db.deleteMail(email);
}

欢迎提出更好的想法! 谢谢你的阅读


共 (2) 个答案

  1. # 1 楼答案

    您可以做的一个优化是在插入新电子邮件之前先删除电子邮件

    在伪SQL中:

    DELETE from emails WHERE emali.user_id=userid AND email NOT IN(...list of emails from the form...) 
    

    这会在一次调用SQL server时删除所有需要删除的电子邮件,如果您有很多电子邮件,而服务器离您很远,则会节省一些延迟

    然后继续插入电子邮件

    //List of mails in db.
    ArrayList<String> emailsInDB = getAllMailsFromDB(user);
    
    //Iterates all emails gotten from the form.
    for (String email : emailsInForm) {
      if (!emailsInDB.contains(email) {
        //New mail! Add it in the db!
        db.insertMail(email, user);
    }
    
  2. # 2 楼答案

    尽管没有很好的文档记录,Oracle允许您定义一种称为VARRAY的数组类型。通过这些,您可以将批处理中的“emailsToAdd”和“emailsToDelete”传递到过程中。这将允许您减少对DB的调用量,从而提高方法的整体性能Here是一个让您开始学习的示例