I have domain:
class Company {
List<Job> jobs;
}
Is there a way to return nested object from collection like:
@Repository
public interface CompanyRepository extends MongoRepository<Company, String>{
Job findByJobId(String jobId);
}
Yes it is possible, try this:
Company.class
@Document
public class Company {
@Id
private String id;
@Field("name")
private String Name;
@DBRef
List<Job> job;
// Getters and Setters
}
Job.class
@Document
public class Job {
@Id
private String id;
@Field("name")
private String name;
// Getters and Setters
}
CompanyRepository.class
public interface CompanyRepository extends MongoRepository<Company, String> {
Company findOneByJobId(String id);
List<Company> findByJobId(String id);
}
JobRepository.class
public interface JobRepository extends MongoRepository<Job, String>{
Job findOneByName(String name);
}
Then you can @Autowire
the repositories and invoke the methods:
Job java = new Job("Core Java Developer");
Job spring = new Job("Spring Web Developer");
Job cSharp = new Job("C# Developer");
Job dotNet = new Job(".Net Web Developer");
List<Job> allJobs = Arrays.asList(java,cSharp,spring, dotNet);
// Save All Jobs
jobRepository.save(allJobs);
// Create Companies
Company oracle = new Company("Oracle", Arrays.asList(java));
Company microsoft = new Company("Microsoft", Arrays.asList(cSharp, dotNet));
Company pivotal = new Company("Pivotal", Arrays.asList(java, spring));
// Save all companies
companyRepository.save(Arrays.asList(oracle,microsoft,pivotal));
// Find job by name - C#
Job cSharpJob = jobRepository.findOneByName("C# Developer");
System.out.println("*******************Found Job by Name************************");
System.out.println(cSharpJob);
System.out.println("*******************************************");
// Find One Company having Job with Job Id - C#
Company companyWithcSharpJob = companyRepository.findOneByJobId(cSharpJob.getId());
System.out.println("********************Company having C# Job found using Job Id: "+ cSharpJob.getId() +"***********************");
System.out.println(companyWithcSharpJob.getName());
System.out.println("*******************************************");
Checkout the Complete Project in my GitHub repository.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With