Spring Core
Spring Professional Certification
Spring Professional Certification
-
- 1 / 227
-
Lernkarten
generic query: multiple rows
queryForList(..)
=> when expecting multiple rows
=> returns list of maps of [Column Name | Field Value]
pairs
List {
0 - Map {ID=1, FIRST_NAME="John", NAME="Smith"}
1 - Map {ID=2, FIRST_NAME="Jane", NAME="Miller"}
2 - Map {ID=3, FIRST_NAME="Joe", NAME="Wells"}
}
domain object queries:
3 callback interfaces
- RowMapper
- RowCallbackHandler
- ResultSetExtractor
domain object query: single row
public Person getPerson(int id) {
return jdbcTemplate.queryForObject("select ...
where id = ?", new PersonMapper(), id);
}
NOTE: no need to cast return type of queryForObject()!!!
class PersonMapper implements RowMapper<Person> {
public Person mapRow(ResultSet rs, int i)
throws SQLException
{
return new Person(rs.getString("first_name"),
rs.getString("last_name"));
}
}
domain object query: multiple rows
public List<Person> getAllPersons() {
return jdbcTemplate.query("select ... from PERSON",
new PersonMapper());
}
NOTE: no need to cast return type of query(..)
NOTE: same row mapper can be used as for single row
domain object query: RowMapper
=> maps single row of a ResultSet to an object
public interface RowMapper<T> {
T mapRow(ResultSet rs, int rowNum)
throws SQLException;
}
domain object query: RowCallbackHandler
=> when there is no return object
(streaming rows to a file, converting rows to XML, etc.)
public interface RowCallbackHandler {
void processRow(ResultSet rs) throws SQLException;
}
domain object query: ResultSetExtractor
=> processes an entire ResultSet at once
public interface ResultSetExtractor<T> {
T extractData(ResultSet rs) throws SQLException,
DataAccessException;
}
inserting a new row
public int insertPerson(Person person) {
return jdbcTemplate.update(
"insert into PERSON (first_name, last_name)" +
"values (?, ?)",
person.getFirstName(),
person.getLastName());
}
updating an existing row
public int updateLastName(Person person) {
return jdbcTemplate.update(
"update PERSON set LAST_NAME=?" +
"where id=?",
person.getLastName(),
person.getId());
}
ACID Principles
Atomic
= each unit of work is an all-or-nothing operation
= commit, rollback
Consistent
= database integrity constraints are never violated
= PK, FK, NOTNULL, UNIQUE, DEFAULT
Isolated
= isolating transactions from each other (isolation levels)
= READ_UNCOMMITTED, READ_COMMITTED, ...
Durable
= committed changes are permanent
Base interface for Spring transaction management and available implementations?
PlatformTransactionManager
=> DataSourceTransactionManager
=> HibernateTransactionManager
=> JpaTransactionManager (Java Persistence API)
=> JtaTransactionManager (Java Transaction API)
=> WebLogicJtaTransactionManager
=> WebSphereUowTransactionManager
=> ...
2 types of transaction management
- global transaction management
=> several data sources are involved
=> JTA: Java Transaction API - local transaction management
=> one local data source involved
declarative transactions with spring: 2 steps
- define a TransactionManager
- declare transactional methods
define transaction manager
<tx:annotation-driven/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
declare transactional methods
public class ExampleClass
{
@Transactional
public Confirmation rewardAccountFor(Example ex) {
// atomic unit-of-work
}
}
@Transactional: What happens exactly?
3 steps
- transaction started before entering method
- commit at the end of method
- rollback if method throws RuntimeException
NOTE: no rollback with Checked Exceptions!
NOTE: only applicable on public methods!
declare transactional class
@Transactional applies to ALL methods declared by the interface!
@Transactional combined at class and method levels:
characteristics & rules
class level = default settings for all methods
method level = overrides default settings
XML transaction declaration
<aop:config>
<aop:pointcut id="foo" expression="execution(...)" />
<aop:advisor pointcut-ref="foo" advice-ref="txAdvice" />
</aop:config>
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="get*" read-only="true" timeout="10"/>
<tx:method name="*" timeout="30"/>
</tx:attributes>
</tx:advice>
4 isolation levels
- READ_UNCOMMITTED
- READ_COMMITTED
- REPEATABLE_READ
- SERIALIZABLE
NOTE: some DBMS do not support all levels!
Dirty Reads
READ_UNCOMMITTED
- lowest isolation level
- current transaction can see the results of other uncommitted unit-of-work
@Transactional(isolation=isolation.READ_UNCOMMITTED)
Default isolation level
READ_COMMITTED
- only committed information can be accessed
- default strategy for most databases
@Transactional(isolation=isolation.READ_COMMITTED)
highest two isolation levels
REPEATABLE_READ
- if row is read twice within same transaction, result will always be the same
- locks not only writing but also reading on row level
SERIALIZABLE
- locks writing and reading on table level
Transaction propagation: 7 levels
- REQUIRED
- REQUIRES_NEW
- NESTED
- SUPPORTS
- NOT_SUPPORTED
- MANDATORY
- NEVER
Transaction propagation: configuration example
@Transactional(propagation=Propagation.REQUIRED)
REQUIRED propagation:
characteristics
- default value
- execute within a current transaction
- create a new one if none exists
REQUIRES_NEW propagation:
characteristics
- create a new transaction
- suspend a current transaction if one exists
Rollback rules
transaction is rolled back by default if a RuntimeException has been thrown
NOTE: any kind of RuntimeException causes rollback (e.g. DataAccessException, HibernateException, ...)
Override default rollback settings
@Transactional(rollbackFor=MyCheckedException.class)
@Transactional(noRollbackFor=JmxException.class)
NOTE: Severel Exception Types are also allowed
noRollbackFor={JmxException.class, MyException.class}
@Test @Transactional
public void testRewardAccountFor() { ... }
=> What happens?
test method runs in a transaction that will be rolled back afterwards
=> no need to clean up database after testing!
@Transactional in Unit Test:
5 annotations
- @TransactionConfiguration
- @Before
- @BerforeTransaction
- @After
- @AfterTransaction
@TransactionConfiguration
example & characteristics
@TransactionConfiguration(defaultRollback=false, transactionManager="txMgr")
@Transactional
public class RewardNetworkTest {
@Test
@Rollback(true) => overrides class settings
public void testRewardAccountFor() { ... }
}
NOTE: If id of transaction manager is equal to transactionManager, it does not have to be specified within @TransactionConfiguration
@Before vs @BeforeTransaction
@After vs @AfterTransaction
@BeforeTransaction annotated methods
=> run before transaction is startet
@Before annotated methods
=> run within transaction but before test method
NOTE: @After and @AfterTransaction work the same way
Hibernate SessionFactory:
characteristics
thread-safe, shareable object that represents a single data source
- provides access to a transactional session
NOTE: ideal candidate for a singleton spring bean!
Hibernate Session:
characteristics
stateful object representing a unit-of-work
- manages persistent objects within unit-of-work
- acts as transaction-scoped cache
- often corresponds at a higher-level to a JDBC connection
Hibernate Mapping:
- What is the mapping for?
- How can the mapping be defined?
- Hibernate requires metadata for ...
= mapping classes to database tables
= mapping class properties to columns
- Metadata can be ...
= annotations or
= XML
Hibernate supports what kind of annotations?
JPA 2 annotation => javax.persistence.*
Hibernate Annotations:
What can be annotated?
Classes
=> applies to entire class (such as table properties)
Data-members
=> typically mapped to a column
NOTE: all data-members are accessed directly!
=> no accessors (getter/setters) needed
=> any accessors will not be used!
6 Hibernate Annotations
- @Entity
- @Table
- @Id
- @Column
- @Transient
- @Access
@Entity
- mandatory
- mark class as an entity