14

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?

yuxh
  • 924
  • 1
  • 9
  • 23
  • Would you also provide User entity? – Sepehr GH Mar 03 '18 at 06:05
  • I update the question,the userName is common, I am not sure anything related to other field? – yuxh Mar 03 '18 at 07:52
  • Have you read the javadoc of the methods. Have you read the javadoc of EntityManager.getReference(Class, Object) (which is in the "see also" of the javadoc of getOne())? What does it say? – JB Nizet Mar 03 '18 at 07:53

1 Answers1

23

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 .

Robert Niestroj
  • 15,299
  • 14
  • 76
  • 119