控制器中没有LazyInitializationException

时间:2016-12-22 09:56:18

标签: hibernate spring-boot spring-data-jpa lazy-loading postgresql-9.4

在我的项目中,我使用Spring Boot和Hibernate 5以及Postgresql 9.4。现在我遇到了问题。我与 LAZY 获取 @OneToMany 关系。当我尝试在事务之外获取此集合时,抛出无异常。对我而言,这不是一个好的行为 - 我期待没有抛出的LazyInitializationException。 Spring Boot项目是新的和干净的。到目前为止,一切都设置为默认值。

这是我的代码:

域类:

@Entity
public class Company {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    @OneToMany(mappedBy="company",orphanRemoval=true,cascade=CascadeType.ALL)
    private List<Store> stores = new ArrayList<>();

    // getters and setters...
}

@Entity
public class Store {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    @Column(nullable=false)
    private String name;
    @ManyToOne
    @JoinColumn(nullable = false, name = "company_id")
    private Company company;

    // getters and setters
}

服务层:

@Service
@Transactional
public class CompanyService {
    @Autowired
    private CompanyRepository companyRepository;

    public Company getCompany() {
        Company company = companyRepository.findOne(1000L);
        return company;
    }
}

控制器层:

@RestController
@RequestMapping("/company")
public class CompanyResource {
    @Autowired
    private CompanyService companyService;

    @GetMapping
    public ResponseEntity<?> getCompany() {
        Company company = companyService.getCompany();
        // HERE I WOULD EXPECT LazyInitializationException
        String storeName = company.getStores().get(0).getName();
        // But storeName is normally filled and resource responds 200
        return new ResponseEntity<>(HttpStatus.OK);
    }
}

application.yml

spring:
    datasource:
        driverClassName: org.postgresql.Driver
        url: url_to_database
        username: something
        password: something
    jpa:
        database: POSTGRESQL
        hibernate:
            ddl-auto: create-drop

将Hibernate enable_lazy_load_no_trans 属性设置为默认值为false。我也尝试启用show-sql,当我调试时,我可以看到hibernate在 company.getStores()。get(0).getName()执行期间执行SQL选择。 有谁知道怎么假装这个?我想在事务之外获得延迟加载异常。

0 个答案:

没有答案