Spring MongoDB unique index

  • Themenstarter Themenstarter Gelöschtes Mitglied 64357
  • Beginndatum Beginndatum
G

Gelöschtes Mitglied 64357

Gast
Ich habe folgendes
Java:
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.Objects;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Length;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection="users")
public class User {

    @Transient
    public static final String SEQUENCE_NAME = "user_sequence";
    
    @Id
    private long id;                                // the id of the document
        
    @DBRef
    private User created_by;                        // the creator   
    private LocalDateTime created_at;                // the created date   

    @DBRef
    private User updated_by;                        // the creator
    private LocalDateTime updated_at;                // the update
    
    @DBRef   
    private User deleted_by;                        // the user who has this deleted
    private LocalDateTime deleted_at;                // the date when the user has this deleted

    @NotBlank
    @Size(min = 1, max = 100)
    private String firstname;                        // first name
    
    @NotBlank
    @Size(min = 1, max = 100)
    private String lastname;                        // last name
    
    @NotBlank
    @Email
    @Indexed(unique=true)
    private String email;                            // the email of the user
    
    @NotBlank       
    @Size(min = 6, max = 15)
    private String password;                        // the password
    
    private boolean blocked;                        // if the user blocked?
    
    private boolean registered;                        // if the user registered?
    
    private String sid;                                // session id
    
    private String telephon;                        // telephon number
    
    private UserRole userRole;                        // the user roles
    
    public User() {
        super();
    }

    public User(
            long id,
            User created_by, LocalDateTime created_at,
            User updated_by, LocalDateTime updated_at,
            User deleted_by, LocalDateTime deleted_at,
            @NotBlank @Size(max = 100) String firstname,
            @NotBlank @Size(max = 100) String lastname,
            @NotBlank @Email String email,
            @NotBlank @Size(max = 100) String password,
            boolean blocked,
            boolean registered,
            String sid,
            String telephon,
            UserRole userRole) {
        super();
        this.id = id;
        this.created_by = created_by;
        this.created_at = created_at;
        this.updated_by = updated_by;
        this.updated_at = updated_at;
        this.deleted_by = deleted_by;
        this.deleted_at = deleted_at;
        this.firstname = firstname;
        this.lastname = lastname;
        this.email = email;
        this.password = password;
        this.blocked = blocked;
        this.registered = registered;
        this.sid = sid;
        this.telephon = telephon;
        this.userRole = userRole;
    }

    public long getId() {
        return id;
    }
    
    public void setId(long id) {
        this.id = id;
    }
    
    public User getCreatedBy() {
        return created_by;
    }
    
    public void setCreatedBy(User created_by) {
        this.created_by = created_by;
    }
    
    public LocalDateTime getCreatedAt() {
        return created_at;
    }
    
    public void setCreatedAt(LocalDateTime created_at) {
        this.created_at = created_at;
    }
    
    public User getUpdatedBy() {
        return updated_by;
    }
    
    public void setUpdatedBy(User updated_by) {
        this.updated_by = updated_by;
    }
    
    public LocalDateTime getUpdatedAt() {
        return updated_at;
    }
    
    public void setUpdatedAt(LocalDateTime updated_at) {
        this.updated_at = updated_at;
    }
    
    public User getDeletedBy() {
        return deleted_by;
    }
    
    public void setDeletedBy(User deleted_by) {
        this.deleted_by = deleted_by;
    }
    
    public LocalDateTime getDeletedAt() {
        return deleted_at;
    }
    
    public void setDeletedAt(LocalDateTime deleted_at) {
        this.deleted_at = deleted_at;
    }
    
    public String getFirstname() {
        return firstname;
    }
    
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    
    public String getLastname() {
        return lastname;
    }
    
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
    
    public String getPassword() {
        return password;
    }
    
    public void setPassword(String password) {
        this.password = password;
    }
    
    public boolean isBlocked() {
        return blocked;
    }
    
    public void setBlocked(boolean blocked) {
        this.blocked = blocked;
    }
    
    public boolean isRegistered() {
        return registered;
    }

    public void setRegistered(boolean registered) {
        this.registered = registered;
    }

    public String getSid() {
        return sid;
    }
    
    public void setSid(String sid) {
        this.sid = sid;
    }
    
    public String getTelephon() {
        return telephon;
    }
    
    public void setTelephon(String telephon) {
        this.telephon = telephon;
    }
}
Des Feld Email ist hierbei als NotBlank, Email und unique annotiert.

Die application.properties sieht hierbei wie folgt aus
Code:
spring.data.mongodb.uri = mongodb://localhost:27017/hurricane
spring.jpa.hibernate.ddl-auto=create
spring.data.mongodb.auto-index-creation=true

Repository nichts besonders
Code:
@Repository
public interface UserRepository extends MongoRepository<User, Long> {

    Optional<User> findByEmailAndPassword(String email, String password);
    Optional<User> findByEmail(String email);
    Optional<User> findBySid(String sid);
    
}

Service:
Code:
@Service
public class UserService {
    
    private MongoOperations mongoOperations;

    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    SequenceGeneratorService sequenceGeneratorService;
    
    @Autowired
    public UserService(MongoOperations mongoOperations) {
        this.mongoOperations = mongoOperations;
    }   

    public User createUser(User creator, User user) throws ResourceNotFoundException {
        if ( creator != null ) {
            userRepository.findById(creator.getId())
                .orElseThrow(() -> new ResourceNotFoundException("Creator not found with the id :: " + creator.getId()));
        }
        
        user.setId(sequenceGeneratorService.generateSequence(User.SEQUENCE_NAME));
        user.setCreatedBy(creator);
        user.setCreatedAt(LocalDateTime.now());
        
        return userRepository.save(user);
    }

und der TestCase
Code:
@SpringBootTest
class UserServiceTest {

    @Autowired
    UserService userService;

    @Test
    void testCreateUserWithValidDatas() throws ResourceNotFoundException {
        String firstname = "firstname";
        String lastname = "lastname";
        String email = "email@email.com";
        String password = "a password";
        
        boolean exception = false;
        User user = new User();
        
        user.setFirstname(firstname);
        user.setLastname(lastname);
        user.setEmail(email);
        user.setPassword(password);
        
        try {
            userService.createUser(null, user);
        } catch (ResourceNotFoundException e) {
            exception = true;
            e.printStackTrace();
        }
        
        assertFalse(exception);
        
        Optional<User> foundUser = userService.findById(user.getId());
        
        assertTrue( foundUser.isPresent() );
        assertEquals(null, foundUser.get().getCreatedBy());
        assertNotEquals(null, foundUser.get().getCreatedAt());
        assertEquals(null, foundUser.get().getUpdatedBy());
        assertEquals(null, foundUser.get().getUpdatedAt());
        assertEquals(null, foundUser.get().getDeletedBy());
        assertEquals(null, foundUser.get().getDeletedAt());
        assertEquals(firstname, foundUser.get().getFirstname());
        assertEquals(lastname, foundUser.get().getLastname());
        assertEquals(email, foundUser.get().getEmail());
        assertEquals(password, foundUser.get().getPassword());

        // clean up
        userService.deleteUser(user.getId());
    }
}

Beim testen erhalte ich aber
org.springframework.dao.DuplicateKeyException: Write operation error on server localhost:27017. Write error: WriteError{code=11000, message='E11000 duplicate key error collection: hurricane.users index: email dup key: { email: "email@email.com" }', details={}}.; nested exception is com.mongodb.MongoWriteException: Write operation error on server localhost:27017. Write error: WriteError{code=11000, message='E11000 duplicate key error collection: hurricane.users index: email dup key: { email: "email@email.com" }', details={}}.
at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:106)
at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2929)
at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:562)
at org.springframework.data.mongodb.core.MongoTemplate.saveDocument(MongoTemplate.java:1528)
at org.springframework.data.mongodb.core.MongoTemplate.doSave(MongoTemplate.java:1464)
at org.springframework.data.mongodb.core.MongoTemplate.save(MongoTemplate.java:1407)
at org.springframework.data.mongodb.repository.support.SimpleMongoRepository.save(SimpleMongoRepository.java:98)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:289)
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137)
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121)
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:529)
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:285)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:639)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:163)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:138)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)
at jdk.proxy2/jdk.proxy2.$Proxy79.save(Unknown Source)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)
at jdk.proxy2/jdk.proxy2.$Proxy79.save(Unknown Source)
at com.tmt.hurricane.usermanagement.service.UserService.createUser(UserService.java:94)
at com.tmt.hurricane.usermanagement.service.UserServiceTest.testCreateUserWithValidDatas(UserServiceTest.java:50)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:95)
at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:91)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:60)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:529)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Caused by: com.mongodb.MongoWriteException: Write operation error on server localhost:27017. Write error: WriteError{code=11000, message='E11000 duplicate key error collection: hurricane.users index: email dup key: { email: "email@email.com" }', details={}}.
at com.mongodb.client.internal.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:1018)
at com.mongodb.client.internal.MongoCollectionImpl.executeReplaceOne(MongoCollectionImpl.java:568)
at com.mongodb.client.internal.MongoCollectionImpl.replaceOne(MongoCollectionImpl.java:551)
at org.springframework.data.mongodb.core.MongoTemplate.lambda$saveDocument$18(MongoTemplate.java:1560)
at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:560)
... 106 more
Dieses will mir nicht ganz einleuchten.
 
Was mir auffällt, dein User hat Felder für "deletedBy etc." Sprich, ein Löschen des Users scheint den User nur als gelöscht zu markieren, aber nicht zu löschen. Ergo wird es nach meinem Verständnis beim zweiten ausführen des Testfalls zu einem Problem kommen.
 
Was mir auffällt, dein User hat Felder für "deletedBy etc." Sprich, ein Löschen des Users scheint den User nur als gelöscht zu markieren, aber nicht zu löschen. Ergo wird es nach meinem Verständnis beim zweiten ausführen des Testfalls zu einem Problem kommen.
Das ist korrekt und auch so gemeint. Aber das obigen findet beim 1. Testlauf auf einer "Jungfräulichen" Datenbank statt.

Ergänzend sei noch erwähnt, dass
Java:
userService.deleteUser(user.getId());
den Endgültig löscht. Die Funktion removeUser(id, boolean) setzt den Eintrag als (un)gelöscht. Und ja, es wäre zu überlegen, ob man die beiden Funktionsnamen nicht vertauschen sollte.
 
Zuletzt bearbeitet von einem Moderator:
Dann hab ich keine direkte Idee.

Sicher das die DB wirklich leer ist vorher? Bei H2 kann man ja eine in-Memory DB nutzen, wie das bei mongodb mit Tests aussieht hab ich keine Ahnung. Ich würde mal in den Test einbauen, dass du vorher prüfst, dass es zu der E-Mail keinen Eintrag gibt. Nicht das durch parallele Test-Ausführungen oder ähnliches sie doch nicht leer ist.
 

Zurück
Oben