1

jHispster項目在控制器中用於避免LazyInitializationException的設置是什麼?爲什麼jHipster項目在Controller中沒有得到LazyInitializationException?

我的控制器:

@GetMapping("/citys") 
@Timed 
public ResponseEntity<List<City>> getAllCidades(@ApiParam Pageable pageable) { 
    log.debug("REST request to get a page of Citys"); 
    Page<City> page = cityService.findAll(pageable); 
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/citys"); 
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); 
} 

城市實體:

@Entity 
@Table(name = "city") 
public class Cidade implements Serializable { 

    private static final long serialVersionUID = 1L; 

    @Id 
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") 
    @SequenceGenerator(name = "sequenceGenerator") 
    private Long id; 

    @NotNull 
    @Column(name = "name", nullable = false) 
    private String name; 

    @ManyToOne(optional = false) 
    @NotNull 
    private State state; 
... 
// gets and sets 
} 

回答

3

這實際上是一個春天的引導,而不是JHipster選項。具體屬性名稱爲spring.jpa.open-in-view。它默認爲true,這會導致Spring Boot註冊OpenEntityManagerInViewInterceptor

來源:Spring Boot properties reference

1

As jdubois mentioned 這是「正常的」使用JPA,如果你訪問一個事務之外懶惰的關係。

通常,您應該使用服務層和事務。例如,UserService類非常適合完成這項工作。

我們剩下的唯一兩個選項是:

在查看模式中使用打開的會話。我不喜歡它,因爲它隱藏了開發者的問題:他應該正確使用JPA。

讓人們正確使用JPA:這就是爲什麼JHipster不會糾正這個問題。通過使用熱切的關係或使用事務和Spring服務,您有很多方法可以解決此問題。在我看來,這就是JPA應該如何使用,以及Spring控制器。

相關問題