道和服务的复杂对象

时间:2013-09-04 14:02:22

标签: spring service dao

所以我有这个复杂的对象,例如:

@Entity
public class House {

private Kitchen kitchen;
private LivingRoom livingRoom;
private MainBedRoom mainBedRoom;
private Toilet toilet;
etc...


}

现在House类中的每个对象(Kitchen,LivingRoom等等)都非常复杂,非原始字段和什么不是..

我有以下服务:

@Service
public HouseService {


}

@Service
public KitchenService{


}

..等等..

我的问题是:

如果我在HouseService中创建一个新的House对象,我是否必须使用其他服务来创建该方法?

似乎我根本不需要所有其他服务,因为House是所有对象的根,我需要的只是一个(显然很大)的HouseService?是吗?

即。 :

HouseService.createNewHouse {

House house  = new House(...);
Kitchen kitchen = new Kitchen(...);
... 

   house.setKitchen(kitchen);
  this.dao.save(house);
  return house; 
  }

}

1 个答案:

答案 0 :(得分:1)

虽然你可以,但不要让你的生活变得复杂。我假设您的每个Entity类都有多个DAO。只需@Inject(或@Autowired) and use them directly in each服务`类。

您的@Service课程应该已经@Transactional,因此您无需通过其他@Service课程获得任何内容(除非有特定的商业逻辑)。

而不是

@Service
public class FirstService {
    @Autowired
    private SecondService secondService;
    @Autowired
    private FirstDao firstDao;

    @Transactional
    public void saveFirst(First first) {
        secondService.saveSecond(first.getSecond());
        firstDao.save(first);
    }
}

@Service
public class SecondService {
    @Autowired
    private SecondDao secondDao ;

    @Transactional
    public void saveSecond(Second second) {
        secondDao .save(second);
    }
}

直接去DAO

@Service
public class FirstService {
    @Autowired
    private SecondDao secondDao;
    @Autowired
    private FirstDao firstDao;

    @Transactional
    public void saveFirst(First first) {
        secondDao.save(first.getSecond());
        firstDao.save(first);
    }
}