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

时间:2015-01-04 11:36:41

标签: java spring hibernate spring-mvc annotations

我使用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总是提取用户实体,我不想这样做。我怎么能做到这一点?
enter image description here

由于

1 个答案:

答案 0 :(得分:0)

让Lazy加载处理可空的一对一映射,让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;

希望这会奏效。