spring data jpa getOne throw LazyInitializationException 和 findBy not [英] spring data jpa getOne throw LazyInitializationException and findBy not

查看:18
本文介绍了spring data jpa getOne throw LazyInitializationException 和 findBy not的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 spring 数据 jpa,这是我的示例:

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;
..}

test1 将抛出LazyInitializationException:无法初始化代理 - 没有会话",但如果我使用 userRepository.findByUserName("aa").getUserName() 就可以了.虽然问题可以通过添加@Transactional来解决,但我想知道这背后的区别和原因.我在 https://stackoverflow.com/a/34385219/4652536 中找到了 anwser 的一部分,但是 findByUserName 中的事务如何工作?

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?

推荐答案

getOne 为您提供参考,但不是实际实体.Get one 不会从数据库中获取对象.它只是使用您指定的 ID 创建一个对象.

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.

如果您想要来自数据库的实体,请使用 findById .

If you want the entity from the DB use findById .

这篇关于spring data jpa getOne throw LazyInitializationException 和 findBy not的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆