事務(Transaction)
基於YMPv2.0的新特性,JDBC模組對資料庫事務的處理更加靈活,任何被類別物件管理器管理的物件都可以透過@Transaction註解來支援事務;
-
#@Transaction註解:
參數說明:
value:交易類型(參考JDBC交易類型),預設為JDBC.TRANSACTION.READ_COMMITTED ;
使用方式:
首先,需要資料庫事務支援的類別物件必須宣告@Transaction註解;
然後,在具體需要開啟事務處理的類別方法上新增@Transaction註解;
交易範例程式碼:
public interface IUserService { User doGetUser(String username, String pwd); boolean doLogin(String username, String pwd); } @Bean @Transaction public class UserService implements IUserService { public User doGetUser(final String username, final String pwd) { return JDBC.get().openSession(new ISessionExecutor<User>() { public User execute(ISession session) throws Exception { Cond _cond = Cond.create().eq("username").param(username).eq("pwd").param(pwd); return session.findFirst(EntitySQL.create(User.class), Where.create(_cond)); } }); } @Transaction public boolean doLogin(String username, String pwd) { User _user = doGetUser(username, pwd); if (_user != null) { _user.setLastLoginTime(System.currentTimeMillis()); _user.update(); // return true; } return false; } } @Bean public class TransDemo { @Inject private IUserService __userService; public boolean testTrans() { return __userService.doLogin("suninformation", "123456"); } public static void main(String[] args) throws Exception { YMP.get().init(); try { TransDemo _demo = YMP.get().getBean(TransDemo.class); _demo.testTrans(); } finally { YMP.get().destroy(); } } }