MapStruct可以对Hibernate实体类进行深度替代吗 [英] Can MapStruct do a deep deproxy of Hibernate Entity Classes

查看:178
本文介绍了MapStruct可以对Hibernate实体类进行深度替代吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是想要直接返回实体类的Web服务开发人员的常见问题.即使加载了我需要的所有数据,仍然有许多我不需要的未初始化代理和集合.我希望他们只返回null而不抛出Lazy Load Exception.基本上,我只想要POJO合同,但是必须清除代理和休眠集合才能实现这一点(除非我不知道休眠中有一些新方法).我可以使用MapStruct来做到这一点吗?

This is a common issue for web service developers who would like to return entity classes directly. Even if all the data I need is loaded there are still many uninitialized proxies and collections that I don't need. I would like for them to just return null and not throw a Lazy Load Exception. Basically I just want the POJO contract, however proxies and hibernate collections have to be purged to get that (unless there is some new way in hibernate that I don't know about). Can I use MapStruct to do this?

有关此操作的更多详细信息:

More details about this if needed:

http://www.mojavelinux.com/blog/archives/2006/06/hibernate_get_out_of_my_pojo/

http://www.gwtproject.org/articles/using_gwt_with_hibernate.html

吉列德(Gilead)是我发现的唯一对此有效的方法,但它不再存在了.

Gilead was the only thing that I found that worked well for this but it is no longer around.

推荐答案

是的,您可以使用MapStruct做到这一点.但是,只能通过显式标记要映射的内容和要忽略的内容.

Yes you can do that with MapStruct. However, only by explicitly marking what you want to map and what you want to ignore.

假设您有此类课程:

public class Car {

    private String name;
    private int year;
    //This is lazy loaded
    private List<Wheel> wheels;
    //getters and setters omitted for simplicity
}

public class Wheel {
    private boolean front;
    private boolean right;
    //getters and setters omitted for simplicity
}

您将需要一个如下所示的映射器:

You will need a mapper that looks like this:

@Mapper
public interface CarMapper {

    @Mapping(target="wheels", ignore=true)
    Car mapWithoutWheels(Car car);

    Car mapWithWheels(Car car);

    List<Wheel> map(List<Wheel> wheels);

    Wheel map(Wheel wheel);
}

如果要强制MapStruct创建新对象而不执行直接映射,则需要List<Wheel>Wheel的显式映射.当前,如果MapStruct看到源类型和目标类型相同,则会直接分配(使用列表,它将创建一个新列表,但不会在列表的元素中调用getter).

The explicit mapping for List<Wheel> and Wheel is needed if you want to force MapStruct to create new objects and not do direct mapping. Currently, if MapStruct sees that the source and target type are same it does direct assignment (with lists it will create a new list, but it won't call getters in the elements of the list).

如果Wheel具有一些延迟加载的元素,则可以有2种映射Wheel的方法,并且必须使用

If Wheel had some lazy loaded elements, then you can have 2 methods for mapping Wheel and you will have to use selection based on qualifiers

这篇关于MapStruct可以对Hibernate实体类进行深度替代吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆