如何使用Spring数据JPA(JPARepository)实现延迟加载?

问题描述 投票:3回答:1

我使用Spring Data JPA和Hibernate作为提供者。我创建了几个扩展到JPARepository<Entity,Serializable>类的Repository类。我现在失败了,当我拿起一个实体时,它带来了附加/连接的实体!哪些是通过@OneToOne @OneToMany等连接的。我怎样才能避免获取那些连接的实体? 我尝试过@OneToMany(fetch=FetchType.LAZY)等但仍然没有运气。以下是我的java代码: 知识库

public interface TicketRepository extends JpaRepository<Ticket, Integer>{

}  

票务实体

@Entity
@Table(name = "tbl_tickets")
public class Ticket {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;

    @Column(name = "customer", nullable = false, length = 256)
    private String customer;


    @OneToOne(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
    @JoinColumn
    private User creator; 

    // ... other properties
}  

服务

@Service
public class TicketService {

  public Ticket save(Ticket obj,String id) {
       User user = userService.findById(Integer.valueOf(id));
       obj.setCreator(user);
       Ticket savedTicket = ticketRepository.save(obj);
   }
}  

savedTicket总是提取用户实体,我不想这样做。我怎么能实现这个目标?

谢谢

java spring hibernate spring-mvc annotations
1个回答
0
投票

让懒惰加载处理可空的一对一映射,你需要让hibernate做Compile time instrumentation并添加@LazyToOne(value = LazyToOneOption.NO_PROXY)到一对一的关系。

@OneToOne(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
@JoinColumn
@LazyToOne(value = LazyToOneOption.NO_PROXY)
private User creator;

希望这会奏效。

© www.soinside.com 2019 - 2024. All rights reserved.