Spring Boot JPA Repository Fetch Join

时间:2018-03-07 16:51:53

标签: java spring hibernate spring-boot spring-data-jpa

我有一个Java 8 Spring Boot应用程序,它使用Jpa-Hibernate与我们的数据库连接。我遇到了在某些情况下让存储库获取连接复杂对象的问题。

这是我的实体对象:

@Entity
@Table(name = "Foo", schema = "dbo")
public class Foo implements Serializable {
    private static final long serialVersionUID = 1L;

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

    @ManyToOne
    @JoinColumn(name = "FooBId")
    private FooB fooB;

    @Column(name = "AccountNumber")
    private String accountNumber;

    //getters and setters
}

这是我的回购:

public interface FooRepository extends JpaRepository<Foo, Integer> {
}

@Repository
public class HibernateFooRepository extends AbstractJpaRepository<Foo, Integer> implements FooRepository {
    public HibernateFooRepository(@Qualifier("emFactory") EntityManager em) {
        super(Foo.class, em);
    }
}

最后我的控制器:

@RestController
@RequestMapping("/foo")
public class FooController {
    private final FooRepository fooRepository;

    public FooController(final FooRepository fooRepository) {
        this.fooRepository = fooRepository;
    }

    @GetMapping(produces = "application/json")
    public ResponseEntity<List<Foo>> getFoos() {
        List<Foo> foos = fooRepository.findAll();
        return ResponseEntity.ok(foos);
    }

    @PostMapping(value = "/create", produces = "application/json")
    public ResponseEntity<Foo> createFoo(@RequestBody Foo foo) {
        Foo saveEntity = fooRepository.save(foo);
        return ResponseEntity.ok(saveEntity);
    }
}

出于某种原因,GET方法完全正常。它通过Id获取FooB上的所有Foo对象和连接。但是,create方法不起作用。

我发现当我作为第一个回购电话进行.findOne时,它就可以了。但是,如果我执行任何其他repo操作,则获取加入将不起作用。例如,如果我这样做:

repo.findOne(1); //Fetches Foo, joins on FooBId and fetches fooB
repo.save(...);

但如果我这样做:

repo.save(...);
repo.findOne(1); //Will not join on FooBId and therefore fooB will be NULL

如果您先调用任何其他repo操作,我不明白为什么repo无法获取fooB。我正在使用org.springframework.data.jpa.repository.JpaRepository

我做错了什么?

0 个答案:

没有答案