如何正确初始化通过实体的懒惰收集?
我需要通过使用实体自行初始化集合。我的意思是,我可以在Java中做到这一点,例如: 我会从StatelesBean类中调用方法。如何正确初始化通过实体的懒惰收集?
那么,我怎么能在PHP的方式呢?如果有人可以写样本代码,我将不胜感激。
@Transient
public void initialize(Collection collection, int levelCursor, int level)
{
if (collection instanceof PersistentBag)
{
if (ObjectUtil.isNull(((PersistentBag)collection).getSession()))
return;
else
{
Iterator itr = ((Collection)collection).iterator();
while (itr.hasNext())
{
if (levelCursor < level)
((SuperEntity)itr.next()).initialize(levelCursor, level);
else
itr.next();
}
}
} else
{
Iterator itr = ((Collection)collection).iterator();
while (itr.hasNext())
{
if (levelCursor < level)
((SuperEntity)itr.next()).initialize(levelCursor, level);
else
itr.next();
}
}
}
/**
* Searches for column and join column annotations for getter methods.
* If found then tries to initialize childs
* @param levelCursor
* @param level
*/
@Transient
public void initialize(int levelCursor, int level)
{
levelCursor++;
Method[] methods = this.getClass().getMethods();
Object obj = null;
try
{
for (Method method : methods)
{
if (method.getAnnotation(JoinColumn.class) != null || method.getAnnotation(JoinTable.class) != null || method.getAnnotation(OneToMany.class) != null)
{
Object result = method.invoke(this, new Object[0]);
if (result == null)
continue;
if (result instanceof SuperEntity)
{
if (levelCursor < level)
((SuperEntity)result).initialize(levelCursor, level);
} else if (result instanceof Collection)
initialize((Collection)result, levelCursor, level);
}
}
}
catch (Exception exc)
{
exc.printStackTrace();
}
}
所以,据我了解你的任务,你想初始化你的实体集合的对象,当你检索它们?
当你要求它的时候,主义加载你的收藏automagicaly。
所以,你可以用一个getter做到这一点:
class User
{
/**
* OneToMany(targetEntity="Car", mappedBy="owner")
*/
private $ownedCars;
public function __construct()
{
$this->ownedCars = new ArrayCollection();
}
public function getOwnedCars($level)
{
// autoload collection
foreach($this->ownedCars as $ownedCar)
{
$ownedCar->initialize($level);
}
return $this->ownedCars;
}
}
谢谢,是的,这是一种解决延迟初始化的方法。但实际上,我想用反射的方式来解决这个问题,因为我不想写所有具有arrayCollection的实体。我更喜欢通用解决方案,正如我在我的问题中提到的,例如MappedSuperClass上的方法包含反射。 – webyildirim 2014-09-04 12:39:21
是否可以在目标实体中实现魔术[__wakeup()](http://php.net/manual/en/language.oop5.magic.php#object.wakeup)方法?当学说将对象反序列化时,它会被调用。 – Mischa 2014-09-04 15:03:33
能否请您解释一下更多你想要做什么?顺便说一句,我不确定Java示例在这里有帮助。一些PHP上下文会更有用。 – lxg 2014-09-03 21:47:09
假设我们有User实体和ownCars arrayCollection。而fetchType是懒惰,所以当我得到用户实体记录我可能想要达到ownedCars集合。我想初始化它们,如user.initialize(1){1是deepLevel}或user.initialize(user.getOwnedCars()) – webyildirim 2014-09-04 07:15:03