FetchType = Lazy和optional = false在JPA中不起作用

时间:2016-09-27 19:51:33

标签: java spring hibernate jpa

我在帐户实体中使用多对一的映射

@ManyToOne(fetch = FetchType.LAZY,optional = false)
    @JoinColumn(name = "CONTACT_ID", referencedColumnName = "CONTACT_ID", nullable = false)
    private Contact Contact;

在我的DAO中,我正在检索数据:

entitymanager.createQuery("SELECT v FROM Account v").getResultList();

虽然我正在使用optional = fasle and fetchType = Lazy。我看到它正在运行所有查询并检索引用的表数据。

我正在使用春季靴子。以下是我的Entitymanager配置

@Configuration
@EnableTransactionManagement
public class DatabaseConfig {


  @Autowired
  private Environment env;

  @Autowired
  private DataSource dataSource;

  @Autowired
  private LocalContainerEntityManagerFactoryBean entityManagerFactory;  


  @Bean
  public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    /*dataSource.setDriverClassName(env.getProperty("db.driver"));*/
    dataSource.setUrl(env.getProperty("db.url"));
    dataSource.setUsername(env.getProperty("db.username"));
    dataSource.setPassword(env.getProperty("db.password"));
    return dataSource;
  }


  @Bean
  public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean entityManagerFactory =
        new LocalContainerEntityManagerFactoryBean();

    entityManagerFactory.setDataSource(dataSource);
    entityManagerFactory.setPackagesToScan(env.getProperty("entitymanager.packagesToScan"));
    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    entityManagerFactory.setJpaVendorAdapter(vendorAdapter);
    Properties additionalProperties = new Properties();
   // additionalProperties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
    additionalProperties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
   // additionalProperties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
    additionalProperties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
    entityManagerFactory.setJpaProperties(additionalProperties);
    return entityManagerFactory;
  }

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

  @Bean
  public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
    return new PersistenceExceptionTranslationPostProcessor();
  }

在application.properties

hibernate.hbm2ddl.auto: update
hibernate.dialect: org.hibernate.dialect.Oracle12cDialect
hibernate.show_sql: true

1 个答案:

答案 0 :(得分:0)

试试这个:

使用 @JsonIgnore ,您已在两个实体之间给出了关系。

  

@JsonIgnore:因为Spring Data REST会忽略那些字段或getter   标有@JsonIgnore注释。