0

I have a contract entity which has oneToOne mapping with generatorState entity

I save one contract, it works and save the contract and the generatorState However when I get the contract in Postman I have the details of the generatorState while I try to set it up as LAZY

Can someone please shed some lights on how to get the contract entity with/without the generatorState detailled

Main

     @Override
    public void run(String... args) throws Exception {

        Contract c1 = new Contract (60,"TSTE");

//        GeneratorState gs = new GeneratorState(60,100);
//        c.setGeneratorState(gs);
//
//        contractRepository.save(c);
//        Contract c2 = contractRepository.findById(60).get();
//        System.out.println("coucou");
 
    }

Contract entity

@Entity
@Data
@NoArgsConstructor
@Table(name="contracts")
public class Contract {

    @Id
    int id;

    String symbol;

    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name ="id")
    private GeneratorState generatorState;

    public Contract(int id, String symbol) {
        this.id = id;
        this.symbol = symbol;
    }

    @JsonIgnore
    @CreationTimestamp
    @Column(nullable = false, updatable = false, columnDefinition = "TIMESTAMP WITH TIME ZONE")
    private ZonedDateTime createdOn;


    @JsonIgnore
    @UpdateTimestamp
    @Column(nullable = false, columnDefinition = "TIMESTAMP WITH TIME ZONE")
    private ZonedDateTime updatedOn;



}

GeneratorState

@Entity
@Table(name="state_generator")
@NoArgsConstructor
public class GeneratorState {

    @Id
    int generatorId;

    public int getGeneratorId() {
        return generatorId;
    }

    public double getLastPrice() {
        return lastPrice;
    }

    double lastPrice;

    @JsonIgnore
    @OneToOne(mappedBy = "generatorState")
    Contract contract;

    public GeneratorState(int generatorId, double lastPrice) {
        this.generatorId = generatorId;
        this.lastPrice = lastPrice;
    }
}

enter image description here

matel
  • 425
  • 5
  • 12
  • Does this answer your question? [JPA Lazy loading is not working in Spring boot](https://stackoverflow.com/questions/55702642/jpa-lazy-loading-is-not-working-in-spring-boot) – Michael Schönbauer Jul 11 '23 at 06:06

1 Answers1

2

from the documentation, we find out that FetchType.LAZY means, that data CAN be lazily fetched.

It does not enforce that it will be lazily fetched, the decision when an entity is delivered as a whole is taken by the framework, and these decision usually make good sense.

Especially in your case, with a 1:1 relationship, the framework will deliver the entity expanded in most cases.

Easiest way to force it to be lazy is to make it 1:n. (not recommending that tho)

For more information look at that blog

There are some ways to force it to use Lazy loaded.

Also, this is maybe a duplicate of this question