簡體   English   中英

使用 MongoDB 和 Spring Data JPA 的復合主鍵

[英]Composite Primary Key using MongoDB and Spring Data JPA

有人可以告訴如何使用 Mongo DB 在 Spring Data JPA 中創建復合鍵

您不能將 MongoDB 與 Spring Data JPA 一起使用,因為 JPA 用於 MySQL 等關系數據庫。

相反,您必須使用 Spring Data MongDB,您將在此處找到文檔:

https://docs.spring.io/spring-data/mongodb/docs/2.1.8.RELEASE/reference/html/

但這里有一個復合鍵的例子:

class StudentChairman {

    @Id
    private CompositeKey id;

    // getters and setters

    static class CompositeKey implements Serializable {
        private String studentId;
        private String groupId;

        // getters and setters
    }
}

MongoDB中的復合/復合主鍵功能可以使用以下方法實現

例如,我們正在創建一個員工文檔,其中員工 ID 和部門應該是唯一的

實體類

@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.employee.createIndex( { "employeeId": 1, "department": 1 }, { unique: true } )

或使用 java 客戶端

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);

}

斷言唯一鍵條件

    @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));
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM