powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Java [игнор отключен] [закрыт для гостей] / Spring @Transactional & Rollback: великие танцы с бубном
3 сообщений из 3, страница 1 из 1
Spring @Transactional & Rollback: великие танцы с бубном
    #38827708
ozzmosis
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Народ, я в ступоре.

Есть таблица:
Код: java
1.
customer(id int primary key, name varchar(20)).



Какие заклинания в коде надо делать, чтобы вот это:
Код: java
1.
2.
3.
4.
insert into customer(1, "aaa");
insert into customer(2, "bbb");
insert into customer(3, "ccc");
insert into customer(1, "ddd");


- работало в одной транзакции и, ес-сно, откатилось ввиду попытки нарушения ПК ?

Про @Transactional и то, что по дефолту НЕ будут откатываться checked-исключения - знаю.
Вроде как надо добавить аннотацию @Service, но пробовал - бестолку.

Как в итоге завести эту шайтан-телегу ?

Вот мои потуги:
Customer.java :
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
package txtest;

public class Customer {
    private int id;
    private String name;

    public int getId() {  return id; }
    public void setId(int id) { this.id = id; }
    public String getName() {  return name; }
    public void setName(String name) { this.name = name; }
}



Вспомогат. класс для показа имени метода:
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
package txtest;
public class DbgInfo {
    public static void showStack() {
        StackTraceElement me = Thread.currentThread().getStackTrace()[2];
        System.out.println( "intro: "+me.getClassName() + ( me.getMethodName().equals("<init>") ? "()" : "."+me.getMethodName() ) );
    }
    public static String getStack() {
        StackTraceElement me = Thread.currentThread().getStackTrace()[2];
        return me.getClassName() + ( me.getMethodName().equals("<init>") ? "()" : "."+me.getMethodName() );
    }
}



CustomerDAO :
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
package txtest;

import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;

public class CustomerDAO {

    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void create(Customer aCust) {
        String queryCustomer = "insert into Customer (id, name) values (?,?)";

        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

        System.out.println(DbgInfo.getStack()+": trying ins into Customer: id="+aCust.getId()+", name="+aCust.getName() );

        jdbcTemplate.update(queryCustomer, new Object[] { aCust.getId(), aCust.getName() });

        System.out.println(DbgInfo.getStack()+": inserted OK");

    }
}



CustomerManager :
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
package txtest;

public class CustomerManager {

    private CustomerDAO custDAO;

    public void setCustDAO(CustomerDAO c) {
        this.custDAO = c;
    }

    public void createCustomer(Customer c) {
        custDAO.create(c);
    }

}



spring-xml :
Код: xml
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <tx:annotation-driven proxy-target-class="true"
        transaction-manager="transactionManager" />

    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

  <!-- Firebird DataSource -->

  <bean id="dataSource"
    class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="org.firebirdsql.jdbc.FBDriver" />
    <property name="url" value="jdbc:firebirdsql://localhost:3050/test" />
    <property name="username" value="sysdba" />
    <property name="password" value="masterke" />
    <property name="initialSize" value="3" />
    <property name="maxActive" value="10" />
  </bean>


    <bean id="custDAO" class="txtest.CustomerDAO">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <bean id="customerManager" class="txtest.CustomerManager">
        <property name="custDAO" ref="custDAO"></property>
    </bean>

</beans>



Тестилка :
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
package txtest;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;
//import org.springframework.stereotype.*;
//@Service("CustomerManager")
@Transactional(
  propagation=Propagation.REQUIRED,
  rollbackFor={
    Exception.class
   ,RuntimeException.class
  }
)
public class TxDmlMain {

    public static void main(String[] args) {
        new TxDmlMain().addSeveralCustomers();

    }


    private void addSeveralCustomers() {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
                "spring.xml");
        CustomerManager custMgr = ctx.getBean("customerManager", CustomerManager.class);

        custMgr.createCustomer(createCustInstance(1, "aaa"));
        custMgr.createCustomer(createCustInstance(2, "bbb"));
        custMgr.createCustomer(createCustInstance(3, "ccc"));
        custMgr.createCustomer(createCustInstance(1, "ddd")); // <<<<< must rollback all prev. statements and Tx <<<<<

        ctx.close();
    }

    private static Customer createCustInstance(int aId, String aName) {
        Customer customer = new Customer();
        customer.setId( aId );
        customer.setName( aName );
        return customer;
    }

}


Результат тестилки: после каждого insert'a добавляет commit.

Ткните носом, чего тут надо подправить ?

ЗЫ. Добавлять <property name="defaultAutoCommit" value="false" /> (к datasource) бестолку, ибо @Transactional. Но я попробовал и получил вообще "сюрприз": каждый вызов CustomerDAO.create(), в котором и происходят insert'ы, откатывается. И в таблице в итоге будет ноль записей :-)
...
Рейтинг: 0 / 0
Spring @Transactional & Rollback: великие танцы с бубном
    #38827790
Озверин
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
ozzmosis,

так public class TxDmlMain - как бе же не бин и аннотация не пашет же...
надо что нить типа .

TxDmlMainc tx = ctx.getBean("txDmlMain ", TxDmlMain .class);
делать же, чтобы все как задумано
...
Рейтинг: 0 / 0
Spring @Transactional & Rollback: великие танцы с бубном
    #38828032
ozzmosis
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Озверин,

да не помогает почему-то...

Вот что поменено:

spring.xml :
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <tx:annotation-driven proxy-target-class="true"
        transaction-manager="transactionManager" />

    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

  <!-- Firebird DataSource -->

  <bean id="dataSource"
    class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="org.firebirdsql.jdbc.FBDriver" />
    <property name="url" value="jdbc:firebirdsql://localhost:3050/t0" />
    <property name="username" value="sysdba" />
    <property name="password" value="masterke" />
    <property name="initialSize" value="3" />
    <property name="maxActive" value="10" />
  </bean>


    <bean id="custDAO" class="txtest.CustomerDAO">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <bean id="customerManager" class="txtest.CustomerManager">
        <property name="custDAO" ref="custDAO"></property>
    </bean>

    <bean id="txDmlMain" class="txtest.TxDmlMain">
    </bean>

</beans>


TxDmlMain.java:
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
package txtest;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.transaction.annotation.*;
@Transactional(
  propagation=Propagation.REQUIRED,
  rollbackFor={
    Exception.class
   ,RuntimeException.class
  }
)
public class TxDmlMain {

    public static void main(String[] args) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
        CustomerManager custMgr = ctx.getBean("customerManager", CustomerManager.class);
        TxDmlMain tm = ctx.getBean("txDmlMain", TxDmlMain.class);
        tm.addSeveralCustomers( custMgr );
        ctx.close();
    }

    private void addSeveralCustomers( CustomerManager custMgr ) {

        custMgr.createCustomer(createCustInstance(1, "aaa"));
        custMgr.createCustomer(createCustInstance(2, "bbb"));
        custMgr.createCustomer(createCustInstance(3, "ccc"));
        custMgr.createCustomer(createCustInstance(1, "ddd"));

    }

    private static Customer createCustInstance(int aId, String aName) {
        Customer customer = new Customer();
        customer.setId( aId );
        customer.setName( aName );
        return customer;
    }

}


- результат тот же: после каждого стейтмента в базу идёт commit. Т.е. транзакции на все 4 стейтмента - на самом деле нету.
...
Рейтинг: 0 / 0
3 сообщений из 3, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / Spring @Transactional & Rollback: великие танцы с бубном
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]