Spring data jpa fetch lazy


#1

@vlad
@eulseb
I have confused regarding below behavior in spring data jpa

@Entity
@Table(name = "T_STUDENT")
public class Student {

............
@OneToMany(cascade = CascadeType.ALL, fetch= FetchType.LAZY)
	@JoinColumn(name = "student_id")
	private List<Address> addresses;

.......................
}

even though it’s lazy when I tried to fetch address its load address object. My question why i am not getting LazyInitializeExceptiion. When i see logs it’s call db to test address object.

Thank you
Salman


#2

Maybe because of the default Open Session in View used by Spring Boot, which is a bad idea anyway.


#3

so if i set

spring.jpa.open-in-view=false

it will give lazyinitializationexception. right ?


#4

After you get out the @Transactional context and the EntityManager is closed, yes. Inside the transnational block, no.


#5

but i didn’t define it in @Transaction block. See below code

public void createPrivateMethod(StudentDTO studentDTO) {
		Student student = new Student();
		student.setName(studentDTO.getName());
		Address address = new Address();
		address.setCity(studentDTO.getAddress());
		List<Address> addressList = new ArrayList<>();
		addressList.add(address);
		address = new Address();
		address.setCity(studentDTO.getAddress() + "1");
		addressList.add(address);
		student.setAddress(addressList);
		this.studentRepository.save(student);
		List<Student> findAll = this.studentRepository.findAll();
		findAll.stream().forEach(s -> s.getAddress().forEach(Address::getCity));
	}

#6

Add a breakpoint and check the stacktrace for the TransactionInterceptor. If you see it, you are in a transactional block.


#7

ok will check and inform you tommrrow.

Thanks vlad


#8

Actually, since this is a Spring issue, you should address it on the Spring forum. Thanks.


#9

Yes it should be. Thanks vlad