当前位置: 首页 > 知识库问答 >
问题:

JsonMappingException:无法初始化代理-无会话

澹台欣怿
2023-03-14

我正在构建一个使用并返回JSON的RESTful Web服务。当我试图通过服务层从数据库中获取ESBRATING对象时,遇到以下堆栈跟踪。然而,当我将Spring数据JPA存储库直接注入控制器并使用它来获取ESRBRating by ID时,它工作得很好。但是,当通过服务层调用时,它不起作用。我在下面提供了堆栈跟踪和代码。有人能向我解释一下为什么在通过服务层时会发生这种情况,而在直接通过Spring数据JPA存储库时却不会发生这种情况吗?如何解决此问题?

堆栈跟踪

Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:165)
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286)
    at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
    at net.jkratz.igdb.model.ESRBRating_$$_jvst319_0.getId(ESRBRating_$$_jvst319_0.java)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:466)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:639)
    ... 76 more

控制器

@RestController
@RequestMapping(produces = "application/json", value="/esrbrating")
public class ESRBRatingController {

    @Inject
    ESRBRatingService esrbRatingService;

    @Inject
    ESRBRatingRepository esrbRatingRepository;

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * Returns all ESRB ratings in database
     * 
     * @return List of ESRBRating objects
     * @see ESRBRating
     */
    @RequestMapping(value = {"","/"}, method = RequestMethod.GET)
    public ResponseEntity<List<ESRBRating>> getESRBRatings() {
        List<ESRBRating> esrbRatings = esrbRatingService.getESRBRatings();
        return new ResponseEntity<>(esrbRatings, HttpStatus.OK);
    }

    /**
     * Returns a single ESRB rating object if exists, otherwise returns HTTP status code 404
     *
     * @param id ID of the ESRB Rating
     * @return ESRB Rating when found
     * @see ESRBRating
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ResponseEntity<?> getUser(@PathVariable("id") Long id) {
        logger.debug("Attempting to fetch ESRB rating with ID: {}", id);
        ESRBRating esrbRating = esrbRatingService.getESRBRating(id);
        //ESRBRating esrbRating = esrbRatingRepository.findOne(id);

        if (esrbRating == null) {
            return new ResponseEntity<>("ESRB Rating not found", HttpStatus.NOT_FOUND);
        } else {
            return new ResponseEntity<>(esrbRating, HttpStatus.OK);
        }
    }

}

服务

@Service
@Transactional
public class ESRBRatingServiceImpl implements ESRBRatingService {

    @Value("#{paging.games.maxPageSize}")
    private static int DEFAULT_PAGE_SIZE;

    @Value("#{paging.games.maxPageSize}")
    private static int MAX_PAGE_SIZE;

    @Inject
    private ESRBRatingRepository esrbRatingRepository;

    @Override
    public List<ESRBRating> getESRBRatings() {
        List<ESRBRating> ratings =  esrbRatingRepository.findAll();
        return ratings;
    }

    @Override
    public ESRBRating getESRBRating(Long id) {
        return esrbRatingRepository.getOne(id);
    }

    @Override
    public ESRBRating saveESRBRating(ESRBRating esrbRating) {
        return esrbRatingRepository.saveAndFlush(esrbRating);
    }

    @Override
    public boolean deleteESRBRating(Long id) {
        esrbRatingRepository.delete(id);
        return true;
    }
}

存储库

package net.jkratz.igdb.repository;

import net.jkratz.igdb.model.ESRBRating;

import org.springframework.data.jpa.repository.JpaRepository;

public interface ESRBRatingRepository extends JpaRepository<ESRBRating, Long> {

}

模型

@Entity
@Table(name = "esrb_rating", schema = "igdb")
@JsonIgnoreProperties(ignoreUnknown = true)
public class ESRBRating implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @NotNull
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false)
    private Long id;

    @NotNull
    @Size(min = 1, max = 255)
    @Column(name = "title", nullable = false, length = 255)
    private String title;

    @Size(max = 65535)
    @Column(length = 65535)
    private String description;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "esrbRating")
    private List<Game> games;

    public ESRBRating() {
    }

    public ESRBRating(Long id, String title, String description) {
        this.id = id;
        this.title = title;
        this.description = description;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ESRBRating that = (ESRBRating) o;

        return Objects.equal(this.id, that.id) &&
                Objects.equal(this.title, that.title) &&
                Objects.equal(this.description, that.description);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(id, title, description);
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add("id", id)
                .add("title", title)
                .add("description", description)
                .toString();
    }
}

这个控制器代码工作正常,直接通过存储库。

@RestController
@RequestMapping(produces = "application/json", value="/esrbrating")
public class ESRBRatingController {

@Inject
ESRBRatingService esrbRatingService;

@Inject
ESRBRatingRepository esrbRatingRepository;

private Logger logger = LoggerFactory.getLogger(getClass());

/**
 * Returns all ESRB ratings in database
 * 
 * @return List of ESRBRating objects
 * @see ESRBRating
 */
@RequestMapping(value = {"","/"}, method = RequestMethod.GET)
public ResponseEntity<List<ESRBRating>> getESRBRatings() {
    List<ESRBRating> esrbRatings = esrbRatingService.getESRBRatings();
    return new ResponseEntity<>(esrbRatings, HttpStatus.OK);
}

/**
 * Returns a single ESRB rating object if exists, otherwise returns HTTP status code 404
 *
 * @param id ID of the ESRB Rating
 * @return ESRB Rating when found
 * @see ESRBRating
 */
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<?> getUser(@PathVariable("id") Long id) {
    logger.debug("Attempting to fetch ESRB rating with ID: {}", id);
    ESRBRating esrbRating = esrbRatingRepository.findOne(id);

    if (esrbRating == null) {
        return new ResponseEntity<>("ESRB Rating not found", HttpStatus.NOT_FOUND);
    } else {
        return new ResponseEntity<>(esrbRating, HttpStatus.OK);
    }
}

}

更新:

我听从了Randall Harleigh的建议,将反向集合设置为@JsonIgnore。然而,现在我得到了一个完全不同的堆栈跟踪。现在Jackson/Spring似乎不知道如何序列化ESBRATING。这方面有什么建议吗?

org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: net.jkratz.igdb.model.ESRBRating_$$_jvstb5c_0["handler"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: net.jkratz.igdb.model.ESRBRating_$$_jvstb5c_0["handler"])
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:238)
    at org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:208)
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:158)
    at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:138)
    at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:122)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:155)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: net.jkratz.igdb.model.ESRBRating_$$_jvstb5c_0["handler"])
    at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:59)
    at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:26)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:505)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:639)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:114)
    at com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:1887)
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:231)
    ... 72 more

更新2:

我最后在ESRBRating类上放了@Proxy(懒=假),现在它工作正常。但是我很好奇这会对性能产生什么样的影响?

@Entity
@Table(name = "esrb_rating", schema = "igdb")
@JsonIgnoreProperties(ignoreUnknown = false)
@Proxy(lazy = false)
public class ESRBRating implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @NotNull
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false)
    private Long id;

    @NotNull
    @Size(min = 1, max = 255)
    @Column(name = "title", nullable = false, length = 255)
    private String title;

    @Size(max = 65535)
    @Column(length = 65535)
    private String description;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "esrbRating")
    private List<Game> games;

    public ESRBRating() {
    }

    public ESRBRating(Long id, String title, String description) {
        this.id = id;
        this.title = title;
        this.description = description;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }


    @JsonIgnore
    public List<Game> getGames() {
        return games;
    }

    public void setGames(List<Game> games) {
        this.games = games;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ESRBRating that = (ESRBRating) o;

        return Objects.equal(this.id, that.id) &&
                Objects.equal(this.title, that.title) &&
                Objects.equal(this.description, that.description);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(id, title, description);
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add("id", id)
                .add("title", title)
                .add("description", description)
                .toString();
    }
}

按照要求,这里是游戏类

@Entity
@Table(name = "game", schema = "igdb",
        indexes = {@Index(name = "idx_game_title", columnList = ("title"), unique = false),
                @Index(name = "idx_game_developer", columnList = ("developer"), unique = false),
                @Index(name = "idx_game_publisher", columnList = ("publisher"), unique = false)})
@JsonIgnoreProperties(ignoreUnknown = true)
public class Game implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @NotNull
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false)
    private Long id;

    @NotNull
    @Size(min = 1, max = 255)
    @Column(name = "title", nullable = false, length = 255)
    private String title;

    @Size(max = 65535)
    @Column(name = "description", length = 65535)
    private String description;

    @Size(max = 255)
    @Column(name = "developer", length = 255)
    private String developer;

    @Size(max = 255)
    @Column(name = "publisher", length = 255)
    private String publisher;

    @NotNull
    @Size(max = 4)
    @Column(name = "players", nullable = false)
    private short players;

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

    @NotNull
    @Column(name = "release_date", nullable = false)
    @Temporal(TemporalType.DATE)
    private Date releaseDate;

    @Size(max = 255)
    @Column(name = "image", length = 255)
    private String image;

    @JoinColumn(name = "esrb_rating_id", referencedColumnName = "id", nullable = false)
    @ManyToOne(optional = false, fetch = FetchType.EAGER)
    private ESRBRating esrbRating;   

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "game")
    private List<GamePlatformMap> gamePlatformMap;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "game")
    private List<GameGenreMap> gameGenreMap;

    public Game() {

    }

    public Game(Long id, String title, String description, String developer,
            String publisher, short players, boolean cooperative,
            Date releaseDate, String image, ESRBRating esrbRating) {
        super();
        this.id = id;
        this.title = title;
        this.description = description;
        this.developer = developer;
        this.publisher = publisher;
        this.players = players;
        this.cooperative = cooperative;
        this.releaseDate = releaseDate;
        this.image = image;
        this.esrbRating = esrbRating;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getDeveloper() {
        return developer;
    }

    public void setDeveloper(String developer) {
        this.developer = developer;
    }

    public String getPublisher() {
        return publisher;
    }

    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

    public short getPlayers() {
        return players;
    }

    public void setPlayers(short players) {
        this.players = players;
    }

    public boolean isCooperative() {
        return cooperative;
    }

    public void setCooperative(boolean cooperative) {
        this.cooperative = cooperative;
    }

    public Date getReleaseDate() {
        return releaseDate;
    }

    public void setReleaseDate(Date releaseDate) {
        this.releaseDate = releaseDate;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public ESRBRating getEsrbRating() {
        return esrbRating;
    }

    public void setEsrbRating(ESRBRating esrbRating) {
        this.esrbRating = esrbRating;
    }

    @JsonIgnore
    public List<GamePlatformMap> getGamePlatformMap() {
        return gamePlatformMap;
    }

    public void setGamePlatformMap(List<GamePlatformMap> gamePlatformMap) {
        this.gamePlatformMap = gamePlatformMap;
    }

    @JsonIgnore
    public List<GameGenreMap> getGameGenreMap() {
        return gameGenreMap;
    }

    public void setGameGenreMap(List<GameGenreMap> gameGenreMap) {
        this.gameGenreMap = gameGenreMap;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Game that = (Game) o;

        return Objects.equal(this.id, that.id) &&
                Objects.equal(this.title, that.title) &&
                Objects.equal(this.description, that.description) &&
                Objects.equal(this.developer, that.developer) &&
                Objects.equal(this.publisher, that.publisher) &&
                Objects.equal(this.players, that.players) &&
                Objects.equal(this.cooperative, that.cooperative) &&
                Objects.equal(this.releaseDate, that.releaseDate) &&
                Objects.equal(this.image, that.image) &&
                Objects.equal(this.esrbRating, that.esrbRating);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(id, title, description, developer, publisher, players,
                cooperative, releaseDate, image, esrbRating);
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add("id", id)
                .add("title", title)
                .add("description", description)
                .add("developer", developer)
                .add("publisher", publisher)
                .add("players", players)
                .add("cooperative", cooperative)
                .add("releaseDate", releaseDate)
                .add("image", image)
                .add("esrbRating", esrbRating)
                .toString();
    }
}

共有3个答案

濮阳旭东
2023-03-14

@jsonIgnore注释可能会解决您的问题,但它会导致您最初设置为FetchType. LAZY的特定字段被完全忽略。这里给出了一个更好的选择https://stackoverflow.com/a/21760361/3609067

邹高峻
2023-03-14

首先根据jackson-core版本下载jackson-datatype-hibernate4-2.2.3.jar或更高版本。然后在配置文件中使用此代码,您可以使用获取策略LAZY而不会出现任何错误。

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module;


public class ApplicationConfig extends WebMvcConfigurerAdapter
{
public MappingJackson2HttpMessageConverter jacksonMessageConverter(){
    MappingJackson2HttpMessageConverter messageConverter = new  MappingJackson2HttpMessageConverter();

    ObjectMapper mapper = new ObjectMapper();
    //Registering Hibernate4Module to support lazy objects
    mapper.registerModule(new Hibernate4Module());

    messageConverter.setObjectMapper(mapper);
    return messageConverter;

}

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    //Here we add our custom-configured HttpMessageConverter
    converters.add(jacksonMessageConverter());
    super.configureMessageConverters(converters);
}
颛孙英才
2023-03-14

当您通过@Responsebody(或在您的情况下通过@RestController返回响应体)返回一个对象时,通常会发生这种情况,并且一个对象正在序列化,但在惰性集合中有尚未引用的子对象。当您在控制器中时,将不再有一个活动的事务可以方便地获取它们(就像您在@服务中启动的事务)。您可以使您的获取策略变得迫切,在仍处于事务中时通过引用引入集合,或者使您的惰性集合成为JSON瞬态集合。

 类似资料:
  • 我有一个LazyInitializationException问题,我不知道如何解决它。 之前的问题是我打电话的时候。getperson=null,但我修复了findProjectEmployeesWithinDates请求获取此人的调用。但当我调用“findProjectEmployeesWithinDates”时,我遇到了一个例外。查找项目员工的代码包括: 所以用debbug我看到: 它位于f

  • 我使用< code>spring-data-jpa与< code > spring-boot(v 2 . 0 . 0 . release),我刚刚在MySQL上写了一个CRUD演示,但是在运行时出现异常,源代码如下: 源码 User.java UserRepository.java 用户服务测试.java 应用程序.yml 例外详细信息 我尝试另一种方法,它可以成功运行。

  • 问题内容: 我有一个看起来像这样的错误: 无法初始化代理-没有会话 我正在使用java,hibernate和spring。尝试生成PDF文档时会出现此错误,我正在按照以下步骤即时生成它并存储在数据库中。 我通过POST方法向应用发送了请求。这将即时生成PDF并显示给用户。 在该请求之后,我发送了另一个请求,但是通过ajax发送了一个请求。这将生成相同的PDF,但会将其保存在数据库中。 该错误表明由

  • 我有一个应用程序,我正在扩展它以提供REST API。在主站点中一切正常,但当我尝试访问REST API时,我在异常日志中得到以下内容: 禁用延迟加载将解决此问题,但会导致不可接受的性能(加载时间从 200 毫秒到 22 秒)。我不知道如何处理这个问题。 我刚开始在ColdFusion中Rest,在我看来,CFC正在以一种不寻常的方式被处理。它们似乎没有被初始化(init方法似乎没有运行),现在看

  • 在我的Spring应用程序中,我实现了一个自定义的身份验证提供商,它使用服务来处理我的登录请求。身份验证提供程序如下: https://github.com/klebermo/webapp_horario_livre/blob/master/src/com/horariolivre/security/CustomAuthenticationProvider.java 我的服务级别是: https:

  • 问题内容: 我有2台物理服务器,我的Web应用程序命中该服务器由负载均衡器管理。我总是得到- org.hibernate.LazyInitializationException:无法初始化代理-没有会话 当其中一台服务器受到攻击而另一台服务器运行平稳而没有任何问题时。我有一个由应用程序启用和管理的本地托管缓存存储。仅当尝试从一个表访问一个特定的列时,才会发生此异常。不管选择哪个服务器,其余的操作都