代码之家  ›  专栏  ›  技术社区  ›  Kirill

为什么@Transactional在某些情况下会忽略延迟获取

  •  1
  • Kirill  · 技术社区  · 5 年前

    (我检查了这方面的问题——他们问的问题不一样)。

    我有一门标准课 具有 获取类型。懒惰的 在“地址”字段。

    @Entity
    public class Person {
    
        @Id
        @GeneratedValue
        private int id;
    
        private String firstName;
        private String lastName;
    
        @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
        @JoinColumn(name = "person_id")
        private List<Address> addresses;
    
        //...constructors, getters and setters
    
    }
    

    下面的方法生成 对地址表和人员表的SQL查询 之前 通过getAddresses()方法初始化地址。我不明白为什么,因为使用 获取类型。懒惰的 .

    @Transactional
    public void testLazyLoadingTransactional() throws Exception {
    
        Optional<Person> person = personRepository.findById(1); 
    
        System.out.println(""); //here I set a breakpoint 
    
        // here I see two SQL queries in a console
        // "select person ..." and "select address ..."
    
        if (person.isPresent()) {
            System.out.println(person.get().getAddresses());
        } else {
            throw new NotFoundException("Person not found");
        }
    }
    

    我还发现,如果在方法的主体中 不要 使用getAddresses()之后,我只得到了一个针对Person表的SQL查询。

    如果是的话

    @Transactional
    public void testLazyLoadingTransactional() throws Exception {
        Optional<Person> person = personRepository.findById(1);  
    }
    

    然后我在控制台中看到一个SQL查询“select person…”。

    为什么在第一种情况下会忽略延迟获取?

    0 回复  |  直到 5 年前