Database¶
Topics
Summary¶
Following 2 types of persistence frameworks can be used in TERASOLUNA Global Framework.In this section database programming method using each of the ones below will be described.
- Spring Data JPA
- MyBatis(2.3)
Programming Method¶
Each database programming method is desribed in the pages below.
[Entity Class Generation] and [Transaction Control] described below have common contents with the programming methods stated above.
Entity Class Generation¶
Entity class is a class @Entity annotation is annotated. Eclipse DTP has afunction to connect to the database and generate entity class from the selected table.Please see the below for details.
Transaction Control¶
Setting of transaction control is made by adding @Transactional annotationto the arbitrary class method.For example, if the transaction boundary is to be set for each class of service class,@Transactional annotation is added to the class as follows.import org.springframework.transaction.annotation.Transactional; ... @Service @Transactional public class HogeServiceImpl implements HogeService { ...Note
@Transactional can be set for each method.
Defining Rollback Exceptions¶
If an exception occurs inside the transaction boundary,only the exception that inherits RuntimeException will be rolled back as default.In case rollbackan exception is additionally defined, rollbackFor attribute isadded to @Transactional as follows.@Transactional(rollbackFor=java.lang.Exception.class)Note
On the other hand, you can set an exception that does not roll back by setting the noRollbackFor attribute.Please refer to http://docs.spring.io/spring/docs/3.2.4.RELEASE/spring-framework-reference/html/transaction.html for detail.
Explicit Transaction¶
In case transaction process is stated directly into the source code without using the annotation,it should be coded as follows.import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; ... @Autowired PlatformTransactionManager transactionManager;// ① ... @Override public void store(MyCompany entity) { DefaultTransactionDefinition def = new DefaultTransactionDefinition(); // ② TransactionStatus status = transactionManager.getTransaction(def); // ③ try { //Business Logic } catch (RuntimeException e) { transactionManager.rollback(status); // ④ throw e; } transactionManager.commit(status); // ⑤
PlatformTransactionManager is field defined.Bean is generated by @Autowired. Transaction definition information is set.DefaultTransactionDefinition class is generated. Transaction is started by transactionManager#getTransaction. In case roll back is made, transactionManager#rollback is used. In case commit is made, transactionManager#commit is used.