映射与 DAO 工厂的懒惰关系



我想做的是在Bean属性和DAO之间建立惰性关系。

所以这是我的代码:

豆类文章

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

DAO 用于将文章映射到 Bean

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的情况下手动设置它。

从外观上看,ResultSet 实际上是您从数据库中查询的数据,因此来自此结构的任何数据都是持久的,对吗?

你可以做的是使用 session.load((,因为它将始终返回一个 Hibernate 代理,而不访问数据库。Hibernate代理是一个只有给定标识符的对象,在本例中为id,所有其他属性尚未初始化,它看起来像来自数据库,但事实并非如此,它是实际检索实体的合成表示。当对它进行操作时,如果它通过id引用的数据应该从持久性层中消失,则代理将抛出ObjectNotFoundException。

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

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

最新更新