提问者:小点点

Spring数据 jpa getOne throw LazyInitializationException and findBy not


我使用Spring data jpa,这是我的示例:

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:cannot initialize proxy-no Session”,但如果我使用userRepository.findByUserName(“aa”).getUserName()就可以了。虽然可以通过添加@Transactional来解决问题,但我想知道其中的区别和原因
我在https://stackoverflow.com/a/34385219/4652536,但findByUserName中的事务性如何工作?


共1个答案

匿名用户

getOne为您获取引用,但不是实际实体。get one不会从DB中获取对象。它只是使用您指定的ID创建一个对象。

如果您想从数据库中获取实体,请使用< code>findById。