i need to insert data in two diferents tables, so i don't understand how interact the two objects for insert the data. i have two classes class a and class b both have two methods addA and addb the class a is composed by a classB object so in my method addA i create a new object of classB and call the addB method, IN both methods i use a connection and a preparedStatement with commit, but i need to do a rollback if the method addB doesen't work, someone could give me an example of this?, thanks!
EXAMPLE OF CLASS A
class a{
int id;
String name;
int age;
a(String name, int age){
this.name= name;
this.age=age;
}
public boolean addA( ) throws Exception {
conecctions.Conn.getConnection();
Statement stmt = null;
Connection conection = conecctions.Conn.connection;
Boolean result = false;
try {
conection.setAutoCommit(false);
stmt = conection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String addnew= "insert into table_a values (?,?)"
PreparedStatement prepared1= conection.prepareStatement(addnew);
prepared1.setString(1, "name");
prepared2.setInt(2, 25);
prepared1.executeUpdate();
ResultSet keys = prepared1.getGeneratedKeys();
int lastKey = 1;
while (keys.next()) {
lastKey = keys.getInt(1);
}
this.id=lastKey;
result = true;
conection.commit();
b newB= new b(this.id, this.age);
newb.addB();
catch (Exception e2) {
if (conection != null) {
try {
System.out.println("rollback");
} catch (Exception e1) {
e1.printStackTrace();
}
}
e2.printStackTrace();
} finally {
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
}// nothing we can do
try {
if (conection != null)
conection.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
return result;
}
EXAMPLE OF CLASS B
class b{
int id;
int idA;
int ageA;
b(String idA, int ageA){
this.idA= idA;
this.ageA=ageA;
}
public boolean addB( ) throws Exception {
conecctions.Conn.getConnection();
Statement stmt = null;
Connection conection = conecctions.Conn.connection;
Boolean result = false;
try {
conection.setAutoCommit(false);
stmt = conection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String addnew= "insert into table_b values (?,?)"
PreparedStatement prepared2= conection.prepareStatement(addnew);
prepared2.setInt(1, a_id);
prepared2.setInt(2, a_age);
prepared2.executeUpdate();
result = true;
conection.commit();
catch (Exception e2) {
if (conection != null) {
try {
System.out.println("rollback");
} catch (Exception e1) {
e1.printStackTrace();
}
}
e2.printStackTrace();
} finally {
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
}// nothing we can do
try {
if (conection != null)
conection.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
return result;
}
its just a example