0

Lab includes some servers. What I am trying to do is listing servers belongs to a lab. For example get servers which belongs to "abc" lab which its id is 1.

Following code gets all servers:

@RequestMapping(value = "servers", method = RequestMethod.GET)
public List<Server> list() {
    return serverRepository.findAll();
}

Entitiy:

public class Server {

    @Id
    @GeneratedValue
    @Column(name = "ID")
    private Long id;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="LAB_ID", referencedColumnName = "ID")
    private Lab lab;
}

Entitiy;

public class Lab {

    @Id
    @GeneratedValue
    @Column(name = "ID")
    private Long id;

    @NotNull
    @Column(name = "LAB_NAME")
    private String labName;

    @OneToMany
    private Set<Server> servers;
}

angular:

$scope.getServers= function () {
    $http.get('services/servers').then(function (response) {
        $scope.servers= response.data;
    });
};

Repository:

public interface ServerRepository extends JpaRepository<Server, Long>{

}
Can Cinar
  • 401
  • 1
  • 8
  • 18
  • show us the repository :) – Admit Nov 01 '17 at 21:23
  • Your mapping is incorrect. Read the hibernate manual to learn how to map a bidirectional OneToMany association. It should be `@OneToMany(mappedBy = "lab")`. That said, you haven't asked any question, nor described any problem you're facing. – JB Nizet Nov 01 '17 at 22:42

1 Answers1

1

Edit your mappings like so

Lab entity

@OneToMany(mappedBy="lab")
private Set<Server> servers;

Server entity

@ManyToOne
private Lab lab;

Now you can write a JPQL like so

public interface ServerRepository extends JpaRepository<Server, Long>{

    @Query("Select s from Server s where s.lab.labName = :name and s.lab.id = :id")
    List<Server> getServers(@Param("name") String name, @Param("id") Long id);

}
Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78