延迟加载 java,设计一个具有延迟加载属性的Java POJO

Please consider below example:

A web application creates a user object for every logged in user. This object has simple String properties for firstName, lastName ...

Each user can have a car too. Consider that fetching the user car is very expensive, so we prefer not to set the users car when user logs in. Instead we want to get car when a use case needs it.

To implement this we have created a User pojo as:

public class User() {

private String FirstName;

private String LastName;

private Car car;

//Here we have the service object, this could be injected with spring or JEE

private CarServices carServices;

public Car getCar() {

//If the car is not fetched yet, go on and get it from your service

if (car == null) {

car = carServices.getCarFromDB(...)

}

return car;

}

}

To initial user after a login:

User newUser = new User();

newUser.setFirstName("foo");

newUser.setLastName("bar");

//We just let user have service, so he can use this service latter

newUser.setCarServices( new CarServices() );

And every use case which needs the user car can get it easily:

newUser.getCar()

However, I have been argued that in this way my User object is not a simple pojo any more and this is not a good approach.

How can I achieve this requirement in better way.

解决方案

I have been argued that in this way my User object is not a simple pojo

To anwer your question I would first like to go back a bit in history.

Pojo is a plain old java object and means that you only use "standard" java. The term was created at a time when J2EE had it's hype. At this time developers coded business logic in enterprise beans and this EJBs needed a lot of infrastructure code. This fact coupled buisness logic to an implementation technology. So Rebecca Parsons, Josh MacKenzie and Martin Fowler came to the conclusion that business logic would be more reuseable and easier to test if you just use standard java. Thus they created the term pojo, because developers like fancy names.

Your User class just depends on standard java and therefore it is a pojo.

Some developers argue that a pojo should not contain any logic. These developer prefer anemic models. Others say that a rich model is the better approach. I belong to the developers who prefer a rich model over an anemic model.

If you want to remove the CarServices dependency from the User class you can implement a Car lazy loading proxy just like hibernate or a jpa implementation does.

At least here are some of my thoughts to beans, pojos, anemic and rich domain models.

Hopefully it helps you when you discuss wih other developers.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值