我正在将Spring BootSpring MessagingGson用于websocket连接并将消息发送到客户端。现在,在向模型中添加新字段并将其发送给客户端之后,我遇到了LazyInitializationException错误。

这是我的模型课:

@Entity
public class Vehicle {
    @Expose
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Expose
    private String name;

    //...
    //some other simple fields
    //...

    @Expose
    @ElementCollection(fetch = FetchType.LAZY)
    @CollectionTable(name = "vehicle_property_values", joinColumns = @JoinColumn(name = "vehicle_id"))
    @MapKeyColumn(name = "key")
    @Column(name="value")
    private Map<String, String> properties = new HashMap<>();
}


我正在使用GsonMessageConverter将对象转换为json并从https://github.com/Coding/WebIDE-Backend/blob/master/src/main/java/net/coding/ide/web/message/GsonMessageConverter.java发送给客户端

Converter可以正常工作,但是我已经将Map<String, String> properties添加到了我的Vehicle模型中,这是一个问题。我遇到异常:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.test.vehicles.model.Vehicle.properties, could not initialize proxy - no Session


GsonMessageConverter的第105行中

this.gson.toJson(payload, writer);


这是我在服务类中发送消息的方式:

@Service
@Transactional
class VehicleServiceImpl implements VehicleService {
    @Autowired
    VehicleRepository vehicleRepository; //JpaRepository
    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;

    private final ConcurrentLinkedDeque<Vehicle> pendingVehicles = new ConcurrentLinkedDeque<>();

    //..some other fields and methods irrelevant in this case

    //method called from controller
    @Override
    void addPendingVehicle(Vehicle vehicle) {
        //set some variables in vehicle
        vehicle = vehicleRepository.save(vehicle);
        pendingVehicles.add(vehicle);
    }

    @Scheduled(initialDelay = 60000, fixedRate = 60000)
    @Transactional
    void sendPendingVehicles() {
        if(pendingVehicles.size() > 0) {
            simpMessagingTemplate.convertAndSend("/topic/vehicles", pendingVehicles);
            pendingVehicles.clear();
        }
    }
}


这是我的WebSocket配置(仅非空方法):

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/queue", "/topic");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/testapp").setAllowedOrigins("*").withSockJS();
    }

    @Override
    public boolean configureMessageConverters(List<MessageConverter> converters) {
        Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        converters.add(new GsonMessageConverter().setGson(gson));
        return true;
    }
}


我不知道如何解决它。如何使其具有交易性?

最佳答案

我不需要在网络套接字消息中发送properties,因此创建了注释

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcludeWebSocketSerialization { }


并将ExclusionStrategy添加到我的Gson

.addSerializationExclusionStrategy(new ExclusionStrategy() {
    @Override
    public boolean shouldSkipField(FieldAttributes fieldAttributes) {
    return fieldAttributes.getAnnotation(ExcludeWebSocketSerialization.class) != null;
    }

    @Override
    public boolean shouldSkipClass(Class<?> aClass) {
    return false;
    }
})

10-04 10:14