How to add mongodb constraint in springboot to validate multiple concurrent request object having same username and active flag

huangapple go评论80阅读模式
英文:

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=&quot;user&quot;)
public class User{
@Id
private long id;
private String username;
private String sessionId;
private boolean active;
}

And my Repository

public interface UserRepository extends MongoRepository&lt;User, String&gt; {

}

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

你可以使用compoundpartialunique索引

@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 = &quot;unique_active_username&quot;, 
    def = &quot;{&#39;username&#39; : 1}&quot;, 
    partialFilter = &quot;{active: { $eq: true }}&quot;, 
    unique = true)
@Data
@Document(collection=&quot;user&quot;)
public class User{
    @Id
    private long id;
    private String username;
    private String sessionId;
    private boolean active;
}

huangapple
  • 本文由 发表于 2023年6月26日 21:10:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76557015.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定