1) O documento discute conceitos de transações em EJB, incluindo definição, comandos, participantes e demarcação de transações.
2) São descritos os tipos de demarcação de transações CMT e BMT e como especificar atributos de transação.
3) As transações distribuídas são suportadas através do padrão EJB, permitindo atualizações em múltiplos bancos de dados e servers.
2. Transações
Definição:
◦ Unidade atômica de trabalho
◦ Pode ser formada por várias operações chamadas a
partir de vários objetos
O padrão EJB suporta transações distribuídas
◦ Entre vários application servers e vários bancos de
dados
As transações são realizadas em nível de
beans e não em nível de tabelas de bancos
de dados
| 2
3. Comandos de transações
BEGIN
◦ Inicia uma nova transação
COMMIT
◦ Confirma as operações/mudanças realizadas na
transação
ROLLBACK
◦ Desfaz as operações/mudanças realizadas na
transação
| 3
4. Participantes de transações
Recursos com estado transacional
◦ Exemplo: Conexão de banco de dados
Resource Manager
◦ Exemplo: Driver JDBC 2.0
Servidor de aplicações
Gerenciador de transações
◦ Controla o estado da transação
◦ Controla todos os resource managers
envolvidos em uma transação
| 4
5. Contexto transacional
Um contexto transacional:
◦ Representa a transação compartilhada pelos
objetos transacionais participantes
◦ É propagado automaticamente para objetos
transacionais na medida em que são usados
◦ Permite a sincronização dos objetos
transacionais envolvidos no momento de
commit ou rollback
| 5
6. Transações Distribuídas
Uma transação distribuída é associada a um
thread.
A transação fica ativa enquanto o thread realiza chamadas
a objetos, possivelmente em vários servidores
O contexto transacional é propagado pelo
container, para cada chamada de método
O padrão EJB obriga que a propagação de
transações seja transparente para o bean
(propagação implícita)
Transações distribuídas são suportadas por two-
phase commits
| 6
7. Transações Distribuídas
Atualizações em
múltiplos bancos
de dados
• Atualizações em
múltiplos bancos de
dados através de
vários application
servers
| 7
8. Níveis de isolamento
Níveis de isolamento determinam o nível de
acesso a um objeto envolvido em uma transação
por um thread em outra transação
Cada resource manager pode usar níveis de
isolamento diferentes
Todos os acessos dentro de uma transação são
feitos com os mesmos níveis de isolamento
Conflitos em níveis de isolamento devem ser
evitados quando múltiplos EJBs fazem acesso ao
mesmo resource manager
| 8
9. Demarcação de transações
A demarcação de transações envolve
◦ O início de uma transação
◦ A confirmação (commit) de uma transação
◦ O cancelamento (rollback) de uma transação
Dois tipos de demarcação de transações
◦ Container-managed transaction demarcation
(CMT)
◦ Bean-managed transaction demarcation
(BMT)
| 9
10. Demarcação implícita x explícita
Cliente EJB
Implícito,
método de negócio usando
especificaçã
o declarativa
Cada método é
uma transação
(implícito)
User
Cliente Transaction EJB
begin()
método de negócio
commit()
Demarcação
explícita
(pelo cliente) O cliente determina os
limites da transação
| 10
11. Demarcação BMT
Apenas session beans podem usar BMT
O bean possui controle total sobre a
transação
É necessário usar
javax.transaction.UserTransaction
O tipo de demarcação de transações
(CMT ou BMT) é indicado no
deployment descriptor
| 11
12. Demarcação de transações BMT
User
Cliente Session Bean Transaction EJB
método de negócio
begin()
método de negócio
Demarcação commit()
gerenciada pelo
bean
O Session Bean
determina os limites da
transação
| 12
13. Demarcação CMT
A declaração do uso de CMT é feita no
Deployment Descriptor
Quando CMT é declarado, fica proibido o uso
de outro tipo de demarcação de transações
É proibido o controle de transações usando:
◦ java.sql.Connection
◦ javax.transaction.UserTransaction
| 13
14. Container-managed transactions
Com CMT, o container gerencia as
transações de forma transparente
CMT pode ser usado para session beans e
entity beans
O bean não tem acesso às transações
◦ Qualquer tentativa de controlar transações
explicitamente causa uma exceção
| 14
15. Container-managed transactions
Deve ser indicado no Deployment
Descriptor o tipo de gerenciamento de
transações CMT
São especificados atributos de transações
(transaction attributes) para cada método
| 15
16. Atributos de transação
Atributos de transações definem os
requisitos transacionais para o método
Seis tipos de atributos
◦ Required
◦ RequiresNew
◦ Supports
◦ NotSupported
◦ Mandatory
◦ Never
| 16
17. Atributos Required
Usa a transação existente
Se não houver transação, inicia nova transação; termina a
nova transação no final de sua execução
Cliente T1 Container T1 Bean T1
Cliente Nenhuma Container T1 Bean T1
| 17
18. Atributos RequiresNew
Sempre inicia uma nova transação; encerra a transação
ao final
Cliente T1 Container T2 Bean T2
Cliente Nenhuma Container T1 Bean T1
| 18
19. Atributo Supports
Não inicia uma nova transação
A associação transacional existente não é suspensa
Cliente T1 Container T1 Bean T1
Cliente Nenhuma Container Nenhuma Bean Nenhuma
| 19
20. Atributo NotSupported
Não inicia uma nova transação
A associação transacional existente é suspensa
Cliente T1 Container Nenhuma Bean Nenhuma
Cliente Nenhuma Container Nenhuma Nenhuma
Bean
| 20
21. Atributo Mandatory
Deve ser chamado de dentro de uma transação; caso
contrário levanta exceção
Cliente T1 Container T1 Bean T1
Cliente Container Bean
Nenhuma
Transaction
RequiredException
| 21
22. Atributo Never
Chamar um método desse tipo com uma transação em
andamento gera uma exceção
RemoteException
Cliente T1 Container
Container Bean
Cliente Nenhuma Container Nenhuma Bean Nenhuma
| 22
23. Transações CMT
A demarcação de transação pode ser
feita através de Anotations (EJB3);
| 23
24. Transações CMT
A demarcação de transação também
pode ser feita através do arquivo ejb-
jar.xml (EJB2);
| 24
25. Rollback CMT
Da mesma forma que o commit o
comando rollback é chamado
automaticamente;
É executado quando uma exceção do
tipo SystemException é levantada;
◦ Herdadas de RuntimeException;
Exceções de aplicação (Checked) não
causam o rollback na transação;
◦ Herdadas de Exception
| 25
26. Rollback Only
...
@Resource SessionContext ctx;
Public void inserirPaciente(Paciente p) throws
PacienteJaExistenteException {
...//<regras de negócio>
}catch(PacienteJaExistenteException ex) {
ejbContext.setRollbackOnly();
throw ex;
}
Para que as exceções de aplicação causem o rollback é
necessário que o programador identifique a mesma e chame
manualmente o método setRollbackOnly();
O bean usa esses métodos para marcar uma transação para
rollback, ou para obter informações sobre o estado de uma
transação, não para controlar a transação
| 26
27. Rollback CMT
Desta forma, o programador deve tomar
cuidado com as exceções de aplicação;
◦ Ele deve manualmente dar rollback utilizando
EJBContext,
◦ Ou marcar que essas exceções causem rollback
automaticamente via annotation;
O exemplo anterior a exceção
PacienteJaExixtenteException realiza
herança da classe Exception;
◦ Capturamos a exceção, realizamos os rollback e
relançamos a exceção;
| 27
28. Rollback Only
Package br.fucapi.controlemedico;
@ApplicationException(rollback=true) ;
Public class PacienteJaExistenteException extends Exception {
public void PacienteJaExistenteException(String pNomePac){
...
}
}
• Marcamos a classe PacienteJaExistenteException com a annotation
@ApplicationException;
• O container EJB irá dar rollback automaticamente quando esta
exceção for levantada dentro de um método de negócio;
| 28
29. Transações e Usuário Final
O conceito de transação para o Usuário
Final (UF) é um pouco diferente do de
banco de dados;
A visão de transação para o UF está ligado
as operações que ele realiza na interface
gráfica;
Um conjunto de passos em uma interface
gráfica é encarada como apenas uma
transação para o UF
◦ Esta pode representar mais de uma transação de
BD;
| 29
30. Transações e Ambientes Multi-
usuários
As transações de banco de dado devem
ocorrer em um curto espaço de tempo
dentro dos métodos de negócio;
O acesso concorrente em um registro de
tabela está protegido por uma transação
apenas dentro dos métodos de negócio
com demarcação;
| 30
31. Transações e Ambientes Multi-
usuários
O tempo de uma transação para o usuário segue os seguintes passos:
◦ Inicia no momento que o mesmo avistou a informação na UI,
◦ passando pelo momento de confirmação da operação (através de um
botão, Link etc)
◦ e finalizando com a tela de sucesso;
O tempo decorrido é bem maior;
Visão Processamento
EJB
Tela sucesso
da informação
Transação de BD
Transação para o Usuário
| 31
32. Transações e Ambientes Multi-
usuários WEB
O acesso/modificação concorrente ao
informação por mais de um usuário põe em
risco a integridade do BD;
T1 (1-5 seg) T1 (06-07 seg)
Edição Pessoa Processamento
Usuário B Cod 143 EJB
Tela sucesso
T1 (1-10 seg) T1 (11-12 seg)
Edição Pessoa Processamento
Usuário A Cod 143 EJB
Tela sucesso
| 32
33. Transações Long Running
Damos o nome de long running transactions (LRT)
as transações que demoram mais que o normal
para completar a operação completa;
Devemos evitar as LRTs:
◦ Consomem muitos recursos computacionais;
◦ Podem gerar dead locks;
◦ Podem segurar recursos por muito tempo
deixando as aplicações lentas;
Devemos transformá-las em transações menores
quando possível;
| 33
34. Transações Long Running
Não existem tempo ideal de timout para
transações de um sistema;
◦ O arquiteto deve observar a aplicação e verificar a
média de tempo de uma transação que depende da
aplicação, do hardware, da memória e da rede
disponíveis;
As LRTs podem ser limitadas na configuração
do driver JDBC;
Uma transação que não oferece problemas
hoje, pode a vir se tornar uma LRT amanhã;
| 34
Notas do Editor
Qual o significado de sincronização?
Two-phase commit Two-phase commit is a protocol complying to the XA interface. It ensures that the result of a transaction is consistent across all resource managers participating in the transaction. It is used only in distributed transactions. The protocol operates in distinct phases to ultimately commit or abort a transaction. Phase one evaluates the status of each resource manager. The transaction manager checks with each local resource manager, whether they are ready to commit the transaction. Each resource manager responds that they are ready or not. A transaction can commit only when all participating resource managers agree during this phase one. This phase is called the prepare phase. Phase two concludes the transaction. Based on the response from each resource manager, the transaction manager instructs all resource managers to commit the transaction if all agree or to roll back the transaction if at least one disagrees. This phase is called commit phase.
Foi tirado pelo motivo de pouco tempo para ministrar as aulas. Este assunto foi considerado irrelevante, pois iremos focar na aula prática. Se o mesmo for utiliszado no futuro é bom dar uma olhada no wikpedia que contem vários exemplos sobre o assunto TRANSACTION_READ_UNCOMMITTED Dirty reads, non-repeatable reads and phantom reads can occur. This level allows a row changed by one transaction to be read by another transaction before any changes in that row have been committed (a &quot;dirty read&quot;). If any of the changes are rolled back, the second transaction will have retrieved an invalid row. TRANSACTION_READ_COMMITTED Dirty reads are prevented; non-repeatable reads and phantom reads can occur. This level only prohibits a transaction from reading a row with uncommitted changes in it. TRANSACTION_REPEATABLE_READ Dirty reads and non-repeatable reads are prevented; phantom reads can occur. This level prohibits a transaction from reading a row with uncommitted changes in it, and it also prohibits the situation where one transaction reads a row, a second transaction alters the row, and the first transaction rereads the row, getting different values the second time (a &quot;non-repeatable read&quot;). TRANSACTION_SERIALIZABLE Dirty reads, non-repeatable reads and phantom reads are prevented. This level includes the prohibitions in TRANSACTION_REPEATABLE_READ and further prohibits the situation where one transaction reads all rows that satisfy a WHERE condition, a second transaction inserts a row that satisfies that WHERE condition, and the first transaction rereads for the same condition, retrieving the additional &quot;phantom&quot; row in the second read.
Foi tirado pelo motivo de pouco tempo para ministrar as aulas. Este assunto foi considerado irrelevante, pois iremos focar na aula prática. Se o mesmo for utiliszado no futuro é bom dar uma olhada no wikpedia que contem vários exemplos sobre o assunto TRANSACTION_READ_UNCOMMITTED Dirty reads, non-repeatable reads and phantom reads can occur. This level allows a row changed by one transaction to be read by another transaction before any changes in that row have been committed (a &quot;dirty read&quot;). If any of the changes are rolled back, the second transaction will have retrieved an invalid row. TRANSACTION_READ_COMMITTED Dirty reads are prevented; non-repeatable reads and phantom reads can occur. This level only prohibits a transaction from reading a row with uncommitted changes in it. TRANSACTION_REPEATABLE_READ Dirty reads and non-repeatable reads are prevented; phantom reads can occur. This level prohibits a transaction from reading a row with uncommitted changes in it, and it also prohibits the situation where one transaction reads a row, a second transaction alters the row, and the first transaction rereads the row, getting different values the second time (a &quot;non-repeatable read&quot;). TRANSACTION_SERIALIZABLE Dirty reads, non-repeatable reads and phantom reads are prevented. This level includes the prohibitions in TRANSACTION_REPEATABLE_READ and further prohibits the situation where one transaction reads all rows that satisfy a WHERE condition, a second transaction inserts a row that satisfies that WHERE condition, and the first transaction rereads for the same condition, retrieving the additional &quot;phantom&quot; row in the second read.
Foi tirado pelo motivo de pouco tempo para ministrar as aulas. Este assunto foi considerado irrelevante, pois iremos focar na aula prática. Se o mesmo for utiliszado no futuro é bom dar uma olhada no wikpedia que contem vários exemplos sobre o assunto TRANSACTION_READ_UNCOMMITTED Dirty reads, non-repeatable reads and phantom reads can occur. This level allows a row changed by one transaction to be read by another transaction before any changes in that row have been committed (a &quot;dirty read&quot;). If any of the changes are rolled back, the second transaction will have retrieved an invalid row. TRANSACTION_READ_COMMITTED Dirty reads are prevented; non-repeatable reads and phantom reads can occur. This level only prohibits a transaction from reading a row with uncommitted changes in it. TRANSACTION_REPEATABLE_READ Dirty reads and non-repeatable reads are prevented; phantom reads can occur. This level prohibits a transaction from reading a row with uncommitted changes in it, and it also prohibits the situation where one transaction reads a row, a second transaction alters the row, and the first transaction rereads the row, getting different values the second time (a &quot;non-repeatable read&quot;). TRANSACTION_SERIALIZABLE Dirty reads, non-repeatable reads and phantom reads are prevented. This level includes the prohibitions in TRANSACTION_REPEATABLE_READ and further prohibits the situation where one transaction reads all rows that satisfy a WHERE condition, a second transaction inserts a row that satisfies that WHERE condition, and the first transaction rereads for the same condition, retrieving the additional &quot;phantom&quot; row in the second read.
Foi tirado pelo motivo de pouco tempo para ministrar as aulas. Este assunto foi considerado irrelevante, pois iremos focar na aula prática. Se o mesmo for utiliszado no futuro é bom dar uma olhada no wikpedia que contem vários exemplos sobre o assunto TRANSACTION_READ_UNCOMMITTED Dirty reads, non-repeatable reads and phantom reads can occur. This level allows a row changed by one transaction to be read by another transaction before any changes in that row have been committed (a &quot;dirty read&quot;). If any of the changes are rolled back, the second transaction will have retrieved an invalid row. TRANSACTION_READ_COMMITTED Dirty reads are prevented; non-repeatable reads and phantom reads can occur. This level only prohibits a transaction from reading a row with uncommitted changes in it. TRANSACTION_REPEATABLE_READ Dirty reads and non-repeatable reads are prevented; phantom reads can occur. This level prohibits a transaction from reading a row with uncommitted changes in it, and it also prohibits the situation where one transaction reads a row, a second transaction alters the row, and the first transaction rereads the row, getting different values the second time (a &quot;non-repeatable read&quot;). TRANSACTION_SERIALIZABLE Dirty reads, non-repeatable reads and phantom reads are prevented. This level includes the prohibitions in TRANSACTION_REPEATABLE_READ and further prohibits the situation where one transaction reads all rows that satisfy a WHERE condition, a second transaction inserts a row that satisfies that WHERE condition, and the first transaction rereads for the same condition, retrieving the additional &quot;phantom&quot; row in the second read.
Foi tirado pelo motivo de pouco tempo para ministrar as aulas. Este assunto foi considerado irrelevante, pois iremos focar na aula prática. Se o mesmo for utiliszado no futuro é bom dar uma olhada no wikpedia que contem vários exemplos sobre o assunto TRANSACTION_READ_UNCOMMITTED Dirty reads, non-repeatable reads and phantom reads can occur. This level allows a row changed by one transaction to be read by another transaction before any changes in that row have been committed (a &quot;dirty read&quot;). If any of the changes are rolled back, the second transaction will have retrieved an invalid row. TRANSACTION_READ_COMMITTED Dirty reads are prevented; non-repeatable reads and phantom reads can occur. This level only prohibits a transaction from reading a row with uncommitted changes in it. TRANSACTION_REPEATABLE_READ Dirty reads and non-repeatable reads are prevented; phantom reads can occur. This level prohibits a transaction from reading a row with uncommitted changes in it, and it also prohibits the situation where one transaction reads a row, a second transaction alters the row, and the first transaction rereads the row, getting different values the second time (a &quot;non-repeatable read&quot;). TRANSACTION_SERIALIZABLE Dirty reads, non-repeatable reads and phantom reads are prevented. This level includes the prohibitions in TRANSACTION_REPEATABLE_READ and further prohibits the situation where one transaction reads all rows that satisfy a WHERE condition, a second transaction inserts a row that satisfies that WHERE condition, and the first transaction rereads for the same condition, retrieving the additional &quot;phantom&quot; row in the second read.
Foi tirado pelo motivo de pouco tempo para ministrar as aulas. Este assunto foi considerado irrelevante, pois iremos focar na aula prática. Se o mesmo for utiliszado no futuro é bom dar uma olhada no wikpedia que contem vários exemplos sobre o assunto TRANSACTION_READ_UNCOMMITTED Dirty reads, non-repeatable reads and phantom reads can occur. This level allows a row changed by one transaction to be read by another transaction before any changes in that row have been committed (a &quot;dirty read&quot;). If any of the changes are rolled back, the second transaction will have retrieved an invalid row. TRANSACTION_READ_COMMITTED Dirty reads are prevented; non-repeatable reads and phantom reads can occur. This level only prohibits a transaction from reading a row with uncommitted changes in it. TRANSACTION_REPEATABLE_READ Dirty reads and non-repeatable reads are prevented; phantom reads can occur. This level prohibits a transaction from reading a row with uncommitted changes in it, and it also prohibits the situation where one transaction reads a row, a second transaction alters the row, and the first transaction rereads the row, getting different values the second time (a &quot;non-repeatable read&quot;). TRANSACTION_SERIALIZABLE Dirty reads, non-repeatable reads and phantom reads are prevented. This level includes the prohibitions in TRANSACTION_REPEATABLE_READ and further prohibits the situation where one transaction reads all rows that satisfy a WHERE condition, a second transaction inserts a row that satisfies that WHERE condition, and the first transaction rereads for the same condition, retrieving the additional &quot;phantom&quot; row in the second read.
Foi tirado pelo motivo de pouco tempo para ministrar as aulas. Este assunto foi considerado irrelevante, pois iremos focar na aula prática. Se o mesmo for utiliszado no futuro é bom dar uma olhada no wikpedia que contem vários exemplos sobre o assunto TRANSACTION_READ_UNCOMMITTED Dirty reads, non-repeatable reads and phantom reads can occur. This level allows a row changed by one transaction to be read by another transaction before any changes in that row have been committed (a &quot;dirty read&quot;). If any of the changes are rolled back, the second transaction will have retrieved an invalid row. TRANSACTION_READ_COMMITTED Dirty reads are prevented; non-repeatable reads and phantom reads can occur. This level only prohibits a transaction from reading a row with uncommitted changes in it. TRANSACTION_REPEATABLE_READ Dirty reads and non-repeatable reads are prevented; phantom reads can occur. This level prohibits a transaction from reading a row with uncommitted changes in it, and it also prohibits the situation where one transaction reads a row, a second transaction alters the row, and the first transaction rereads the row, getting different values the second time (a &quot;non-repeatable read&quot;). TRANSACTION_SERIALIZABLE Dirty reads, non-repeatable reads and phantom reads are prevented. This level includes the prohibitions in TRANSACTION_REPEATABLE_READ and further prohibits the situation where one transaction reads all rows that satisfy a WHERE condition, a second transaction inserts a row that satisfies that WHERE condition, and the first transaction rereads for the same condition, retrieving the additional &quot;phantom&quot; row in the second read.