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

各位高手,我在使用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)
巴扎黑

이 PertantBag도 List를 구현한 것입니다. Hibernate는 왜 ArrayList를 직접 사용하지 않습니까? 지연 로딩을 지원해야 하기 때문에 유사한 ArrayList 구현을 기반으로 하는 다른 레이어로 래핑되어야 합니다. 예를 들어, List의 get, size 등의 메소드를 호출할 경우 지연 로딩인 경우 PerpersistBag는 먼저 데이터베이스에서 데이터를 읽은 후 작업을 수행합니다. Eager(코드에 의해 설정됨)인 경우 일반 ArrayList와 다르지 않습니다.

사용자 입장에서는 별 느낌이 없으니 그냥 List로 사용하세요.

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿