2012-03-27 58 views
0

如果我不使用休眠,我會使用的JdbcTemplate做一個數據庫調用,比如:如何在春天將事務設置在最低級別,類似於jdbc?

getJdbcTemplate().update("....") 

我過去這樣做,我沒寫任何XML bean配置或使用任何註釋進行交易。那麼我有什麼樣的交易範圍呢?

當前在使用hibernate的spring mvc時,我正在注入sessionManager(不使用HibernateDaoSupport),並且將@Transaction註釋放在我的服務類(使用Dao)上。

@Service 
@Transactional 
public class UserServiceImpl extends UserService { 

    @Autowired 
    UserService userService 

    @Override 
    public User getUser(int id) { 
     return userDao.get(User.class, id); 
    } 

} 

我的應用程序上下文XML有:

<context:component-scan base-package="com.myapp"/> 
<mvc:annotation-driven/> 

<bean id="dataSource" .../> 
<bean id="sessionFactory" .../> 

<tx:annotation-driven /> 

在這一點上我真的不在乎多單DB調用跨越更多的交易,我想事情要儘可能地快。

我該如何做到JdbcTemplate的功能?

什麼是交易的各種選擇,特別是尋找儘可能減少表/行鎖定的方法(我在猜測我想要的是什麼jdbcTemplate爲我開箱即用)。

回答

1

當您使用@Transactional不指定任何隔離級別,則默認爲默認底層數據存儲的隔離級別。對於jdbc和hibernate都是如此。

如果你想改變隔離級別,你將不得不在@Transactional提供隔離枚舉。

@Transactional(isolation=Isolation.???) 

其中???可以如所描述的水平here

  1. READ_COMMITTED
  2. READ_UNCOMMITTED
  3. REPEATABLE_READ
  4. SERIALIZABLE
  5. DEFAULT

要設置默認以外,你將不得不設置一個布爾值屬性的隔離級別 「allowCustomIsolationLevels」如果使用JTA事務,則將事務管理器設置爲true。

您可以參考春季文檔中關於設置的更多信息@Transactional

0

關於「儘可能快地」,我做了一個回答這種問題的使用無狀態會話:

Best way to insert a good amount of records in hibernate

基本上(我複製/粘貼我的代碼從我的答案在上面問題):

Session session = sessionFactory.openStatelessSession(); 
Transaction tx = session.beginTransaction(); 
for (int i=0; i<100000; i++) { 
    Item item = new Item(...); 
    session.save(item); 
    if (i % 100 == 0) { 
     session.flush(); 
     session.clear(); // not needed ? (see below) 
    } 
} 
tx.commit(); 
session.close(); 
相關問題