英文:
How to add mongodb constraint in springboot to validate multiple concurrent request object having same username and active flag
问题
I have a Pojo class:
@Data
@Document(collection="user")
public class User {
@Id
private long id;
private String username;
private String sessionId;
private boolean active;
}
And my Repository:
public interface UserRepository extends MongoRepository<User, String> {
}
In my service class, I'm doing:
repository.save(user);
When parallel requests are made in the database, multiple records are created for the same username, and the active status is true. Only one true active status record should be created per username, and there can be multiple false active records. How can I add a MongoDB database-level constraint to check this? Any suggestions?
英文:
I have pojo class
@Data
@Document(collection="user")
public class User{
@Id
private long id;
private String username;
private String sessionId;
private boolean active;
}
And my Repository
public interface UserRepository extends MongoRepository<User, String> {
}
In my service class i'm doing
repository.save(user);
When Parallel requests are made in database there are multiple records created for the same username and the active status is true. only one true active status record should be created per username and can have multiple false active records. How to add mongodb database level constraint to check this. Any suggestions
答案1
得分: 0
你可以使用compound、partial和unique索引
@CompoundIndex(
name = "unique_active_username",
def = "{'username': 1}",
partialFilter = "{active: { $eq: true }}",
unique = true)
@Data
@Document(collection="user")
public class User{
@Id
private long id;
private String username;
private String sessionId;
private boolean active;
}
英文:
You could use compaund, partial, unique index
@CompoundIndex(
name = "unique_active_username",
def = "{'username' : 1}",
partialFilter = "{active: { $eq: true }}",
unique = true)
@Data
@Document(collection="user")
public class User{
@Id
private long id;
private String username;
private String sessionId;
private boolean active;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论