面向对象对象之间的事务JAVA

面向对象对象之间的事务JAVA

本文介绍了面向对象对象之间的事务JAVA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有人可以帮助我,我有2个用户和地址都具有addNewUser()和addNewAdress(),此方法使用preparesatement进行事务,但是我不知道如何加入objets,因为当我添加新用户时,我需要添加具有用户ID的新adrees.

i hope somebody can help me with this, i have 2 clases User and Adressboth 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!

推荐答案

您不必提交事务即可获取插入ID. (关于如何获取它的答案,请参见此处).然后,您只需在工作单元末尾提交一次事务即可.我建议不要将事务管理放在该对象的范围之外,并且不要在任何这些对象(用户或地址)中提交事务.这将限制它们的范围,并使代码变得更整洁,并且事务代码(commit-rollback-exception处理)将独立且可重用.

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.

这篇关于面向对象对象之间的事务JAVA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 16:21