【问题标题】:Hibernate one to many bidirectional association not loading with Spring Data休眠一对多双向关联不加载 Spring Data
【发布时间】:2014-10-15 13:54:07
【问题描述】:

我有一个如下的双向映射

@Entity
@Table(name = "Stock")
public class StockEntity implements Serializable {


    private String planNum;

    private Set<StockOptionEntity> options = new HashSet<StockOptionEntity>(0);



    @OneToMany(fetch = FetchType.EAGER, mappedBy="stock")
    public Set<StockOptionEntity> getOptions() {
        return Options;
    }

    public void setOptions(Set<StockOptionEntity> Options) {
        this.Options = Options;
    }
}

然后我有另一个映射如下..

@Entity
@Table(name = "StockOption")
@IdClass(StockOptionEntityPK.class)
public class StockOptionEntity implements Serializable {



    private StockEntity stock;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "PlanNum", insertable = false, updatable = false)    
    public StockEntity getStock() {
        return Stock;
    }

    public void setStock(StockEntity Stock) {
        this.Stock = Stock;
    }
}

然后我为会话、实体和事务管理器声明如下 Spring Beans

@Bean
public DataSource msSqlDataSource() {
    SQLServerConnectionPoolDataSource dataSource = new SQLServerConnectionPoolDataSource();
    ...........
    return dataSource;

}
@Bean
@DependsOn({ "msSqlDataSource"})    
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    try {
        sessionFactory.setDataSource(msSqlDataSource());
    } catch (Exception e) {
        log.error("Failed to attach dataSource object to SessionFactory bean. "
                + "Exception: " + e.getMessage());
    }
    sessionFactory
            .setPackagesToScan("com.firstx.db.entity.*");
    sessionFactory.setHibernateProperties(hibernateProperties());

    return sessionFactory;
}
@Bean
@DependsOn({ "sessionFactory","msSqlDataSource"})
public EntityManagerFactory entityManagerFactory() {

    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(true);

    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(vendorAdapter);
    factory.setPackagesToScan("com.firstx.db.entity.*");
    try {
        factory.setDataSource(msSqlDataSource());
    } catch (Exception e) {
        log.error("Failed to attach dataSource object to EntityManagerFactor bean. "
                + "Exception: " + e.getMessage());
    }
    factory.afterPropertiesSet();

    return factory.getObject();
}
  @Bean
   public PlatformTransactionManager transactionManager(){
      JpaTransactionManager transactionManager = new JpaTransactionManager();
      transactionManager.setEntityManagerFactory(
              entityManagerFactory() );
      return transactionManager;
   }

最后,我使用 Spring Data repository - repository.findOne(...) 方法来提取我的 Stock 对象以及 StockOptions。

在这种情况下,我无法检索股票期权的集合。集合为空。

我尝试了以下方法(保持 Spring bean 不变),

  1. 将关系转换为单向关系(通过删除 mappedBy 和相关内容)。
  2. 删除了 Set 的初始化。
  3. 删除了 StockOption 的 ID 类

以上两个选项都不起作用。

在调试中,我看到 StockOptions 已成功检索并加载到会话缓存中。但是,我无法弄清楚为什么它实际上没有被加载回父对象。

下面是调试...

1853270 [http-nio-8080-exec-10] TRACE o.h.e.i.DefaultInitializeCollectionEventListener - Initializing collection [com.firstx.db.entity.base.StockEntity.options#d97]
1853270 [http-nio-8080-exec-10] TRACE o.h.e.i.DefaultInitializeCollectionEventListener - Checking second-level cache
1853270 [http-nio-8080-exec-10] TRACE o.h.e.i.DefaultInitializeCollectionEventListener - Collection not cached
1853271 [http-nio-8080-exec-10] DEBUG o.h.l.c.p.AbstractLoadPlanBasedCollectionInitializer - Loading collection: [com.firstx.db.entity.base.StockEntity.options#d97]
1853271 [http-nio-8080-exec-10] DEBUG org.hibernate.SQL - select options0_.PlanNum as PlanNum1_11_0_, options0_.PlanNum as PlanNum1_13_0_, options0_.OptionCode as Optio2_13_0_, options0_.PlanNum as PlanNum1_13_1_ ......... from StockOption options0_ where options0_.PlanNum=?
1853271 [http-nio-8080-exec-10] TRACE o.h.e.j.i.JdbcCoordinatorImpl - Registering statement [SQLServerPreparedStatement:13]
1853271 [http-nio-8080-exec-10] TRACE o.h.e.j.i.JdbcCoordinatorImpl - Registering last query statement [SQLServerPreparedStatement:13]
1853271 [http-nio-8080-exec-10] TRACE o.h.type.descriptor.sql.BasicBinder - binding parameter [1] as [VARCHAR] - [d97]
1853271 [http-nio-8080-exec-10] TRACE o.h.l.p.e.i.AbstractLoadPlanBasedLoader - Bound [2] parameters total
1853305 [http-nio-8080-exec-10] TRACE o.h.e.j.i.JdbcCoordinatorImpl - Registering result set [SQLServerResultSet:68]
1854044 [http-nio-8080-exec-10] DEBUG o.h.l.p.e.p.i.ResultSetProcessorImpl - Preparing collection intializer : [com.firstx.db.entity.base.StockEntity.options#d97]
1854044 [http-nio-8080-exec-10] TRACE o.h.e.loading.internal.LoadContexts - Constructing collection load context for result set [SQLServerResultSet:68]
1854773 [http-nio-8080-exec-10] TRACE o.h.e.l.i.CollectionLoadContext - Starting attempt to find loading collection [[com.firstx.db.entity.base.StockEntity.options#d97]]
1854773 [http-nio-8080-exec-10] TRACE o.h.e.loading.internal.LoadContexts - Attempting to locate loading collection entry [CollectionKey[com.firstx.db.entity.base.StockEntity.options#d97]] in any result-set context
1854774 [http-nio-8080-exec-10] TRACE o.h.e.loading.internal.LoadContexts - Collection [CollectionKey[com.firstx.db.entity.base.StockEntity.options#d97]] not located in load context
1854774 [http-nio-8080-exec-10] TRACE o.h.e.l.i.CollectionLoadContext - Collection not yet initialized; initializing
1854774 [http-nio-8080-exec-10] TRACE o.h.l.p.e.p.i.ResultSetProcessorImpl - Processing result set
1854774 [http-nio-8080-exec-10] DEBUG o.h.l.p.e.p.i.ResultSetProcessorImpl - Starting ResultSet row #0
1854774 [http-nio-8080-exec-10] TRACE o.h.t.descriptor.sql.BasicExtractor - extracted value ([PlanNum1_13_1_] : [VARCHAR]) - [D97]
1854774 [http-nio-8080-exec-10] TRACE o.h.t.descriptor.sql.BasicExtractor - extracted value ([Optio2_13_1_] : [VARCHAR]) - [03]
1854775 [http-nio-8080-exec-10] TRACE o.h.t.descriptor.sql.BasicExtractor - extracted value ([PlanNum1_11_0_] : [VARCHAR]) - [D97]
1854775 [http-nio-8080-exec-10] DEBUG o.h.l.p.e.p.i.CollectionReferenceInitializerImpl - Found row of collection: [com.firstx.db.entity.base.StockEntity.options#D97]
1855453 [http-nio-8080-exec-10] TRACE o.h.e.l.i.CollectionLoadContext - Starting attempt to find loading collection [[com.firstx.db.entity.base.StockEntity.options#D97]]
1855454 [http-nio-8080-exec-10] TRACE o.h.e.loading.internal.LoadContexts - Attempting to locate loading collection entry [CollectionKey[com.firstx.db.entity.base.StockEntity.options#D97]] in any result-set context
1855454 [http-nio-8080-exec-10] TRACE o.h.e.loading.internal.LoadContexts - Collection [CollectionKey[com.firstx.db.entity.base.StockEntity.options#D97]] not located in load context
1855454 [http-nio-8080-exec-10] TRACE o.h.e.l.i.CollectionLoadContext - Collection already initialized; ignoring
1856195 [http-nio-8080-exec-10] DEBUG o.h.l.p.e.p.i.ResultSetProcessorImpl - Starting ResultSet row #1
1856196 [http-nio-8080-exec-10] TRACE o.h.t.descriptor.sql.BasicExtractor - extracted value ([PlanNum1_13_1_] : [VARCHAR]) - [D97]
1856196 [http-nio-8080-exec-10] TRACE o.h.t.descriptor.sql.BasicExtractor - extracted value ([Optio2_13_1_] : [VARCHAR]) - [18]
1856196 [http-nio-8080-exec-10] TRACE o.h.t.descriptor.sql.BasicExtractor - extracted value ([PlanNum1_11_0_] : [VARCHAR]) - [D97]
1856196 [http-nio-8080-exec-10] DEBUG o.h.l.p.e.p.i.CollectionReferenceInitializerImpl - Found row of collection: [com.firstx.db.entity.base.StockEntity.options#D97]
1856819 [http-nio-8080-exec-10] TRACE o.h.e.l.i.CollectionLoadContext - Starting attempt to find loading collection [[com.firstx.db.entity.base.StockEntity.options#D97]]
1856820 [http-nio-8080-exec-10] TRACE o.h.e.loading.internal.LoadContexts - Attempting to locate loading collection entry [CollectionKey[com.firstx.db.entity.base.StockEntity.options#D97]] in any result-set context
1856820 [http-nio-8080-exec-10] TRACE o.h.e.loading.internal.LoadContexts - Collection [CollectionKey[com.firstx.db.entity.base.StockEntity.options#D97]] not located in load context
1856820 [http-nio-8080-exec-10] TRACE o.h.e.l.i.CollectionLoadContext - Collection already initialized; ignoring
1857454 [http-nio-8080-exec-10] DEBUG o.h.l.p.e.p.i.ResultSetProcessorImpl - Starting ResultSet row #2
1857454 [http-nio-8080-exec-10] TRACE o.h.t.descriptor.sql.BasicExtractor - extracted value ([PlanNum1_13_1_] : [VARCHAR]) - [D97]
1857454 [http-nio-8080-exec-10] TRACE o.h.t.descriptor.sql.BasicExtractor - extracted value ([Optio2_13_1_] : [VARCHAR]) - [42]
1857455 [http-nio-8080-exec-10] TRACE o.h.t.descriptor.sql.BasicExtractor - extracted value ([PlanNum1_11_0_] : [VARCHAR]) - [D97]
1857455 [http-nio-8080-exec-10] DEBUG o.h.l.p.e.p.i.CollectionReferenceInitializerImpl - Found row of collection: [com.firstx.db.entity.base.StockEntity.options#D97]
1858028 [http-nio-8080-exec-10] TRACE o.h.e.l.i.CollectionLoadContext - Starting attempt to find loading collection [[com.firstx.db.entity.base.StockEntity.options#D97]]
1858028 [http-nio-8080-exec-10] TRACE o.h.e.loading.internal.LoadContexts - Attempting to locate loading collection entry [CollectionKey[com.firstx.db.entity.base.StockEntity.options#D97]] in any result-set context
1858028 [http-nio-8080-exec-10] TRACE o.h.e.loading.internal.LoadContexts - Collection [CollectionKey[com.firstx.db.entity.base.StockEntity.options#D97]] not located in load context
1858028 [http-nio-8080-exec-10] TRACE o.h.e.l.i.CollectionLoadContext - Collection already initialized; ignoring
1858628 [http-nio-8080-exec-10] TRACE o.h.l.p.e.p.i.ResultSetProcessorImpl - Done processing result set (3 rows)
1858628 [http-nio-8080-exec-10] TRACE o.h.l.p.e.p.i.AbstractRowReader - Total objects hydrated: 0
1859193 [http-nio-8080-exec-10] TRACE o.h.e.loading.internal.LoadContexts - Attempting to locate loading collection entry [CollectionKey[com.firstx.db.entity.base.StockEntity.options#d97]] in any result-set context
1859193 [http-nio-8080-exec-10] TRACE o.h.e.loading.internal.LoadContexts - Collection [CollectionKey[com.firstx.db.entity.base.StockEntity.options#d97]] located in load context
1861703 [http-nio-8080-exec-10] TRACE o.h.e.l.i.CollectionLoadContext - Removing collection load entry [org.hibernate.engine.loading.internal.LoadingCollectionEntry<rs=SQLServerResultSet:68, coll=[com.firstx.db.entity.base.StockEntity.options#d97]>@8edfd0]
1863159 [http-nio-8080-exec-10] DEBUG o.h.e.l.i.CollectionLoadContext - 1 collections were found in result set for role: com.firstx.db.entity.base.StockEntity.options
1863159 [http-nio-8080-exec-10] TRACE o.h.e.l.i.CollectionLoadContext - Ending loading collection [org.hibernate.engine.loading.internal.LoadingCollectionEntry<rs=SQLServerResultSet:68, coll=[com.firstx.db.entity.base.StockEntity.options#d97]>@8edfd0]
1864512 [http-nio-8080-exec-10] DEBUG o.h.e.l.i.CollectionLoadContext - Collection fully initialized: [com.firstx.db.entity.base.StockEntity.options#d97]
1865190 [http-nio-8080-exec-10] DEBUG o.h.e.l.i.CollectionLoadContext - 1 collections initialized for role: com.firstx.db.entity.base.StockEntity.options
1865190 [http-nio-8080-exec-10] TRACE o.h.e.j.i.JdbcCoordinatorImpl - Releasing result set [SQLServerResultSet:68]
1865190 [http-nio-8080-exec-10] TRACE o.h.e.j.i.JdbcCoordinatorImpl - Closing result set [SQLServerResultSet:68]
1865190 [http-nio-8080-exec-10] TRACE o.h.e.j.i.JdbcCoordinatorImpl - Releasing statement [SQLServerPreparedStatement:13]
1865190 [http-nio-8080-exec-10] TRACE o.h.e.j.i.JdbcCoordinatorImpl - Closing prepared statement [SQLServerPreparedStatement:13]
1865211 [http-nio-8080-exec-10] TRACE o.h.e.j.i.JdbcCoordinatorImpl - Starting after statement execution processing [ON_CLOSE]
1865979 [http-nio-8080-exec-10] DEBUG o.h.l.c.p.AbstractLoadPlanBasedCollectionInitializer - Done loading collection
1865979 [http-nio-8080-exec-10] TRACE o.h.e.i.DefaultInitializeCollectionEventListener - Collection initialized
1866720 [http-nio-8080-exec-10] DEBUG o.h.l.e.p.AbstractLoadPlanBasedEntityLoader - Done entity load : com.firstx.db.entity.base.StockEntity#d97
1866720 [http-nio-8080-exec-10] TRACE org.hibernate.internal.SessionImpl - Setting cache mode to: NORMAL
1866720 [http-nio-8080-exec-10] DEBUG o.h.e.t.spi.AbstractTransactionImpl - committing
1866720 [http-nio-8080-exec-10] TRACE org.hibernate.internal.SessionImpl - before transaction completion
1866740 [http-nio-8080-exec-10] DEBUG o.h.e.t.i.jdbc.JdbcTransaction - committed JDBC Connection
1866740 [http-nio-8080-exec-10] DEBUG o.h.e.t.i.jdbc.JdbcTransaction - re-enabling autocommit
1866763 [http-nio-8080-exec-10] TRACE o.h.e.t.i.TransactionCoordinatorImpl - after transaction completion
1866763 [http-nio-8080-exec-10] TRACE org.hibernate.internal.SessionImpl - after transaction completion
1866763 [http-nio-8080-exec-10] TRACE org.hibernate.internal.SessionImpl - Setting flush mode to: AUTO
1866763 [http-nio-8080-exec-10] TRACE org.hibernate.internal.SessionImpl - Closing session
1866764 [http-nio-8080-exec-10] TRACE o.h.e.j.i.JdbcCoordinatorImpl - Closing JDBC container [org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl@6dc5a3df]
1866764 [http-nio-8080-exec-10] TRACE o.h.e.j.i.LogicalConnectionImpl - Closing logical connection
1866764 [http-nio-8080-exec-10] DEBUG o.h.e.j.i.LogicalConnectionImpl - Releasing JDBC connection
1866764 [http-nio-8080-exec-10] DEBUG o.h.e.j.i.LogicalConnectionImpl - Released JDBC connection

另外,我没有启用任何缓存选项。

正如您在上面看到的,正在获取 stockoption 集合,但没有插入到 stock 对象中。


更新

我原始帖子中的资本化股票和期权是查找和替换错误.. 抱歉..

我写了一个绕过弹簧数据的简单类,结果它工作了!实体加载没有任何问题。

我认为我在 Spring 数据配置方面做错了(可能是)。但不确定。

以下是使用相同映射的简单(常规休眠 DAO 样式):

@Repository
public class NewStock {

    @Autowired
    private SessionFactory  sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public StockEntity retrieveStock(String planNum) {

        Session session = sessionFactory.openSession();
        session.beginTransaction();
        List<StockEntity> stockList = session
                                .createQuery("from StockEntity where planNum = '" +
                                        planNum+ "'")
                                        .list();
        session.close();


        return stockList.get(0);

    }

}

请帮助找出根本原因。

【问题讨论】:

  • 检查我的答案,看看是否有帮助
  • Chaitanya 和 Michal.. 对大写字母的原始帖子感到抱歉。经过更多测试后,他的问题似乎来自 Spring Data。

标签: java spring hibernate spring-data


【解决方案1】:

请尝试更改

 private StockEntity Stock;

进入

private StockEntity stock;

【讨论】:

    【解决方案2】:

    当你声明字段和对应的getter和setter方法时,你必须遵循Java bean naming conventions

    StockEntity.java类中,属性Options应该是options,它应该以小写字母开头。

    同样适用于您的其他实体 - StockOptionEntity.java 类属性 Stock 应为 stock

    现在问题来了,根据日志,它有以下消息:

    1854774 [http-nio-8080-exec-10] TRACE o.h.e.loading.internal.LoadContexts - 
    Collection [CollectionKey[com.firstx.db.entity.base.StockEntity.options#d97]] not 
    located in load context
    

    此消息表示休眠无法在 StockEntity 类中找到名为 options 的属性。因此,即使 hibernate 获得了 StockOptionEntity 的记录,因为它没有找到它只是忽略它的属性。

    要解决此问题,只需遵循 Java bean 命名约定。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      相关资源
      最近更新 更多