Ich habe folgende Entity:
Repository:
Serviceklasse:
Testklasse:
Im Testfall testCreateUserWithCreator erhalte ich folgende Fehlermeldung:
Java:
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.validator.constraints.Length;
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JoinColumn(name = "created_by", referencedColumnName = "id")
@ManyToOne(fetch = FetchType.LAZY)
private User created_by;
@OneToMany(mappedBy = "created_by", fetch = FetchType.EAGER)
private List<User> userList;
@NotNull
@CreationTimestamp
private LocalDateTime created_at;
@OneToOne(cascade = CascadeType.REMOVE, fetch=FetchType.EAGER)
@JoinColumn(name="updated_by")
private User updated_by;
private LocalDateTime updated_at;
@OneToOne(cascade = CascadeType.REMOVE, fetch=FetchType.EAGER)
@JoinColumn(name="deleted_by")
private User deleted_by;
private LocalDateTime deleted_at;
@NotNull
@NotBlank
@Length(min=3, max=255)
private String firstname;
@NotNull
@NotBlank
@Length(min=3, max=255)
private String lastname;
@NotNull
@NotBlank
@Email
@Length(min=3, max=255)
@Column(unique=true)
private String email;
@NotNull
@NotBlank
@Length(min=3, max=255)
private String password;
public User() {
}
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 List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
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 setDeleted_by(User deletedBy) {
this.deleted_by = deleted_by;
}
public LocalDateTime getDeletedAt() {
return deleted_at;
}
public void setDeleted_at(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;
}
@Override
public int hashCode() {
return Objects.hash(created_at, created_by, deleted_at, deleted_by, email, firstname, id, lastname, password,
updated_at, updated_by);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
return Objects.equals(created_at, other.created_at) && Objects.equals(created_by, other.created_by)
&& Objects.equals(deleted_at, other.deleted_at) && Objects.equals(deleted_by, other.deleted_by)
&& Objects.equals(email, other.email) && Objects.equals(firstname, other.firstname)
&& Objects.equals(id, other.id) && Objects.equals(lastname, other.lastname)
&& Objects.equals(password, other.password) && Objects.equals(updated_at, other.updated_at)
&& Objects.equals(updated_by, other.updated_by);
}
@Override
public String toString() {
return "User [id=" + id + ", created_by=" + created_by + ", userList=" + userList + ", created_at=" + created_at
+ ", updated_by=" + updated_by + ", updated_at=" + updated_at + ", deleted_by=" + deleted_by
+ ", deleted_at=" + deleted_at + ", firstname=" + firstname + ", lastname=" + lastname + ", email="
+ email + ", password=" + password + "]";
}
}
Repository:
Code:
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.tmt.mytestapp.user.model.User;
@Repository
public interface UserRepository extends CrudRepository<User, Long> {
Optional<User> findByEmail(String email);
}
Serviceklasse:
Code:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.google.common.base.Preconditions;
import com.tmt.hurricane.global.exception.ResourceNotFoundException;
import com.tmt.mytestapp.user.model.User;
import com.tmt.mytestapp.user.repository.UserRepository;
import java.time.LocalDateTime;
import java.util.Optional;
import javax.transaction.Transactional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@Service
public class UserService {
private static Logger logger = LogManager.getLogger(UserService.class);
@Autowired
UserRepository userRepository;
public User createUser(User creator, User user) throws ResourceNotFoundException {
logger.debug("UserService::createUser(" + creator + ", " + user + ")");
Preconditions.checkNotNull(user, "UserService::createUser(" + creator + ", " + user + "): The adding user must not be zero");
if ( creator != null && !userRepository.existsById(creator.getId()) )
throw new ResourceNotFoundException("UserService::createUser(" + creator + ", " + user + "): Creator not found with the id :: " + creator.getId());
user.setCreatedBy(creator);
user.setCreatedAt(LocalDateTime.now());
return userRepository.save(user);
}
public void removeUser(long id) throws ResourceNotFoundException {
logger.debug("UserService::removeUser(" + id + ")");
User user = userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("UserService::removeUser(" + id + "): User not found for this id"));
userRepository.delete(user);
}
public Optional<User> findUserById(long userId) {
logger.debug("UserService::findUserById(" + userId + ")");
return userRepository.findById(userId);
}
}
Testklasse:
Code:
import static org.junit.jupiter.api.Assertions.*;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.tmt.mytestapp.global.exception.ResourceNotFoundException;
import com.tmt.mytestapp.user.model.User;
@SpringBootTest
class UserServiceTest {
@Autowired
UserService userService;
@Test
void testCreateUserWithMinimalistValidData() throws ResourceNotFoundException, NullPointerException {
String firstname = "firstname";
String lastname = "lastname";
String email = "email@email.com";
String password = "password";
User user = new User();
user.setFirstname(firstname);
user.setLastname(lastname);
user.setEmail(email);
user.setPassword(password);
User createdUser = userService.createUser(null, user);
Optional<User> foundUser = userService.findUserById(createdUser.getId());
assertTrue( foundUser.isPresent(), "testCreateUserWithMinimalistValidData(): User (" + user + ") not stored");
assertNull(foundUser.get().getCreatedBy(), "testCreateUserWithMinimalistValidData(): User (" + foundUser.get().getCreatedBy() + ") creator not null");
assertNotNull(foundUser.get().getCreatedAt(), "testCreateUserWithMinimalistValidData(): User (" + foundUser.get().getCreatedAt() + ") creator date not set");
assertNull(foundUser.get().getUpdatedBy(), "testCreateUserWithMinimalistValidData(): User (" + foundUser.get().getUpdatedBy() + ") updater was set");
assertNull(foundUser.get().getUpdatedAt(), "testCreateUserWithMinimalistValidData(): User (" + foundUser.get().getUpdatedAt() + ") updater date was set");
assertNull(foundUser.get().getDeletedBy(), "testCreateUserWithMinimalistValidData(): User (" + foundUser.get().getDeletedBy() + ") deleter was set");
assertNull(foundUser.get().getDeletedAt(), "testCreateUserWithMinimalistValidData(): User (" + foundUser.get().getDeletedAt() + ") deleter date was set");
assertEquals(firstname, foundUser.get().getFirstname(), "testCreateUserWithMinimalistValidData(): User (" + foundUser.get().getFirstname() + ") Firstname not identical with " + firstname);
assertEquals(lastname, foundUser.get().getLastname(), "testCreateUserWithMinimalistValidData(): User (" + foundUser.get().getLastname() + ") Lastname not identical with " + lastname);
assertEquals(email, foundUser.get().getEmail(), "testCreateUserWithMinimalistValidData(): User (" + foundUser.get().getEmail() + ") Email not identical with " + email);
assertEquals(password, foundUser.get().getPassword(), "\"testCreateUserWithMinimalistValidData(): User (" + foundUser.get().getPassword() + ") Password not identical with " + password);
// clean up
userService.removeUser(foundUser.get().getId());
}
@Test
void testCreateUserWithCreator() throws ResourceNotFoundException, NullPointerException {
// store creator
String creatorFirstname = "firstname";
String creatorLastname = "lastname";
String creatorEmail = "createrl@email.com";
String creatorPassword = "password";
User creator = new User();
creator.setFirstname(creatorFirstname);
creator.setLastname(creatorLastname);
creator.setEmail(creatorEmail);
creator.setPassword(creatorPassword);
User createdCreator = userService.createUser(null, creator);
Optional<User> foundCreator = userService.findUserById(createdCreator.getId());
assertTrue( foundCreator.isPresent(), "testCreateUserWithCreator(): Creator (" + createdCreator + ") not stored");
// stored user
String userFirstname = "user firstname";
String userLastname = "user lastname";
String userEmail = "useremail@email.com";
String userPassword = "userpassword";
User user = new User();
user.setFirstname(userFirstname);
user.setLastname(userLastname);
user.setEmail(userEmail);
user.setPassword(userPassword);
User createdUser = userService.createUser(foundCreator.get(), user);
Optional<User> foundUser = userService.findUserById(createdUser.getId());
assertTrue( foundUser.isPresent(), "testCreateUserWithCreator(): User (" + createdUser + ") not stored");
assertEquals(createdUser.getId(), foundUser.get().getId(), "testCreateUserWithCreator(): User (" + foundUser.get() + ") creator not identical with " + createdUser.getId());
assertNotNull(foundUser.get().getCreatedBy(), "testCreateUserWithCreator(): User (" + foundUser.get() + ") creator date not set");
assertNull(foundUser.get().getUpdatedBy(), "testCreateUserWithCreator(): User (" + foundUser.get().getUpdatedBy() + ") updater was set");
assertNull(foundUser.get().getUpdatedAt(), "testCreateUserWithCreator(): User (" + foundUser.get().getUpdatedAt() + ") updater date was set");
assertNull(foundUser.get().getDeletedBy(), "testCreateUserWithCreator(): User (" + foundUser.get().getDeletedBy() + ") deleter was set");
assertNull(foundUser.get().getDeletedAt(), "testCreateUserWithCreator(): User (" + foundUser.get().getDeletedAt() + ") deleter date was set");
assertEquals(userFirstname, foundUser.get().getFirstname(), "testCreateUserWithCreator(): User (" + foundUser.get() + ") firstname not identical with " + userFirstname);
assertEquals(userLastname, foundUser.get().getLastname(), "testCreateUserWithCreator(): User (" + foundUser.get() + ") lastname not identical with " + userLastname);
assertEquals(userEmail, foundUser.get().getEmail(), "testCreateUserWithCreator(): User (" + foundUser.get() + ") email not identical with " + userEmail);
assertEquals(userPassword, foundUser.get().getPassword(), "\"testCreateUserWithCreator(): User (" + foundUser.get() + ") password not identical " + userPassword);
// clean up
userService.removeUser(foundCreator.get().getId());
userService.removeUser(foundUser.get().getId());
}
}
Im Testfall testCreateUserWithCreator erhalte ich folgende Fehlermeldung:
ich verstehe nur nicht was hier gerad schiefläuftorg.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.tmt.mytestapp.user.model.User.userList, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:614)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:218)
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:591)
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:149)
at org.hibernate.collection.internal.PersistentBag.toString(PersistentBag.java:621)
at java.base/java.lang.String.valueOf(String.java:3367)
at java.base/java.lang.StringBuilder.append(StringBuilder.java:167)
at com.tmt.mytestapp.user.model.User.toString(User.java:335)
at java.base/java.lang.String.valueOf(String.java:3367)
at java.base/java.lang.StringBuilder.append(StringBuilder.java:167)
at com.tmt.mytestapp.user.service.UserService.createUser(UserService.java:47)
at com.tmt.mytestapp.user.service.UserService$$FastClassBySpringCGLIB$$b0cccf6b.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy.invokeMethod(CglibAopProxy.java:386)
at org.springframework.aop.framework.CglibAopProxy.access$000(CglibAopProxy.java:85)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:704)
at com.tmt.mytestapp.user.service.UserService$$EnhancerBySpringCGLIB$$9d482c8a.createUser(<generated>)
at com.tmt.mytestapp.user.service.UserServiceTest.testCreateUserWithCreator(UserServiceTest.java:135)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
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)