1

我正在寻找以下使用 Java 中准备好的语句更新 SQL 表的最佳编码模式。

SQL 表名是 table1 和 attr1, att2, att3, att4, attr5 and .... in table1。

目前我的伪

If (want to update att1 only) {
    PreparedStatement pst = Connection.prepareStatement("UPDATE table1 SET attr1 = ?");
} else if (want to update attr1 & attr2 only) {
    PreparedStatement pst = Connection.prepareStatement("UPDATE table1 SET attr1 = ?, attr2 = ?");
} else if (want to update attr1 & attr2 & attr3) {
    PreparedStatement pst = Connection.prepareStatement("UPDATE table1 SET attr1 = ?, attr2 = ?, attr3 = ?");
}  else if (want to udpate attr1 & attr3) {
   PreparedStatement pst = Connection.prepareStatement("UPDATE table1 SET attr1 = ?, attr3 = ?");
} ......

.... else {
    Bad Request
}

上面的代码会使 WHERE SQL 条件变得更加复杂。我不喜欢这里的 if - else if - else 模式,因为很难维护。

是的,我知道其他选项是动态生成 UPDATE SQL 查询并使用 ORM 解决方案。我相信动态生成 SQL UPDATE Query 逻辑会变得复杂。

请提供最适合此处的任何其他模式或解决方案。

4

1 回答 1

1

您可以只编写一个更新语句来更新所有非关键字段并每次调用它。

public class MyThing {
     private long uniqueID;
     private String attr1;
     private String attr2;
     private String attr3;
     // ++ rest of attriutes, getters and setters  
}

public MyThing getMyThing(long uniqueID) {
    // code to retrieve MyThing from table1, poulating all attributes
}

public void updateMyThing(MyThing myThing) {
    PreparedStatement pst = Connection.prepareStatement
        (" UPDATE table1 SET attr1 = ?, attr2 = ?, attr3 = ?, attr4 = ?, attr5 = ?" +
         " WHERE id = ? );
    pst.SetString(1, myThing.getAttr1());
    pst.SetString(2, myThing.getAttr2());
    pst.SetString(3, myThing.getAttr3());
    pst.SetString(4, myThing.getAttr4());
    pst.SetString(5, myThing.getAttr5());
    pst.SetString(6, myThing.getId());

    // etc.
}

So retrieve a MyThing object from the DB. Update whatever attributes you want then call the update method. All attributes updated whether they have changed or not

于 2013-03-30T22:10:33.587 回答