简体   繁体   中英

FetchType.EAGER do not fetch object

My entities:

@Entity
@NoArgsConstructor
public class Company {

  @Id
  @Getter
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  @ManyToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "agent_id")
  private Agent agent;

}

and

@Entity
@NoArgsConstructor
public class Agent {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Getter
  private Long id;

  @Column(unique=true)
  @Getter
  private String name;
}

and problem method

@Transactional
public void update(Company entity) {
    Company existing = companyRepository.getOne(entity.getId());
    //System.out.println(existing.getAgent().getName());
    em.detach(existing);
    System.out.println(existing.getAgent()); // => org.hibernate.LazyInitializationException: could not initialize proxy - no Session
}

Last line causes LazyInitializationException, if I uncomment System.out.println(), everything works fine. So it looks like FetchType.LAZY. What am I doing wrong?

use findOne() method instead of getOne()

Method findOne() - internally call entity manager.getReference(...) .

The result of getReference() call it's returned object that is a Proxy and not the actual entity object type. So when you out of update() method you can't call proxy anymore.

I recommend you to read about How does a JPA Proxy work and how to unproxy it with Hibernate

The difference is that :

getOne() - lazy loaded

findOne() - is not

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM