'Composite Primary Key using MongoDB and Spring Data JPA
Could someone tell how to create a composite key in Spring Data JPA using Mongo DB
Solution 1:[1]
You cannot use MongoDB with Spring Data JPA because JPA is for relational databases like MySQL.
Instead you have to use Spring Data MongDB and you will find the documentation here:
https://docs.spring.io/spring-data/mongodb/docs/2.1.8.RELEASE/reference/html/
But here's an example with a composite key:
class StudentChairman {
@Id
private CompositeKey id;
// getters and setters
static class CompositeKey implements Serializable {
private String studentId;
private String groupId;
// getters and setters
}
}
Solution 2:[2]
The composite/compound primary key feature in MongoDB can be achieved using the below approach
For instance, we are creating an Employee document where the employee_id and department Should be unique
Entity class
@Document(collection = "employee")
@CompoundIndex(name = "employee_unique_idx", def = "{'employeeId': 1, 'department': 1}",
unique = true)
public class Employee {
@Id
private String id;
private String employeeId;
private String department;
private String organization;
}
DB creation part, you can create the unique composite key manually by
db.employee.createIndex( { "employeeId": 1, "department": 1 }, { unique: true } )
or using the java client
try (MongoClient mongoClient = MongoClients.create(uri)) {
String databaseName = "demo-db";
MongoDatabase database = mongoClient.getDatabase(databaseName);
MongoCollection<Document> employee = database.getCollection("employee");
IndexOptions indexOptions = new IndexOptions();
//Enforcing unique key const
indexOptions.unique(true);
//creating unique composite key
employee.createIndex(compoundIndex(ascending("employeeId"), descending("department")),
indexOptions);
}
Asserting the unique key condition
@Autowired
private EmployeeRepository employeeRepository;
@Test
void crudEmployee() {
Employee employee1 = new Employee();
employee1.setEmployeeId("emp1");
employee1.setDepartment("Data Engineer");
employee1.setOrganization("Freelancer");
Employee employee2 = new Employee();
employee2.setEmployeeId("emp2");
employee2.setDepartment("Data Engineer");
employee2.setOrganization("Freelancer");
Employee employee3 = new Employee();
employee3.setEmployeeId("emp1");
employee3.setDepartment("Data Engineer");
employee3.setOrganization("Freelancer");
employeeRepository.save(employee1);
employeeRepository.save(employee2);
//we are trying to create duplicate entry but the mongo
//will not allow it because of unique key constraint
Assertions.assertThrows(org.springframework.dao.DuplicateKeyException.class,
() -> employeeRepository.save(employee3));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Simon Martinelli |
Solution 2 |