简体   繁体   中英

How to fetch data before commit in Spring Data JPA?

I'm saving two entity related to each other. After it, I can get the first entity, but I get a NullPointerException when I try to get the second entity from the first entity. This is the example:

@Entity
@Table(name = "PARAMETRIZACION")
public class Parametrizacion {

    @Id
    @Column(name = "id_param", unique = true, nullable = false)
    private Integer idParam;

    @OneToMany(fetch = FetchType.LAZY)
    private List<Arreglo> listArreglo;
}

And

@Entity
@Table(name = "ARREGLO")
public class Arreglo {
    @Id
    @Column(name = "id_arreglo", unique = true, nullable = false)
    private Integer idArreglo;
}

And my Service:

@Service
@Repository
public class TestServiceImpl implements TestService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void methodTest(){
        ...
        parametrizacionRepository.saveAndFlush(parametrizacion);//Id=1
        ...
        arregloRepository.saveAndFlush(listArreglo);//Id=1

        Parametrizacion paramFetch = parametrizacionRepository.findById(1);
        Log.info("Param.Id=" + paramFetch.getIdParam());
        Log.info("Size=" + paramFetch.getListArreglo().size());
    }
}

The result for first log is: Param.Id=1 The result for second log is: NullPointerException

How can I get the full entity including his childrens? Only If I do this query after commit transaction I can get the data but I need Save data, Update data and Find data before do Commit on finish transaction.

Maybe there is a problem with the unidirectional relationship. Try adding some @ManyToOne field in the Arreglo class and declare how should they match by adding mappedBy="" to the @OneToMany annotation.

There are some nice examples how the relations should look like: https://en.wikibooks.org/wiki/Java_Persistence/OneToMany

What you are doing is saving parametrizacion and listArreglo separately. And this don't set any relation for parametrizacion with Arreglo. You have to set listArreglo to parametrizacion's listArreglo variable and save only parametrizacion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM