【发布时间】:2015-09-02 06:41:20
【问题描述】:
在我的 webapp 中,使用了 Spring 事务和 Hibernate 会话 API。 请在下面查看我的服务和 DAO 类和用法;
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"));
}
}
客户服务
@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();
}
}
客户DAO
@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中创建的,然后通过DAO持久化后可能会改变相关WebAccount的状态。当事务提交时,一个新的客户和相关的WebAccount 对象被持久化到数据库中。我知道这很正常。
问题是;在CustomerDAO#save() >> doSomeInsertUpdate() 方法中,'webAccount' 为 NULL,当时尚未设置该值。
编辑:左提一下,它是受限制的,不想更改BizCustomerService 和CustomerService 的代码,因为可以有很多对DAO 方法的调用,它会影响很多.所以只想在 DAO 级别进行更改。
所以我的问题是如何在 doSomeInsertUpdate() 方法中访问 WebAccount 对象?需要使用任何 Hibernate 吗?
提前致谢!!
【问题讨论】:
-
您不是已经在 doSomeInsertUpdate 方法中访问了 WebAccount 对象吗?如您的代码
if (customer.getWebAccount() != null)所示?还是我错过了什么?
标签: java spring hibernate spring-mvc jpa