使用 Liferay Service Builder 删除所有记录
Delete All Records using Liferay Service Builder
我可以使用 Liferay Service Builder 删除特定记录,但是当我想从该 table 中删除所有记录时该怎么办。
我是 Liferay 的新手所以任何帮助将不胜感激...!!!
由于您的实体名称是 Location
,请在您的 LocationLocalServiceImpl.java
中添加以下方法并构建服务:
public void deleteAllLocations(){
try{
LocationUtil.removeAll();
}catch(Exception ex){
// Log exception here.
}
}
构建成功后,deleteAllLocations
将被复制到 LocationLocalServiceUtil.java
,您可以在您的操作中使用它 class 作为:
LocationLocalServiceUtil.deleteAllLocations();
问题已经有了提问者满意的答案,但我想我会添加另一个相同的答案。由于您在服务实现中编写自定义方法(在您的情况下 LocationLocalServiceImpl
):
- 您可以直接访问持久性 bean,因此无需使用
LocationUtil
。
- 接受的答案建议捕获任何
Exception
并记录下来。我不同意这一点,因为它会悄无声息地失败,并且根据应用程序逻辑,以后可能会导致问题。例如,如果您的 removeAll
在一个交易中被调用,该交易的成功取决于正确删除所有实体并且接受的方法失败,则交易不会回滚,因为您没有抛出 SystemException
.
考虑到这一点,请考虑以下内容(在您的实施中,如上所述):
public void deleteAllLocations() throws SystemException {
locationPersistence.removeAll();
}
然后,无论您从何处调用它(例如在控制器中),您都可以控制发生故障时发生的情况
try {
LocationLocalServiceUtil.removeAllLocations();
} catch (SystemException e) {
// here whatever you've removed has been rolled back
// instead of just logging it, warn the user that an error occurred
SessionErrors.add(portletRequest, "your-error-key");
log.error("An error occurred while removing all locations", e);
}
话虽如此,您的 LocationUtil
class 在服务外部可用,因此您可以从控制器调用它。如果您的目标只是删除所有 Location
实体而不在该事务的上下文中执行任何其他操作,则您可以在控制器中使用 LocationUtil
。这将使您不必重建服务层。
我可以使用 Liferay Service Builder 删除特定记录,但是当我想从该 table 中删除所有记录时该怎么办。
我是 Liferay 的新手所以任何帮助将不胜感激...!!!
由于您的实体名称是 Location
,请在您的 LocationLocalServiceImpl.java
中添加以下方法并构建服务:
public void deleteAllLocations(){
try{
LocationUtil.removeAll();
}catch(Exception ex){
// Log exception here.
}
}
构建成功后,deleteAllLocations
将被复制到 LocationLocalServiceUtil.java
,您可以在您的操作中使用它 class 作为:
LocationLocalServiceUtil.deleteAllLocations();
问题已经有了提问者满意的答案,但我想我会添加另一个相同的答案。由于您在服务实现中编写自定义方法(在您的情况下 LocationLocalServiceImpl
):
- 您可以直接访问持久性 bean,因此无需使用
LocationUtil
。 - 接受的答案建议捕获任何
Exception
并记录下来。我不同意这一点,因为它会悄无声息地失败,并且根据应用程序逻辑,以后可能会导致问题。例如,如果您的removeAll
在一个交易中被调用,该交易的成功取决于正确删除所有实体并且接受的方法失败,则交易不会回滚,因为您没有抛出SystemException
.
考虑到这一点,请考虑以下内容(在您的实施中,如上所述):
public void deleteAllLocations() throws SystemException {
locationPersistence.removeAll();
}
然后,无论您从何处调用它(例如在控制器中),您都可以控制发生故障时发生的情况
try {
LocationLocalServiceUtil.removeAllLocations();
} catch (SystemException e) {
// here whatever you've removed has been rolled back
// instead of just logging it, warn the user that an error occurred
SessionErrors.add(portletRequest, "your-error-key");
log.error("An error occurred while removing all locations", e);
}
话虽如此,您的 LocationUtil
class 在服务外部可用,因此您可以从控制器调用它。如果您的目标只是删除所有 Location
实体而不在该事务的上下文中执行任何其他操作,则您可以在控制器中使用 LocationUtil
。这将使您不必重建服务层。