Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring data jpa getOne throw LazyInitializationException and findBy not

I use spring data jpa ,here is my sample:

public interface UserRepository extends JpaRepository<User, Long> {

    User findByUserName(String userName);
....}

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserRepositoryTests {

    @Autowired
    private UserRepository userRepository;
    @Test
    public void test1(){
        String name = userRepository.getOne(3L).getUserName();
    }

}
@Entity
public class User extends Entitys implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue
    private Integer id;
    @Column(nullable = false, unique = true)
    private String userName;
..}

the test1 will throw "LazyInitializationException: could not initialize proxy - no Session",but if I use userRepository.findByUserName("aa").getUserName() will ok. Although the problem can be solved by add @Transactional, I want to know the difference and the reason behind this.
I find part of anwser in https://stackoverflow.com/a/34385219/4652536, but how transactional work in findByUserName?

like image 457
yuxh Avatar asked Mar 03 '18 02:03

yuxh


People also ask

What is difference between getOne and findById?

The calling findById() returns an eagerly fetched entity whereas Calling getOne() returns a lazily fetched entity.

What is difference between findById and getById?

As a consequence, findById() returns the actual object and getById returns a reference of the entity.

What does findById return in JPA?

Its findById method retrieves an entity by its id. The return value is Optional<T> . Optional<T> is a container object which may or may not contain a non-null value. If a value is present, isPresent returns true and get returns the value.

What is the difference between CrudRepository and JpaRepository?

Each of these defines its own functionality: CrudRepository provides CRUD functions. PagingAndSortingRepository provides methods to do pagination and sort records. JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.


Video Answer


1 Answers

getOne gets you a reference, but not the actual entity. Get one does noe fetch the object from the DB. It just creates an object with the ID you specified.

If you want the entity from the DB use findById .

like image 84
Robert Niestroj Avatar answered Oct 19 '22 03:10

Robert Niestroj