- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我在 Spring (3.2.2) 中使用 JPA(使用 Hibernate 4.3.3 作为持久性提供程序),我的所有字段都加载正常,但是当我尝试访问我的 Collection 时,它会抛出错误-
Exception in thread "main" org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.br.common.catalog.entity.Category.allParentCategoryXrefs, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:572)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:212)
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:551)
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:140)
at org.hibernate.collection.internal.PersistentBag.toString(PersistentBag.java:526)
at java.lang.String.valueOf(String.java:2827)
at java.io.PrintStream.println(PrintStream.java:771)
at test.Test.main(Test.java:30)
当我对此进行调试时,我的实体类中定义的每个集合都出现错误 - com.sun.jdi.InvocationException 发生调用方法。
我尝试使用 collection.size() 和 Hibernate.initialize() 但这些都不起作用。在网上搜索时,我发现扩展 Persitence 可以解决问题,即。
@PersistenceContext(type=PersistenceContextType.EXTENDED)
protected EntityManager em;
这很好,但通过这个我发现 em 将始终保持打开状态,现在 spring 将无法处理这个问题。有没有办法使用 Spring 来解决这个问题。非常感谢任何帮助。
我的实体是 -
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name="CATEGORY")
public class Category implements Serializable {
@Id
@GeneratedValue(generator= "CategoryId")
@Column(name = "CATEGORY_ID")
protected Long id;
@ManyToOne(targetEntity = Category.class)
@JoinColumn(name = "DEFAULT_PARENT_CATEGORY_ID")
@Index(name="CATEGORY_PARENT_INDEX", columnNames={"DEFAULT_PARENT_CATEGORY_ID"})
protected Category defaultParentCategory;
@OneToMany(targetEntity = Categoryref.class, mappedBy = "categoryrefPK.category")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="test")
@OrderBy(value="displayOrder")
@BatchSize(size = 50)
protected List<Categoryref> childCategoryRefs = new ArrayList<Categoryref>(10);
@OneToMany(targetEntity = Categoryref.class, mappedBy = "categoryrefPK.subCategory",fetch=FetchType.LAZY)
@Cascade(value={org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.PERSIST})
@OrderBy(value="displayOrder")
@BatchSize(size = 50)
protected List<Categoryref> parentCategoryRefs = new ArrayList<Categoryref>(10);
}
@Entity
@Polymorphism(type = PolymorphismType.EXPLICIT)
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "CATEGORY_REF")
public class Categoryref implements Serializable {
/** The category id. */
@EmbeddedId
CategoryrefPK categoryrefPK = new CategoryrefPK();
public CategoryrefPK getCategoryrefPK() {
return categoryrefPK;
}
public void setCategoryrefPK(final CategoryrefPK categoryrefPK) {
this.categoryrefPK = categoryrefPK;
}
}
@Embeddable
public class CategoryrefPK implements Serializable {
@ManyToOne(targetEntity = Category.class, optional=false)
@JoinColumn(name = "CATEGORY_ID")
protected Category category = new Category();
@ManyToOne(targetEntity = Category.class, optional=false)
@JoinColumn(name = "SUB_CATEGORY_ID")
protected Category subCategory = new Category();
}
我的 Xml 配置为 -
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.br" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
....
</bean>
<!-- this is also used we can used this also -->
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="abc" />
<property name="packagesToScan" value="com.br.common.*" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
</bean>
</property>
</bean>
</beans>
Persitence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="abc">
transaction-type="RESOURCE_LOCAL">
<mapping-file>META-INF/category.orm.xml</mapping-file>
<class>com.br.common.Category</class>
<class>com.br.common.Categoryref</class>
<class>com.br.common.CategoryrefPK</class>
<properties>
<property name="javax.persistence.jdbc.user" value="user"
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"></property>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test>
<property name="javax.persistence.jdbc.password" value="...">
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.transaction.flush_before_completion"
value="false" />
<property name="hibernate.connection.autocommit" value="true" />
<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory"/>
<property name="hibernate.cache.use_second_level_cache" value="true" />
<property name="hibernate.cache.use_query_cache" value="true"/>
<property name="hibernate.generate_statistics" value="false" />
<property name="hibernate.archive.autodetection" value="false" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.id.new_generator_mappings" value="true" />
</properties>
</persistence-unit>
</persistence>
这是我的 dao 我通过服务层调用 dao
@Repository("categoryDaoImpl")
public class CategoryDaoImpl implements ICategoryDAO {
@PersistenceContext
protected EntityManager em;
public Category save(Category category) {
Category category2= em.merge(category);
em.flush();
return category2;
}
public Category readCategoryById(Long categoryId) {
return em.find(Category.class, categoryId);
}
}
服务层
@Service("blCatalogService")
@Transactional(propagation=Propagation.REQUIRED)
public class CatalogServiceImpl implements ICatalogService {
@Resource(name="categoryDaoImpl")
protected ICategoryDAO categoryDao;
@Transactional
public Product saveProduct(Product product) {
return productDao.save(product);
}
public Category findCategoryById(Long categoryId) {
return categoryDao.readCategoryById(categoryId);
}
}
这是主要的
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext-persistence.xml");
ICatalogService serviceCategory= (ICatalogService) context
.getBean("blCatalogService");
Category parentCategory=serviceCategory.findCategoryById(2l);
System.out.println(parentCategory.getAllParentCategoryrefs());//here error is coming while accessing collection
}
}
最佳答案
问题是当这个方法调用返回时:
Category parentCategory=serviceCategory.findCategoryById(2l);
在这里,您不再处于 @Transactional
上下文中。这意味着链接到 parentCategory 的 session 已关闭。现在,当您尝试访问链接到已关闭 session 的集合时,会发生 No Session
错误。
需要注意的一点是,main 方法在任何 spring bean 之外运行,并且没有持久性上下文的概念。
解决方案是从事务上下文中调用 parentCategory.getAllParentCategoryrefs()
,这永远不能成为应用程序的主要方法。
然后将 parentCategory 重新附加到新的持久化上下文,然后调用 getter。
例如,尝试将 parentCategory 传递回同一服务的事务方法:
serviceCategory.nowItWorks(parentCategory);
服务上的方法是事务性的:
@Transactional(readOnly=true)
public void nowItWorks(Category category) {
dao.nowItWorks(category);
}
在 DAO 中:
public void nowItWorks(Category category) {
Category reattached = em.merge(category);
System.out.println("It works: " + reattached.getAllParentCategoryrefs());
}
关于java - 无法懒惰地初始化角色集合,..无法初始化代理 - 无 session - JPA + SPRING,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22643098/
是否为每个 Shiny session 分配了 session ID/ session key (如果部署在 Shiny 服务器上)?如果是,我如何访问该信息?我已阅读文档here然而上网查了一下,并
我正在使用 this koajs session 模块。 我检查了源代码,但我真的无法理解。 我想知道它保存 session 数据的位置,因为我没有看到创建的文件,并且当服务器重新启动时, sessi
实现高可扩展性的一种方法是使用网络负载平衡在多个服务器之间分配处理负载。 这种方法提出的一个挑战是服务器是否具有状态意识 - 将用户状态存储在“ session ”中。 此问题的一个解决方案是“粘性
在负载平衡服务器的上下文中, session 亲和性和粘性 session 之间有什么区别? 最佳答案 我见过这些术语可以互换使用,但有不同的实现方式: 在第一个响应中发送 cookie,然后在后续响
我希望其他人向我解释哪种方法更好:使用 session 或设计无 session 。我们正在开始开发一个新的 Web 应用程序,但尚未决定要遵循什么路径。 无 session 设计在我看来更可取: 优
现在用户在他的权限中有很多角色,我将允许他点击 href 并在新窗口中扮演另一个角色。每个角色都有自己的 session 。 既然浏览器打开窗口不能用新 session 打开,我必须在服务器端想办法。
我正在尝试为express.js Node 应用程序实现 session 存储我的问题是: 如何删除具有浏览器 session 生命周期的 cookie(根据连接文档标记有 expires = fal
在开始在 golang 中使用 session 之前,我需要回答一些问题 session 示例 import "github.com/gorilla/sessions" var store = ses
我读过 Namespaced Attributes . 我尝试使用此功能: #src/Controller/CartController.php public function addProduct(
我正在努力完成以下工作: 根据用户的类型更改用户的 session cookie 到期日期。 我有一个 CakePHP Web 应用程序,其中我使用 CakePHP session 创建了我的身份验证
这是我在这里的第一个问题,我希望我做对了。 我需要处理一个 Java EE 项目,所以在开始之前,我会尝试做一些简单的事情,看看我是否能做到。 我坚持使用有状态 session Bean。 这是问题:
ColdFusion session 与 J2EE session 相比有什么优势吗? ColdFusion session documentation提到了 J2EE session 的优点,但没有
在执行任何任务之前,我需要准确地在创建 session 时创建一个 session 范围变量(因为我的所有任务都需要一个初始 session 范围变量才能运行)。因为,创建 session 时,gra
我们当前的应用使用 HTTP session ,我们希望将其替换为 JWT。 该设置仅允许每个用户进行一次 session 。这意味着: 用户在设备 1 上登录 用户已在设备 1 上登录(已创建新 s
很难说出这里问的是什么。这个问题是含糊的、模糊的、不完整的、过于宽泛的或修辞性的,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开它,visit the help center 。 已关
假设我在两个或更多设备上打开了两个或更多用户 session (同一用户没有管理员权限)。 在当前 session 中,如果我注销,是否意味着所有其他 session 也会关闭?如果没有,有没有办法通
我正在评估在 tomcat 中使用带有 session 复制的粘性 session 的情况。根据我的初步评估,我认为如果我们启用 session 复制,那么在一个 tomcat 节点中启动的 sess
我开始使用 golang 和 Angular2 构建一个常规的网络应用程序,最重要的是我试图在 auth0.com 的帮助下保护我的登录.我从 here 下载快速入门代码并尝试运行代码,它运行了一段时
我在 Spring Controller 中有一个方法,它接受两个相同类型的参数其中一个来自 session ,另一个来自表单提交(UI)。 问题是在 Controller 方法中我的非 sessio
在我登录之前,我可以点击我的安全约束目录之外的任何内容。如果我尝试转到安全约束目录内的某个位置,它会将我重定向到表单登录页面。如您所料。 登录后,我可以继续我的业务,并访问我的安全约束内外的资源。
我是一名优秀的程序员,十分优秀!