小编NKi*_*253的帖子

尽管有 Spring 事务,但 LazyInitializationException 异常?

下面的方法导致org.hibernate.LazyInitializationException被抛出,我很感激帮助理解原因。我正在使用 JPA 2/Hibernate & Spring。

JPA 2/Hibernate 使用默认的transaction持久化上下文,因此,下面的方法不应该允许延迟加载吗?

@Service
public class GalleryService {
    @Transactional(readOnly=true)
    public Response getGallery(@PathParam("id") int id) {
        Gallery g = daoWrapper.findById(Gallery.class, id);
        ...
        GalleryDto gDto = new GalleryDto();
        ...
        // getImages() returns a collection of 'image' objects.
        gDto.setImages(g.getImages());
        return Response.ok(gDto).build();
    }
}
Run Code Online (Sandbox Code Playgroud)

注意daoWrapper是一个包装实体管理器方法的便利类。

@Repository
public class daoWrapper implements BaseDao {

   @PersistenceContext(unitName="persistStore") 
   private EntityManager em;

   @Override
   public <T,U> T findById(Class<T> entity, U id) {
        return this.em.find(entity, id);
   }
   ...
}
Run Code Online (Sandbox Code Playgroud)

应用程序上下文文件: …

java spring hibernate jpa

5
推荐指数
1
解决办法
2599
查看次数

遍历ORM关系会返回重复的结果

我有4张桌子 - store, catalog_galleries, catalog_images, and catalog_financials.

store --> catalog_galleries --> catalog_images换句话说,当我遍历关系时:store.getCatalogGallery().getCatalogImages()我得到重复的记录.有谁知道这可能是什么原因?关于在哪里看的任何建议?

store表具有一种OneToOne关系,catalog_galleries该关系又具有OneToMany与之关系catalog_images和渴望获取类型.该store表也OneToMany与之有关系catalog_financials.

以下是相关实体:

商店实体

@Entity
@Table(name="store")  
public class Store {
    ...
    private CatalogGallery gallery;
    ...
    @OneToOne(mappedBy="store")
    public CatalogGallery getGallery() {
        return gallery;
    }
}
Run Code Online (Sandbox Code Playgroud)

CatalogGallery实体

@Entity
@Table(name="catalog_galleries")  
public class CatalogGallery {
    ...
    private Store store;
    private Collection<CatalogImage> catalogImages;
    ...
    @OneToOne
    @PrimaryKeyJoinColumn
    public Store getStore() {
        return store;
    }

    @OneToMany(mappedBy="catalogGallery", …
Run Code Online (Sandbox Code Playgroud)

java sql hibernate jpa

4
推荐指数
1
解决办法
1775
查看次数

标签 统计

hibernate ×2

java ×2

jpa ×2

spring ×1

sql ×1