关于Spring的CrudRepository返回Entity的问题

各位高手,我在使用hibernate、jpa、springdata集成时遇到了如下的问题:

1.model

@Entity
@Tablename="group",schema="sc"
@Inheritancestrategy = InheritanceType.TABLE_PER_CLASS
public class Group extends AbstractEntity
{ ... @ElementCollectionfetch= FetchType.EAGER @NotNull @Columnname="user" @CollectionTablename = "t_group_users", schema = "sc", joinColumns = @JoinColumnname = "group_id" private List<String> users;
}

2.repository

public interface GroupRepository extends CrudRepository<Group, UUID>
{
}

3.config

@Configuration
@EnableJpaRepositoriesbasePackages = { "com.**.**" }
public class RepositoryTestConfig
{ @Bean public PlatformTransactionManager transactionManagerEntityManagerFactory emf { JpaTransactionManager transactionManager = new JpaTransactionManager; transactionManager.setEntityManagerFactoryemf; return transactionManager; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactoryDataSource dataSource { LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean; emfb.setDataSourcedataSource; emfb.setJpaVendorAdapterjpaVendorAdapter; emfb.setPackagesToScan"com.**.**.model"; Properties properties = new Properties; properties.setProperty"hibernate.hbm2ddl.auto", "create"; properties.setProperty"hibernate.format_sql", "true"; emfb.setJpaPropertiesproperties; return emfb; } @Bean public JpaVendorAdapter jpaVendorAdapter { HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter; adapter.setDatabaseDatabase.H2; adapter.setShowSqlfalse; adapter.setGenerateDdlfalse; adapter.setDatabasePlatform"org.hibernate.dialect.H2Dialect"; return adapter; } @Beanname = "testFunctionDataSource" public DataSource dataSource { DriverManagerDataSource dataSource = new DriverManagerDataSource; dataSource.setDriverClassName"org.h2.Driver"; dataSource.setUrl"jdbc:h2:~/test;INIT=CREATE SCHEMA IF NOT EXISTS sc"; dataSource.setUsername"sa"; dataSource.setPassword""; return dataSource; }
}

但我使用groupRepository.findOne方法时,users返回的是org.hibernate.collection.internal.PersistentBag类型,而不是ArrayList类型,请问是什么原因?

这个PersistentBag也是List的一种实现。Hibernate为啥不直接用ArrayList呢,因为它要支持懒加载,所以需要在类似ArrayList实现的基础上再包装一层。比如你调用List的get、size之类的方法,如果是懒加载,这个PersistentBag会先去把数据从数据库里面读进来,再做操作。如果是Eager的(就像你的代码设置的),那么就和一般的ArrayList没啥区别了。

对于用户来说,是没什么感受的,你就把他当List用就好。

发表评论

电子邮件地址不会被公开。 必填项已用*标注