在我的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"));
}
}
的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
中创建的,然后可能会在通过DAO保留后更改相关WebAccount
的状态。提交事务时,新的Customer和相关的WebAccount
对象将持久保存到DB。我知道这是正常的。
问题是;在CustomerDAO#save() >> doSomeInsertUpdate()
方法中,'webAccount'为NULL,此时尚未设置该值。
编辑:还有一点,它是受限制的,不想更改BizCustomerService
和CustomerService
的代码,因为可以对DAO方法进行多次调用它可以影响很多。所以想只在DAO级别进行更改。
所以我的问题是如何在doSomeInsertUpdate()方法中访问WebAccount对象?是否需要任何Hibernate使用?
提前致谢!!
答案 0 :(得分:0)
不确定你期待什么,但我认为这里没有魔力。如果您希望WebAccount为!= null
,则必须明确地创建一个并将其保存到数据库中。
WebAccount wb = new WebAccount();
getSession().save(wb);
customer.setWebAccount(wb);