我使用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: could not initialize proxy - no Session"的异常,但如果我使用userRepository.findByUserName("aa").getUserName()就不会。虽然可以通过添加@Transactional来解决问题,但我想知道这两种方式的区别和原因。
我在https://dev59.com/N5Lea4cB1Zd3GeqPz0Pr#34385219中找到了部分答案,但是@Transactional在findByUserName中是如何起作用的?