java - jhipster LazyInitializationException

标签 java spring-boot jhipster

嗨,我有使用 jhipster 4.2.0 的微服务应用程序 这是我的资源类

import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;

/**
 * REST controller for managing Medida.
 */
@RestController
@RequestMapping("/api")
public class MedidaResource {

    private final Logger log = LoggerFactory.getLogger(MedidaResource.class);

    private static final String ENTITY_NAME = "medida";

    private final MedidaRepository medidaRepository;
    private final ClienteRepository clienteRepository;

    public MedidaResource(MedidaRepository medidaRepository, ClienteRepository clienteRepository) {
        this.medidaRepository = medidaRepository;
        this.clienteRepository = clienteRepository;
    }

    /**
     * POST  /medidas : Create a new medida.
     *
     * @param medida the medida to create
     * @return the ResponseEntity with status 201 (Created) and with body the new medida, or with status 400 (Bad Request) if the medida has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/medidas")
    @Timed
    public ResponseEntity<Medida> createMedida(@Valid @RequestBody Medida medida) throws URISyntaxException {
        log.debug("REST request to save Medida : {}", medida);
        if (medida.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new medida cannot already have an ID")).body(null);
        }
        Medida result = medidaRepository.save(medida);
        return ResponseEntity.created(new URI("/api/medidas/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /medidas : Updates an existing medida.
     *
     * @param medida the medida to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated medida,
     * or with status 400 (Bad Request) if the medida is not valid,
     * or with status 500 (Internal Server Error) if the medida couldnt be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/medidas")
    @Timed
    public ResponseEntity<Medida> updateMedida(@Valid @RequestBody Medida medida) throws URISyntaxException {
        log.debug("REST request to update Medida : {}", medida);
        if (medida.getId() == null) {
            return createMedida(medida);
        }
        Medida result = medidaRepository.save(medida);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, medida.getId().toString()))
            .body(result);
    }

    /**
     * GET  /medidas : get all the medidas.
     *
     * @return the ResponseEntity with status 200 (OK) and the list of medidas in body
     */
    @GetMapping("/medidas")
    @Timed
    public List<Medida> getAllMedidas() {
        log.info("------------------ REST request to get all Medidas");
        List<Medida> medidas = medidaRepository.findAll();
        return medidas;
    }

    /**
     * GET  /medidas/medidas : get all the medidas por cliente.
     *
     * @return the ResponseEntity with status 200 (OK) and the list of medidas in body
     */
    @GetMapping("/medidas/cliente/{id}")
    @Timed
    public List<Medida> getAllMedidasCliente(@PathVariable Long id) {
        log.debug("REST request to get all Medidas");
        log.info("ID de cliente:" + id);
        Cliente cliente = clienteRepository.getOne(id);
        log.info("Cliente encontrado: "+ cliente);
        List<Medida> medidas = medidaRepository.findAllByCliente(cliente);
        return medidas;
    }

    /**
     * GET  /medidas/:id : get the "id" medida.
     *
     * @param id the id of the medida to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the medida, or with status 404 (Not Found)
     */
    @GetMapping("/medidas/{id}")
    @Timed
    public ResponseEntity<Medida> getMedida(@PathVariable Long id) {
        log.debug("REST request to get Medida : {}", id);
        Medida medida = medidaRepository.findOne(id);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(medida));
    }

    /**
     * DELETE  /medidas/:id : delete the "id" medida.
     *
     * @param id the id of the medida to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/medidas/{id}")
    @Timed
    public ResponseEntity<Void> deleteMedida(@PathVariable Long id) {
        log.debug("REST request to delete Medida : {}", id);
        medidaRepository.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

}

这个错误发生在咨询API:http://localhost:9060/anelapi/api/medidas/cliente/1

2017-04-10 15:48:23.425 DEBUG 10068 --- [  XNIO-2 task-4] c.a.clothes.web.rest.MedidaResource      : REST request to get all Medidas
2017-04-10 15:48:23.429  INFO 10068 --- [  XNIO-2 task-4] c.a.clothes.web.rest.MedidaResource      : ID de cliente:1
2017-04-10 15:48:23.435 ERROR 10068 --- [  XNIO-2 task-4] c.a.clothes.aop.logging.LoggingAspect    : Exception in com.anelsoftware.clothes.web.rest.MedidaResource.getAllMedidasCliente() with cause = 'NULL' and exception = 'could not initialize proxy - no Session'

org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:146)
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:259)
    at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:73)
    at com.anelsoftware.clothes.domain.Cliente_$$_jvstc20_0.toString(Cliente_$$_jvstc20_0.java)
    at java.lang.String.valueOf(Unknown Source)
    at java.lang.StringBuilder.append(Unknown Source)
    at com.anelsoftware.clothes.web.rest.MedidaResource.getAllMedidasCliente(MedidaResource.java:106)

如果我尝试http://localhost:9060/anelapi/api/medidas这个工作没问题

希望你的帮助,谢谢

最佳答案

如果您想使用关系调用 2 个存储库,则应通过使用 @Transactional 注释 getAllMedidasCliente() 将它们包含在同一事务中。

更好的是,引入一个客户端服务来处理事务方面的问题,顺便说一句,这是 yo jhipster:entity 提出的选项之一。

此外,您可能只想调用 clienteRepository 并启用 JPA eager fetching 以通过 cliente 获取所有 medidas。

关于java - jhipster LazyInitializationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43330963/

相关文章:

java - Spring Boot自定义登录页面显示404

jhipster - 自定义 JHipster

java - 将 ArrayList 分成具有特定元素数量的更小的 ArrayList

java - java中的子菜单问题

java - 使用 Prometheus 监控 Spring Boot 应用程序

hibernate - 使用 Spring Boot 2.1+ 为 Hibernate 配置缓存

java - 用java制作Jhipster REST客户端

javascript - 使用 Jhipster 进行表单验证

java - Java排序中的链表实现不起作用

java - 使用 java 反射将派生对象传递到需要父类(super class)的方法中?