相关疑难解决方法(0)

如何解决"未能懒散地初始化角色集合"的Hibernate异常

我有这个问题:

org.hibernate.LazyInitializationException:懒得初始化角色集合:mvc3.model.Topic.comments,没有会话或会话被关闭

这是模型:

@Entity
@Table(name = "T_TOPIC")
public class Topic {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;

    @ManyToOne
    @JoinColumn(name="USER_ID")
    private User author;

    @Enumerated(EnumType.STRING)    
    private Tag topicTag;

    private String name;
    private String text;

    @OneToMany(mappedBy = "topic", cascade = CascadeType.ALL)
    private Collection<Comment> comments = new LinkedHashSet<Comment>();

    ...

    public Collection<Comment> getComments() {
           return comments;
    }

}
Run Code Online (Sandbox Code Playgroud)

调用模型的控制器如下所示:

@Controller
@RequestMapping(value = "/topic")
public class TopicController {

    @Autowired
    private TopicService service;

    private static final Logger logger = LoggerFactory.getLogger(TopicController.class);


    @RequestMapping(value = "/details/{topicId}", method = RequestMethod.GET)
    public ModelAndView …
Run Code Online (Sandbox Code Playgroud)

java spring jsp hibernate spring-mvc

340
推荐指数
21
解决办法
46万
查看次数

Hibernate:LazyInitializationException:懒得初始化一个角色集合.无法初始化代理 - 没有会话

我有下一个错误: nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.example.Model.entities, could not initialize proxy - no Session

我的Model实体:

class Model {
...
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "model", orphanRemoval = true)
    @Cascade(CascadeType.ALL)
    @Fetch(value = FetchMode.SUBSELECT)
    public Set<Entity> getEntities() {
        return entities;
    }

    public void addEntity(Entity entity) {
        entity.setModel(this);
        entities.add(entity);
    }

}
Run Code Online (Sandbox Code Playgroud)

我有一个服务类:

@Service
@Transactional
class ServiceImpl implements Service {
    @Override
    public void process(Model model) {
        ...
        model.addEntity(createEntity());
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用其他服务方法调用服务:

@Override
@JmsListener(destination = …
Run Code Online (Sandbox Code Playgroud)

java spring hibernate jpa spring-transactions

12
推荐指数
2
解决办法
4万
查看次数

标签 统计

hibernate ×2

java ×2

spring ×2

jpa ×1

jsp ×1

spring-mvc ×1

spring-transactions ×1