问题
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