2015-09-02 19 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);