【问题标题】:Mapping lazy relationship with DAO Factory使用 DAO 工厂映射惰性关系
【发布时间】:2016-02-12 08:09:30
【问题描述】:

我正在尝试做的是在 Bean 属性和 DAO 之间建立一种惰性关系。

这是我的代码:

豆类文章

public class Article {
    private Long id;
    private Product product;
    private Attribut attribut;
    private String name;
    private Article ParentArticle;
    \\ getters and setters
}

将文章映射到 Bean 的 DAO

private Article map(ResultSet resultSet) throws SQLException {
        Article article = new Article();
        \\set the id of the Article
        article.setId(resultSet.getLong("id"));     
        \\get the DAO of each article Bean attribute
        ProductDao productDao = daoFactory.getProductDao();
        ArticleDao articleDao = daoFactory.getArticleDao();
        AttributsDao attributsDao = daoFactory.getAttributDao();`

        \\set the product of the article by searching the product with his DAO
        article.setProduct(productDao.find(resultSet.getLong("idProduct")));

        \\set the Attribut of the article by searching the attribute with his DAO   
        article.setAttribut(attributsFonctionsDao.trouver(resultSet.getLong("idAttribut")));
       \\set the designation of the article     article.setDesignation(resultSet.getString("designationArticle"));
        \\set the Parent Article by searching the article with his DAO 
        article.setParentArticle(articleDao.trouver(resultSet.getLong("idArticleParent")));
        return article;
    }

所以我要问的是是否有办法映射文章对象属性,所以这里的属性产品、属性和父文章只有它们的 id 而不是对所有对象收费。我知道 Hibernate 可以提供帮助,但我想在没有 ORM 的情况下手动设置它。

【问题讨论】:

    标签: java jakarta-ee mapping dao


    【解决方案1】:

    从外观上看,ResultSet 实际上是您从数据库中查询到的数据,所以这个结构中的任何数据都是持久的,对吗?

    您可以做的是使用session.load(),因为这将始终返回一个 Hibernate 代理,而无需访问数据库。 Hibernate 代理是一个只有给定标识符的对象,在这种情况下是 id,并且所有其他属性还没有被初始化,它看起来像是来自数据库但它没有,它是实际检索到的合成表示实体。当对它进行操作时,如果它所引用的 id 引用的数据应该从持久层中消失,则代理将抛出 ObjectNotFoundException。

    我知道这可能不是您所期望的,因为您提到您正在寻找 ORM-free solution,但我相信这实际上符合您的目的,即为您的其他期望找到解决方案,即 not charge all the Object 的一种方式: )

    如果您使用 JPA,Hibernate 的 session.get() 的等效功能由 EntityManager.html#getReference 提供

    【讨论】:

    • 感谢您的回答。
    猜你喜欢
    • 2011-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多