Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data Mongo: How to return nested object by its field?

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);
}
like image 339
marknorkin Avatar asked Dec 18 '22 13:12

marknorkin


1 Answers

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.

like image 140
Sanjay Rawat Avatar answered Dec 28 '22 06:12

Sanjay Rawat