OOP & Transactions between objects JAVA

☆樱花仙子☆ 提交于 2020-01-24 20:59:07

问题


i hope somebody can help me with this, i have 2 clases User and Adress both have addNewUser() and addNewAdress() this methods do a transactions with preparedsatement, but i dont know how to join the objets because when i add a new user i need to add a new adrees with the user id.

class User{
  public boolean addNewUser(){
        Connection con = conecctions.getconnection;

    Statement stmt = null;
    Boolean result = false;


            try {

        stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_UPDATABLE);

        PreparedStatement addUser = 
           con.prepareStatement(query);
          addUser.setBoolean(1, false);
          addUser.setString(1, "name");

        con.commit();

          ...
          ...
          ...
        Adress newAdress = new Adress("new_user_id", "addres");
      newAdrees.addNewAdress();

  }

i think do that its wrong, how can i implement composition? and use the same commit for both methods. thanks!


回答1:


You don't have to commit the transaction to get the insert id. (There is an answered question on how you can get it here). Then, you need to commit just once the transaction at the end of your unit of work. I would suggest to leave the transaction management outside of this object's scope, and don't commit the transaction in any of these objects (either User or Address). This will limit their scope and the code become cleaner, also the transaction code (commit-rollback-exception handling) will be standalone and reusable.



来源:https://stackoverflow.com/questions/48552027/oop-transactions-between-objects-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!