2015-09-02 20 views
0

在我的webapp中,使用了Spring事務和Hibernate會話API。 請參閱下面的我的服務和DAO類和用法;Spring&Hibernate - 獲取persisteed對象狀態已更改

BizCustomerService

@Service 
@Transactional(propagation = Propagation.REQUIRED) 
public class BizCustomerService { 

    @Autowired 
    CustomerService customerService; 

    public void createCustomer(Customer cus) { 
     //some business logic codes here 

     customerService.createCustomer(cus); 

     //***the problem is here, changing the state of 'cus' object 
     //it is necessary code according to business logic 
     if (<some-check-meet>) 
      cus.setWebAccount(new WebAccount("something", "something")); 
    } 
} 

的CustomerService

@Service 
@Transactional(propagation = Propagation.REQUIRED) 
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS) 
public class CustomerService { 

    @Autowired 
    CustomerDAO customerDao; 

    public Long createCustomer(Customer cus) { 
     //some code goes here 
     customerDao.save(); 
    } 
} 

CustomerDAO

@Repository 
public class CustomerDAO { 

    @Autowired 
    private SessionFactory sessionFactory; 

    private Session getSession() { 
     return sessionFactory.getCurrentSession(); 
    } 

    public Long save(Customer customer) { 
     //* the old code 
     //return (Long) getSession().save(customer); 

     //[START] new code to change 
     Long id = (Long) getSession().save(customer); 

     //1. here using 'customer' object need to do other DB insert/update table functions 
     //2. if those operation are failed or success, as usual, they are under a transaction boundary 
     //3. lets say example private method 
     doSomeInsertUpdate(customer); 
     //[END] new code to change 

     return id; 
    } 

    //do other insert/update operations 
    private void doSomeInsertUpdate(customer) { 

     //when check webAccount, it is NULL 
     if (customer.getWebAccount() != null) { 
       //to do something 
     } 

    } 
} 

客戶

@Entity 
@Table(name = "CUSTOMER") 
public class Customer { 
    //other relationships and fields 

    @OneToOne(fetch = FetchType.LAZY, mappedBy = "customer") 
    @Cascade({CascadeType.ALL}) 
    public WebAccount getWebAccount() { 
      return this.webAccount; 
    } 
} 

在上面的代碼,顧客在BizCustomerService創建隨後可改變的相關WebAccount狀態通過DAO持續之後。並且當交易被提交時,新的客戶和相關的對象被持久化到DB。我知道這很正常。

問題是;在CustomerDAO#save() >> doSomeInsertUpdate()方法中,'webAccount'爲NULL,並且該值當時尚未設置。

編輯:左一提的是,它是限制,不希望在BizCustomerServiceCustomerService更改代碼,因爲可以有很多的調用到DAO方法可以影響很多。所以只想在DAO級別進行更改。

所以我的問題是如何訪問doSomeInsertUpdate()方法中的WebAccount對象?任何Hibernate使用需要?

在此先感謝!

+0

您是否已經在您的doSomeInsertUpdate方法中訪問WebAccount對象?如你的代碼所見'if(customer.getWebAccount()!= null)'?或者我想念什麼? –

回答

0

不知道你在期待什麼,但我認爲這裏沒有魔法。如果您希望Web帳戶爲!= null,則必須明確製作一個並將其保存到數據庫。

WebAccount wb = new WebAccount(); 
getSession().save(wb); 
customer.setWebAccount(wb);