java - 关于Spring的CrudRepository返回Entity的问题
大家讲道理
大家讲道理 2017-04-18 09:51:04
0
1
458

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

1.model

@Entity
@Table(name="group",schema="sc")
@Inheritance(strategy =  InheritanceType.TABLE_PER_CLASS)
public class Group extends AbstractEntity
{
    ...
    
    @ElementCollection(fetch= FetchType.EAGER)
    @NotNull
    @Column(name="user")
    @CollectionTable(name = "t_group_users", schema = "sc", joinColumns = @JoinColumn(name = "group_id"))
    private List<String> users;
}

2.repository

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

3.config

@Configuration
@EnableJpaRepositories(basePackages = { "com.**.**" })
public class RepositoryTestConfig
{
    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf)
    {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);

        return transactionManager;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource)
    {
        LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
        emfb.setDataSource(dataSource());
        emfb.setJpaVendorAdapter(jpaVendorAdapter());
        emfb.setPackagesToScan("com.**.**.model");

        Properties properties = new Properties();
        properties.setProperty("hibernate.hbm2ddl.auto", "create");
        properties.setProperty("hibernate.format_sql", "true");
        emfb.setJpaProperties(properties);

        return emfb;
    }

    @Bean
    public JpaVendorAdapter jpaVendorAdapter()
    {
        HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
        adapter.setDatabase(Database.H2);
        adapter.setShowSql(false);
        adapter.setGenerateDdl(false);
        adapter.setDatabasePlatform("org.hibernate.dialect.H2Dialect");

        return adapter;
    }

    @Bean(name = "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类型,请问是什么原因?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回覆(1)
巴扎黑

這個PersistentBag也是List的一種實作。 Hibernate為啥不直接用ArrayList呢,因為它要支援懶加載,所以需要在類似ArrayList實現的基礎上再包裝一層。例如你呼叫List的get、size之類的方法,如果是懶加載,這個PersistentBag會先去把資料從資料庫裡面讀進來,再做操作。如果是Eager的(就像你的程式碼設定的),那麼就和一般的ArrayList沒啥區別了。

對使用者來說,是沒什麼感受的,你就把他當List用就好。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板