├── .gitignore ├── README.md ├── advanced-ioc ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── bobocode │ ├── AdvancedBeanExample.java │ ├── congfig │ └── RootConfig.java │ ├── dao │ ├── AccountDao.java │ └── impl │ │ ├── FakeAccountDao.java │ │ └── InMemAccountDao.java │ └── service │ └── AccountService.java ├── aop-basics ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── bobocode │ ├── AspectsExamples.java │ ├── aspects │ └── UserServiceAspects.java │ ├── configs │ └── ApplicationConfigs.java │ └── service │ ├── UserService.java │ └── impl │ └── UserServiceImpl.java ├── bean-overriding ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── bobocode │ │ ├── BeanOverridingExample.java │ │ ├── configs │ │ ├── AdditionalConfig.java │ │ └── MainConfig.java │ │ └── service │ │ ├── TalkingService.java │ │ └── impl │ │ ├── CFanService.java │ │ └── PhpFanService.java │ └── resources │ └── application-context.xml ├── ioc-basics ├── README.md ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── bobocode │ │ ├── DependencyInjectionExample.java │ │ ├── JavaConfigsApplicationContextExample.java │ │ ├── XmlConfigsApplicationContextExample.java │ │ ├── configs │ │ └── ApplicationConfigs.java │ │ ├── dao │ │ ├── AccountDao.java │ │ └── impl │ │ │ └── FakeAccountDaoImpl.java │ │ └── service │ │ └── AccountService.java │ └── resources │ └── application-context.xml ├── jpa-tx-management ├── README.md ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── bobocode │ ├── AccountApp.java │ ├── config │ ├── JpaConfig.java │ └── RootConfig.java │ ├── dao │ ├── AccountDao.java │ └── impl │ │ └── JpaAccountDao.java │ └── service │ └── AccountService.java ├── mvc-basics ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── bobocode │ │ ├── configs │ │ ├── BobocodeWebInitializer.java │ │ ├── RootConfig.java │ │ └── WebConfig.java │ │ └── web │ │ └── controller │ │ ├── AccountController.java │ │ ├── ParametrizedHelloController.java │ │ └── WelcomeController.java │ └── webapp │ └── WEB-INF │ └── views │ ├── account.jsp │ ├── accountForm.jsp │ └── welcome.jsp ├── pom.xml ├── profiles-and-properties ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── bobocode │ │ ├── ProfilesAndPropertiesExample.java │ │ └── config │ │ ├── JpaConfig.java │ │ └── RootConfig.java │ └── resources │ └── application.properties ├── rest-basics ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── bobocode │ ├── configs │ ├── AccountRestApiWebInitializer.java │ ├── RootConfig.java │ └── WebConfig.java │ ├── exception │ └── EntityNotFoundException.java │ ├── service │ └── AccountService.java │ └── web │ ├── WebAppExceptionHandler.java │ └── controller │ ├── AccountRestController.java │ └── WelcomeController.java ├── spring-framework-tutorial-model ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── bobocode │ └── model │ ├── Account.java │ ├── Address.java │ ├── Credentials.java │ ├── Gender.java │ ├── Role.java │ ├── RoleType.java │ └── User.java └── spring-framework-tutorial-util ├── pom.xml └── src └── main └── java └── com └── bobocode └── util └── TestDataGenerator.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | .idea 3 | **/*.iml 4 | **/target 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Spring framework tutorial 2 | The list of tutorials on Dependency Injection, Aspect-Oriented programming, and Spring MVC 3 | 4 | ### Pre-conditions :heavy_exclamation_mark: 5 | You're supposed to have at least good knowledge on Java SE 6 | 7 | ### Related resources :information_source: 8 | #### Overview 9 | * [Spring in Action](https://www.amazon.com/Spring-Action-Covers-4/dp/161729120X/ref=sr_1_1?s=books&ie=UTF8&qid=1538391717&sr=1-1&keywords=spring+in+action) :green_book: 10 | * **1.1** Simplifying Java development. *(Advantages of Spring)* 11 | * **1.2** Containing your beans. *(A bean lifecycle)* 12 | #### Bean configuration 13 | * [Spring IoC and Dependency Injection tutorial](https://github.com/bobocode-projects/spring-framework-tutorial/tree/master/ioc-basics#spring-ioc-and-dependency-injection-tutorial) 14 | * [Spring in Action](https://www.amazon.com/Spring-Action-Covers-4/dp/161729120X/ref=sr_1_1?s=books&ie=UTF8&qid=1538391717&sr=1-1&keywords=spring+in+action) :green_book: 15 | * **2.2.1** Creating discoverable beans *([`@Component`](https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-stereotype-annotations))* 16 | * **2.2.2** Naming a component-scanned bean 17 | * **2.2.3** Setting a base package for component scanning. *([`@ComponentScan`](https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-scanning-autodetection))* 18 | * **2.2.4** Annotating beans to be automatically wired. *(Configuring dependency injection with [`@Autowired`](https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-autowired-annotation))* 19 | * **2.3.1** Creating a configuration class. ([`@Congifuration`](https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-java-configuration-annotation)) 20 | * **2.3.2** Declaring a simple bean. (Explicit Java configuration using [`@Bean`](https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-java-bean-annotation)) 21 | * **2.3.3** Injecting with JavaConfig. *(Java config file features)* 22 | #### ORM 23 | * [Spring in Action](https://www.amazon.com/Spring-Action-Covers-4/dp/161729120X/ref=sr_1_1?s=books&ie=UTF8&qid=1538391717&sr=1-1&keywords=spring+in+action) :green_book: 24 | * **11.2.1** Configuring an entity manager factory. *(How to configure JPA without persistence.xml?)* 25 | * **11.2.2** Writing a JPA-based repository. *(How to create DAO using [`@Repository`](https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/data-access.html#dao-annotations)?)* 26 | * **10.1.1** Getting to know Spring’s data-access exception hierarchy. *(Why Spring wraps SQL checked exceptions?)* 27 | #### Transaction management 28 | * [Understanding the Spring Framework’s Declarative Transaction Implementation](https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/data-access.html#tx-decl-explained) 29 | * [Using @Transactional](https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/data-access.html#transaction-declarative-annotations) 30 | -------------------------------------------------------------------------------- /advanced-ioc/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-framework-tutorial 7 | com.bobocode 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | advanced-ioc 13 | 14 | 15 | 16 | com.bobocode 17 | spring-framework-tutorial-util 18 | 1.0-SNAPSHOT 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /advanced-ioc/src/main/java/com/bobocode/AdvancedBeanExample.java: -------------------------------------------------------------------------------- 1 | package com.bobocode; 2 | 3 | import com.bobocode.congfig.RootConfig; 4 | import com.bobocode.service.AccountService; 5 | import org.springframework.context.ApplicationContext; 6 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 7 | 8 | public class AdvancedBeanExample { 9 | private static AccountService accountService; 10 | 11 | public static void main(String[] args) { 12 | init(); 13 | accountService.printAllAccounts(); 14 | } 15 | 16 | private static void init() { 17 | ApplicationContext applicationContext = new AnnotationConfigApplicationContext(RootConfig.class); 18 | accountService = applicationContext.getBean(AccountService.class); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /advanced-ioc/src/main/java/com/bobocode/congfig/RootConfig.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.congfig; 2 | 3 | import org.springframework.context.annotation.ComponentScan; 4 | import org.springframework.context.annotation.Configuration; 5 | 6 | @Configuration 7 | @ComponentScan("com.bobocode") 8 | public class RootConfig { 9 | } 10 | -------------------------------------------------------------------------------- /advanced-ioc/src/main/java/com/bobocode/dao/AccountDao.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.dao; 2 | 3 | import com.bobocode.model.Account; 4 | 5 | import java.util.List; 6 | 7 | public interface AccountDao { 8 | void save(Account account); 9 | List findAll(); 10 | } 11 | -------------------------------------------------------------------------------- /advanced-ioc/src/main/java/com/bobocode/dao/impl/FakeAccountDao.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.dao.impl; 2 | 3 | import com.bobocode.dao.AccountDao; 4 | import com.bobocode.model.Account; 5 | import com.bobocode.util.TestDataGenerator; 6 | import org.springframework.stereotype.Component; 7 | 8 | import java.util.List; 9 | 10 | @Component 11 | public class FakeAccountDao implements AccountDao { 12 | @Override 13 | public void save(Account account) { 14 | throw new UnsupportedOperationException("This DAO implementation does not support save()"); 15 | } 16 | 17 | @Override 18 | public List findAll() { 19 | return TestDataGenerator.getAccountList(10); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /advanced-ioc/src/main/java/com/bobocode/dao/impl/InMemAccountDao.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.dao.impl; 2 | 3 | import com.bobocode.dao.AccountDao; 4 | import com.bobocode.model.Account; 5 | import org.springframework.context.annotation.Primary; 6 | import org.springframework.stereotype.Component; 7 | 8 | import java.util.ArrayList; 9 | import java.util.HashMap; 10 | import java.util.List; 11 | import java.util.Map; 12 | 13 | @Component 14 | @Primary 15 | public class InMemAccountDao implements AccountDao { 16 | private long idSequence = 1; 17 | private Map accountMap = new HashMap<>(); 18 | 19 | @Override 20 | public void save(Account account) { 21 | account.setId(idSequence++); 22 | accountMap.put(account.getId(), account); 23 | } 24 | 25 | @Override 26 | public List findAll() { 27 | return new ArrayList<>(accountMap.values()); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /advanced-ioc/src/main/java/com/bobocode/service/AccountService.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.service; 2 | 3 | import com.bobocode.dao.AccountDao; 4 | import org.springframework.beans.factory.annotation.Qualifier; 5 | import org.springframework.stereotype.Service; 6 | 7 | @Service 8 | public class AccountService { 9 | private final AccountDao accountDao; 10 | 11 | public AccountService(@Qualifier("fakeAccountDao") AccountDao accountDao) { 12 | this.accountDao = accountDao; 13 | } 14 | 15 | public void printAllAccounts() { 16 | accountDao.findAll().forEach(System.out::println); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /aop-basics/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | 8 | com.bobocode 9 | spring-framework-tutorial 10 | 1.0-SNAPSHOT 11 | 12 | aop-basics 13 | 14 | 15 | 16 | org.springframework 17 | spring-aspects 18 | 5.0.7.RELEASE 19 | 20 | 21 | com.bobocode 22 | spring-framework-tutorial-util 23 | 1.0-SNAPSHOT 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /aop-basics/src/main/java/com/bobocode/AspectsExamples.java: -------------------------------------------------------------------------------- 1 | package com.bobocode; 2 | 3 | import com.bobocode.configs.ApplicationConfigs; 4 | import com.bobocode.model.User; 5 | import com.bobocode.service.UserService; 6 | import org.springframework.context.ApplicationContext; 7 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 8 | 9 | import java.util.List; 10 | 11 | public class AspectsExamples { 12 | private static UserService userService; 13 | 14 | public static void main(String[] args) { 15 | init(); 16 | List users = userService.findAllUsers(); 17 | User user = userService.findByEmail("test@gmail.com"); 18 | 19 | System.out.printf("All users: %s%n", users); 20 | System.out.printf("User found by email:%s%n", user); 21 | } 22 | 23 | private static void init() { 24 | ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfigs.class); 25 | userService = context.getBean(UserService.class); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /aop-basics/src/main/java/com/bobocode/aspects/UserServiceAspects.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.aspects; 2 | 3 | import com.bobocode.model.User; 4 | import com.bobocode.service.UserService; 5 | import org.aspectj.lang.JoinPoint; 6 | import org.aspectj.lang.annotation.*; 7 | import org.springframework.stereotype.Component; 8 | 9 | import java.util.List; 10 | 11 | @Aspect 12 | @Component 13 | public class UserServiceAspects { 14 | 15 | @Before("execution(com.bobocode.model.User com.bobocode.service.UserService.findByEmail(String)) && args(email)") 16 | public void beforeUserFindByEmail(String email) { 17 | System.out.println("*** Find user by email: " + email); 18 | } 19 | 20 | @Pointcut("execution(* com.bobocode.service.*Service.*(..))") 21 | public void findFromUserService() { 22 | } 23 | 24 | @Before("findFromUserService()") 25 | public void beforeFind() { 26 | System.out.println("*** Find from UserService"); 27 | } 28 | 29 | @After("findFromUserService() && target(service)") 30 | public void afterFindUser(JoinPoint joinPoint, UserService service) { 31 | String methodName = joinPoint.getSignature().getName(); 32 | String className = service.getClass().getName(); 33 | System.out.println("*** Got information using method " + methodName + " of class " + className); 34 | } 35 | 36 | @AfterReturning(value = "execution(* com.bobocode.service.UserService.findAllUsers(..))", returning = "users") 37 | public void afterReturningUserList(List users) { 38 | System.out.println("*** Returned " + users.size() + " users"); 39 | 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /aop-basics/src/main/java/com/bobocode/configs/ApplicationConfigs.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.configs; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.ComponentScan; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.context.annotation.EnableAspectJAutoProxy; 7 | import org.springframework.stereotype.Component; 8 | 9 | /** 10 | * This class specify application context configuration. Basically, it's all about which instances of which classes 11 | * should be created and registered in the context. An instance that is registered int the context is called 'bean'. 12 | * 13 | * To tell the container, which bean should be created, you could either specify packages to scan using @{@link ComponentScan}, 14 | * or declare your own beans using @{@link Bean}. When you use @{@link ComponentScan} the container will discover 15 | * specified package and its sub-folders, to find all classes marked @{@link Component}. 16 | * 17 | * If you want to import other configs from Java class or XML file, you could use @{@link org.springframework.context.annotation.Import} 18 | * and @{@link org.springframework.context.annotation.ImportResource} accordingly 19 | */ 20 | @Configuration 21 | @ComponentScan(basePackages = "com.bobocode") 22 | @EnableAspectJAutoProxy 23 | public class ApplicationConfigs { 24 | 25 | } 26 | -------------------------------------------------------------------------------- /aop-basics/src/main/java/com/bobocode/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.service; 2 | 3 | import com.bobocode.model.User; 4 | 5 | import java.util.List; 6 | 7 | public interface UserService { 8 | List findAllUsers(); 9 | User findByEmail(String email); 10 | } 11 | -------------------------------------------------------------------------------- /aop-basics/src/main/java/com/bobocode/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.service.impl; 2 | 3 | import com.bobocode.model.User; 4 | import com.bobocode.service.UserService; 5 | import com.bobocode.util.TestDataGenerator; 6 | import org.springframework.stereotype.Service; 7 | 8 | import java.util.List; 9 | import java.util.stream.IntStream; 10 | 11 | import static java.util.stream.Collectors.toList; 12 | 13 | 14 | @Service 15 | public class UserServiceImpl implements UserService { 16 | 17 | @Override 18 | public List findAllUsers() { 19 | return IntStream.rangeClosed(1, 10) 20 | .mapToObj(i -> TestDataGenerator.generateUserWithAddressAndRoles()) 21 | .collect(toList()); 22 | } 23 | 24 | @Override 25 | public User findByEmail(String email) { 26 | User user = TestDataGenerator.generateUserWithAddressAndRoles(); 27 | user.getCredentials().setEmail(email); 28 | return user; 29 | } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /bean-overriding/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-framework-tutorial 7 | com.bobocode 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | bean-overriding 13 | 14 | 15 | -------------------------------------------------------------------------------- /bean-overriding/src/main/java/com/bobocode/BeanOverridingExample.java: -------------------------------------------------------------------------------- 1 | package com.bobocode; 2 | 3 | 4 | import com.bobocode.configs.MainConfig; 5 | import com.bobocode.service.TalkingService; 6 | import org.springframework.context.ApplicationContext; 7 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 8 | 9 | public class BeanOverridingExample { 10 | public static void main(String[] args) { 11 | ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class); 12 | 13 | TalkingService talkingService = context.getBean(TalkingService.class); 14 | System.out.println(talkingService.saySomething()); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /bean-overriding/src/main/java/com/bobocode/configs/AdditionalConfig.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.configs; 2 | 3 | import com.bobocode.service.TalkingService; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | 7 | @Configuration 8 | public class AdditionalConfig { 9 | 10 | @Bean("talkingService") 11 | public TalkingService pythonFanService() { 12 | return () -> "Python is awesome!"; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /bean-overriding/src/main/java/com/bobocode/configs/MainConfig.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.configs; 2 | 3 | import com.bobocode.service.TalkingService; 4 | import org.springframework.context.annotation.*; 5 | 6 | @Configuration 7 | @ComponentScan(basePackages = "com.bobocode.service") 8 | @ImportResource("classpath:application-context.xml") 9 | @Import(AdditionalConfig.class) 10 | public class MainConfig { 11 | 12 | @Bean("talkingService") 13 | public TalkingService javaFanService() { 14 | return () -> "Java is the best!"; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /bean-overriding/src/main/java/com/bobocode/service/TalkingService.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.service; 2 | 3 | 4 | public interface TalkingService { 5 | String saySomething(); 6 | } 7 | -------------------------------------------------------------------------------- /bean-overriding/src/main/java/com/bobocode/service/impl/CFanService.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.service.impl; 2 | 3 | import com.bobocode.service.TalkingService; 4 | import org.springframework.stereotype.Service; 5 | 6 | @Service("talkingService") 7 | public class CFanService implements TalkingService { 8 | @Override 9 | public String saySomething() { 10 | return "I like C, and I don't care..."; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /bean-overriding/src/main/java/com/bobocode/service/impl/PhpFanService.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.service.impl; 2 | 3 | 4 | import com.bobocode.service.TalkingService; 5 | 6 | public class PhpFanService implements TalkingService { 7 | 8 | @Override 9 | public String saySomething() { 10 | return "Php is still good :D"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /bean-overriding/src/main/resources/application-context.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /ioc-basics/README.md: -------------------------------------------------------------------------------- 1 | # Spring IoC and Dependency Injection tutorial 2 | This is the tutorial on Spring IoC, ApplicationContext configuration and Dependency Injection 3 | 4 | ### Pre-conditions :heavy_exclamation_mark: 5 | You're supposed to be familiar with *Inversion of Control* and *Dependency Injection* pattern 6 | ### Related resources :information_source: 7 | * [Instantiating the Spring Container by Using AnnotationConfigApplicationContext](https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-java-instantiating-container) 8 | -------------------------------------------------------------------------------- /ioc-basics/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | 8 | com.bobocode 9 | spring-framework-tutorial 10 | 1.0-SNAPSHOT 11 | 12 | spring-framework-ioc-basics 13 | 14 | 15 | 16 | com.bobocode 17 | spring-framework-tutorial-util 18 | 1.0-SNAPSHOT 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /ioc-basics/src/main/java/com/bobocode/DependencyInjectionExample.java: -------------------------------------------------------------------------------- 1 | package com.bobocode; 2 | 3 | 4 | import com.bobocode.configs.ApplicationConfigs; 5 | import com.bobocode.dao.AccountDao; 6 | import com.bobocode.service.AccountService; 7 | import org.springframework.context.ApplicationContext; 8 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 9 | 10 | /** 11 | * Application context that is built using annotation based configuration. 12 | *

13 | * In this example we are requesting {@link AccountService} bean from Spring context. This bean has a dependency 14 | * {@link AccountDao}, which is injected by Spring container. It shows typical Spring Dependency Injection container work. 15 | * It builds application context (creates beans) according to the configurations, on the other hand it injects the beans 16 | * where it is requested. 17 | */ 18 | public class DependencyInjectionExample { 19 | private static AccountService accountService; 20 | 21 | public static void main(String[] args) { 22 | init(); 23 | accountService.findOldestClient().ifPresent(System.out::println); 24 | } 25 | 26 | private static void init(){ 27 | ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfigs.class); 28 | accountService = context.getBean(AccountService.class); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /ioc-basics/src/main/java/com/bobocode/JavaConfigsApplicationContextExample.java: -------------------------------------------------------------------------------- 1 | package com.bobocode; 2 | 3 | 4 | import com.bobocode.configs.ApplicationConfigs; 5 | import com.bobocode.dao.AccountDao; 6 | import org.springframework.context.ApplicationContext; 7 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 8 | 9 | /** 10 | * Application context that is built using annotation based configuration. 11 | */ 12 | public class JavaConfigsApplicationContextExample { 13 | private static AccountDao accountDao; 14 | 15 | public static void main(String[] args) { 16 | init(); 17 | accountDao.getAllAccounts().forEach(System.out::println); 18 | } 19 | 20 | private static void init() { 21 | ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfigs.class); 22 | accountDao = context.getBean(AccountDao.class); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /ioc-basics/src/main/java/com/bobocode/XmlConfigsApplicationContextExample.java: -------------------------------------------------------------------------------- 1 | package com.bobocode; 2 | 3 | 4 | import com.bobocode.dao.AccountDao; 5 | import com.bobocode.model.Account; 6 | import org.springframework.context.ApplicationContext; 7 | import org.springframework.context.support.ClassPathXmlApplicationContext; 8 | 9 | /** 10 | * Application context that is built using XML configuration. 11 | */ 12 | public class XmlConfigsApplicationContextExample { 13 | private static AccountDao accountDao; 14 | 15 | public static void main(String[] args) { 16 | init(); 17 | accountDao.getAllAccounts().forEach(System.out::println); 18 | } 19 | 20 | private static void init(){ 21 | ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml"); 22 | accountDao = context.getBean(AccountDao.class); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /ioc-basics/src/main/java/com/bobocode/configs/ApplicationConfigs.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.configs; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.ComponentScan; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.stereotype.Component; 7 | 8 | /** 9 | * This class specify application context configuration. Basically, it's all about which instances of which classes 10 | * should be created and registered in the context. An instance that is registered int the context is called 'bean'. 11 | * 12 | * To tell the container, which bean should be created, you could either specify packages to scan using @{@link ComponentScan}, 13 | * or declare your own beans using @{@link Bean}. When you use @{@link ComponentScan} the container will discover 14 | * specified package and its sub-folders, to find all classes marked @{@link Component}. 15 | * 16 | * If you want to import other configs from Java class or XML file, you could use @{@link org.springframework.context.annotation.Import} 17 | * and @{@link org.springframework.context.annotation.ImportResource} accordingly 18 | */ 19 | @Configuration 20 | @ComponentScan(basePackages = "com.bobocode") 21 | public class ApplicationConfigs { 22 | 23 | } 24 | -------------------------------------------------------------------------------- /ioc-basics/src/main/java/com/bobocode/dao/AccountDao.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.dao; 2 | 3 | import com.bobocode.model.Account; 4 | 5 | import java.util.List; 6 | 7 | public interface AccountDao { 8 | List getAllAccounts(); 9 | } 10 | -------------------------------------------------------------------------------- /ioc-basics/src/main/java/com/bobocode/dao/impl/FakeAccountDaoImpl.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.dao.impl; 2 | 3 | import com.bobocode.dao.AccountDao; 4 | import com.bobocode.model.Account; 5 | import com.bobocode.util.TestDataGenerator; 6 | import org.springframework.stereotype.Component; 7 | 8 | import java.util.List; 9 | 10 | /** 11 | * This class is marked with @{@link Component}, thus Spring container will create an instance of {@link FakeAccountDaoImpl} 12 | * class, and will register it the context. 13 | */ 14 | @Component 15 | public class FakeAccountDaoImpl implements AccountDao { 16 | 17 | @Override 18 | public List getAllAccounts() { 19 | return TestDataGenerator.getAccountList(10); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /ioc-basics/src/main/java/com/bobocode/service/AccountService.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.service; 2 | 3 | import com.bobocode.dao.AccountDao; 4 | import com.bobocode.model.Account; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Component; 7 | import org.springframework.stereotype.Service; 8 | 9 | import java.util.Optional; 10 | 11 | import static java.util.Comparator.comparing; 12 | 13 | /** 14 | * This class is marked as component, so Spring will crete an instance of this class, and will register it 15 | * in the application context. That instance is called a bean. 16 | * 17 | * This service has a relation to dao. If you want the container to inject (set) this relation, you can mark the field 18 | * with @{@link Autowired}. 19 | * 20 | */ 21 | @Service 22 | public class AccountService { 23 | private final AccountDao accountDao; 24 | 25 | public AccountService(AccountDao accountDao) { 26 | this.accountDao = accountDao; 27 | } 28 | 29 | public Optional findOldestClient() { 30 | return accountDao.getAllAccounts().stream().min(comparing(Account::getBirthday)); 31 | } 32 | } 33 | 34 | -------------------------------------------------------------------------------- /ioc-basics/src/main/resources/application-context.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /jpa-tx-management/README.md: -------------------------------------------------------------------------------- 1 | # Spring ORM and Transaction management 2 | This is the tutorial on Spring ORM, Declarative Tx management and PlatformTransactionManager configuration 3 | 4 | ### Pre-conditions :heavy_exclamation_mark: 5 | You're supposed to be familiar with Spring IoC 6 | ### Related materials :heavy_exclamation_mark: 7 | * [`@Transactional`](https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/data-access.html#transaction-declarative-annotations) 8 | * [`@Repository`](shttps://docs.spring.io/spring-framework/docs/current/spring-framework-reference/data-access.html#dao-annotations) 9 | 10 | ## 11 | -------------------------------------------------------------------------------- /jpa-tx-management/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-framework-tutorial 7 | com.bobocode 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | jpa-tx-management 13 | 14 | 15 | 16 | 17 | org.springframework 18 | spring-orm 19 | 5.0.7.RELEASE 20 | 21 | 22 | com.h2database 23 | h2 24 | 1.4.197 25 | 26 | 27 | org.slf4j 28 | slf4j-simple 29 | 1.7.24 30 | 31 | 32 | org.hibernate.javax.persistence 33 | hibernate-jpa-2.1-api 34 | 1.0.2.Final 35 | 36 | 37 | org.hibernate 38 | hibernate-core 39 | 5.3.2.Final 40 | 41 | 42 | 43 | 44 | javax.xml.bind 45 | jaxb-api 46 | 2.2.11 47 | 48 | 49 | 50 | com.bobocode 51 | spring-framework-tutorial-util 52 | 1.0-SNAPSHOT 53 | 54 | 55 | -------------------------------------------------------------------------------- /jpa-tx-management/src/main/java/com/bobocode/AccountApp.java: -------------------------------------------------------------------------------- 1 | package com.bobocode; 2 | 3 | import com.bobocode.config.RootConfig; 4 | import com.bobocode.model.Account; 5 | import com.bobocode.service.AccountService; 6 | import com.bobocode.util.TestDataGenerator; 7 | import org.springframework.context.ApplicationContext; 8 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 9 | 10 | import java.math.BigDecimal; 11 | import java.util.List; 12 | 13 | /** 14 | * This this code snipped shows Spring Transaction Manager with JPA example 15 | */ 16 | public class AccountApp { 17 | private static AccountService accountService; 18 | 19 | public static void main(String[] args) { 20 | init(); 21 | accountService.printAllAccounts(); 22 | accountService.withdraw(1L, BigDecimal.valueOf(1000)); 23 | accountService.printAllAccounts(); 24 | } 25 | 26 | private static void init() { 27 | ApplicationContext context = new AnnotationConfigApplicationContext(RootConfig.class); 28 | accountService = context.getBean(AccountService.class); 29 | List accountList = TestDataGenerator.getAccountList(5); 30 | accountList.forEach(accountService::save); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /jpa-tx-management/src/main/java/com/bobocode/config/JpaConfig.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; 6 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; 7 | import org.springframework.orm.jpa.JpaVendorAdapter; 8 | import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; 9 | import org.springframework.orm.jpa.vendor.Database; 10 | import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; 11 | 12 | import javax.sql.DataSource; 13 | 14 | @Configuration 15 | public class JpaConfig { 16 | @Bean 17 | public DataSource dataSource() { 18 | return new EmbeddedDatabaseBuilder() 19 | .setType(EmbeddedDatabaseType.H2) 20 | .setName("bobocodeDB") 21 | .build(); 22 | } 23 | 24 | @Bean 25 | public JpaVendorAdapter jpaVendorAdapter() { 26 | HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter(); 27 | adapter.setDatabase(Database.H2); 28 | adapter.setShowSql(true); 29 | adapter.setGenerateDdl(true); // this sets hibernate.hbm2ddl.auto=update 30 | return adapter; 31 | } 32 | 33 | @Bean("entityManagerFactory") 34 | public LocalContainerEntityManagerFactoryBean localContainerEMF(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) { 35 | LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); 36 | emf.setDataSource(dataSource); 37 | emf.setJpaVendorAdapter(jpaVendorAdapter); 38 | emf.setPersistenceUnitName("basicEntities"); // by default Spring will name "default" 39 | emf.setPackagesToScan("com.bobocode.model");// JPA entity classes will be loaded from this package 40 | return emf; 41 | } 42 | 43 | // todo: instead of configuring previous three beans you can use file META-INF/persistence.xml and the following bean 44 | /*@Bean("entityManagerFactory") 45 | public LocalEntityManagerFactoryBean entityManagerFactoryBean() { 46 | LocalEntityManagerFactoryBean emfb = new LocalEntityManagerFactoryBean(); 47 | emfb.setPersistenceUnitName("basicEntities"); 48 | return emfb; 49 | }*/ 50 | } 51 | -------------------------------------------------------------------------------- /jpa-tx-management/src/main/java/com/bobocode/config/RootConfig.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.ComponentScan; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.orm.jpa.JpaTransactionManager; 7 | import org.springframework.transaction.PlatformTransactionManager; 8 | import org.springframework.transaction.annotation.EnableTransactionManagement; 9 | 10 | import javax.persistence.EntityManagerFactory; 11 | 12 | @Configuration 13 | @ComponentScan("com.bobocode") 14 | @EnableTransactionManagement 15 | public class RootConfig { 16 | @Bean 17 | public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory){ 18 | return new JpaTransactionManager(entityManagerFactory); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /jpa-tx-management/src/main/java/com/bobocode/dao/AccountDao.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.dao; 2 | 3 | import com.bobocode.model.Account; 4 | 5 | import java.util.List; 6 | 7 | public interface AccountDao { 8 | List findAll(); 9 | 10 | Account findById(long id); 11 | 12 | void save(Account account); 13 | } 14 | -------------------------------------------------------------------------------- /jpa-tx-management/src/main/java/com/bobocode/dao/impl/JpaAccountDao.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.dao.impl; 2 | 3 | import com.bobocode.dao.AccountDao; 4 | import com.bobocode.model.Account; 5 | import org.springframework.stereotype.Repository; 6 | import org.springframework.transaction.annotation.Transactional; 7 | 8 | import javax.persistence.EntityManager; 9 | import javax.persistence.PersistenceContext; 10 | import java.util.List; 11 | 12 | @Repository 13 | @Transactional // wraps object with transaction proxy using Spring AOP. Is applied to all public methods of a class 14 | public class JpaAccountDao implements AccountDao { 15 | @PersistenceContext // injects a EntityManager proxy, a "shared EntityManager" that is related to current transaction 16 | private EntityManager entityManager; 17 | 18 | @Override 19 | public List findAll() { 20 | return entityManager.createQuery("select a from Account a", Account.class).getResultList(); 21 | } 22 | 23 | @Override 24 | public Account findById(long id) { 25 | return entityManager.find(Account.class, id); 26 | } 27 | 28 | @Override 29 | public void save(Account account) { 30 | entityManager.persist(account); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /jpa-tx-management/src/main/java/com/bobocode/service/AccountService.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.service; 2 | 3 | import com.bobocode.dao.AccountDao; 4 | import com.bobocode.model.Account; 5 | import org.springframework.stereotype.Service; 6 | import org.springframework.transaction.annotation.Transactional; 7 | 8 | import java.math.BigDecimal; 9 | import java.util.List; 10 | 11 | @Service 12 | @Transactional// wraps object with transaction proxy using Spring AOP. Is applied to all public methods of a class 13 | public class AccountService { 14 | private AccountDao accountDao; 15 | 16 | public AccountService(AccountDao accountDao) { 17 | this.accountDao = accountDao; 18 | } 19 | 20 | public void save(Account account) { 21 | accountDao.save(account); 22 | } 23 | 24 | public void withdraw(long accountId, BigDecimal value) { 25 | Account account = accountDao.findById(accountId); 26 | account.setBalance(account.getBalance().subtract(value)); 27 | } 28 | 29 | @Transactional(readOnly = true) 30 | public void printAllAccounts() { 31 | List accounts = accountDao.findAll(); 32 | accounts.forEach(System.out::println); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /mvc-basics/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | 8 | com.bobocode 9 | spring-framework-tutorial 10 | 1.0-SNAPSHOT 11 | 12 | mvc-basics 13 | war 14 | 15 | 16 | 17 | org.springframework 18 | spring-webmvc 19 | 5.0.7.RELEASE 20 | 21 | 22 | javax.servlet 23 | javax.servlet-api 24 | 4.0.1 25 | provided 26 | 27 | 28 | com.bobocode 29 | spring-framework-tutorial-util 30 | 1.0-SNAPSHOT 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | org.apache.maven.plugins 39 | maven-war-plugin 40 | 2.6 41 | 42 | false 43 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /mvc-basics/src/main/java/com/bobocode/configs/BobocodeWebInitializer.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.configs; 2 | 3 | import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; 4 | 5 | 6 | public class BobocodeWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { 7 | @Override 8 | protected Class[] getRootConfigClasses() { 9 | return new Class[]{RootConfig.class}; 10 | } 11 | 12 | @Override 13 | protected Class[] getServletConfigClasses() { 14 | return new Class[]{WebConfig.class}; 15 | } 16 | 17 | @Override 18 | protected String[] getServletMappings() { 19 | return new String[]{"/"}; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /mvc-basics/src/main/java/com/bobocode/configs/RootConfig.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.configs; 2 | 3 | import org.springframework.context.annotation.ComponentScan; 4 | import org.springframework.context.annotation.ComponentScan.Filter; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.context.annotation.FilterType; 7 | import org.springframework.stereotype.Controller; 8 | import org.springframework.web.servlet.config.annotation.EnableWebMvc; 9 | 10 | @Configuration 11 | @ComponentScan(basePackages = "com.bobocode", excludeFilters = { 12 | @Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class), 13 | @Filter(type = FilterType.ANNOTATION, value = Controller.class) 14 | }) 15 | public class RootConfig { 16 | } 17 | -------------------------------------------------------------------------------- /mvc-basics/src/main/java/com/bobocode/configs/WebConfig.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.configs; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.ComponentScan; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.web.servlet.ViewResolver; 7 | import org.springframework.web.servlet.config.annotation.EnableWebMvc; 8 | import org.springframework.web.servlet.view.InternalResourceViewResolver; 9 | 10 | @Configuration 11 | @ComponentScan(basePackages = "com.bobocode.web") 12 | @EnableWebMvc 13 | public class WebConfig { 14 | @Bean 15 | public ViewResolver viewResolver() { 16 | InternalResourceViewResolver resolver = new InternalResourceViewResolver(); 17 | resolver.setPrefix("/WEB-INF/views/"); 18 | resolver.setSuffix(".jsp"); 19 | return resolver; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /mvc-basics/src/main/java/com/bobocode/web/controller/AccountController.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.web.controller; 2 | 3 | import com.bobocode.model.Account; 4 | import com.bobocode.util.TestDataGenerator; 5 | import org.springframework.format.annotation.DateTimeFormat; 6 | import org.springframework.stereotype.Controller; 7 | import org.springframework.ui.Model; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.PostMapping; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | 12 | @Controller 13 | @RequestMapping("/accounts") 14 | public class AccountController { 15 | 16 | @GetMapping("/generate") 17 | public String generate(Model model) { 18 | Account account = TestDataGenerator.getAccount(); 19 | model.addAttribute("account", account); 20 | return "account"; 21 | } 22 | 23 | /** 24 | * Handles POST request and forwards {@link Account} instance to the account.jsp view. Suppose you have an HTML form 25 | * that uses method POST and submits data to this controller. Spring will handle the request, create {@link Account} 26 | * instance and set all account fields that match form input parameters. 27 | * 28 | * @param account instance that is created using HTML form input parameters 29 | * @param model created and passed by Spring 30 | * @return the view name 31 | */ 32 | @PostMapping 33 | public String post(@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Account account, Model model) { 34 | model.addAttribute(account); 35 | return "account"; 36 | } 37 | 38 | @GetMapping("/add") 39 | public String getAccountForm() { 40 | return "accountForm"; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /mvc-basics/src/main/java/com/bobocode/web/controller/ParametrizedHelloController.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.web.controller; 2 | 3 | import org.springframework.stereotype.Controller; 4 | import org.springframework.web.bind.annotation.*; 5 | 6 | @Controller 7 | @RequestMapping("/hello") 8 | public class ParametrizedHelloController { 9 | 10 | @ResponseBody 11 | @GetMapping 12 | public String helloQueryParam(@RequestParam(defaultValue = "Bobo") String name) { 13 | return "

Hello, " + name + "

"; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /mvc-basics/src/main/java/com/bobocode/web/controller/WelcomeController.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.web.controller; 2 | 3 | import org.springframework.stereotype.Controller; 4 | import org.springframework.ui.Model; 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | 7 | @Controller 8 | public class WelcomeController { 9 | 10 | @GetMapping({"/", "/welcome"}) 11 | public String hello() { 12 | return "welcome"; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /mvc-basics/src/main/webapp/WEB-INF/views/account.jsp: -------------------------------------------------------------------------------- 1 | <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 | 3 | 4 | 5 | 7 | Account 8 | 9 | 10 | 11 |
12 |

Account generator

13 |

This pages generates an account data for you.

14 |
15 |

${account.firstName} ${account.lastName}

16 |

${account.email}

17 |

${account.birthday}

18 | Generate 19 | Enter data 20 |
21 | 22 | 23 | -------------------------------------------------------------------------------- /mvc-basics/src/main/webapp/WEB-INF/views/accountForm.jsp: -------------------------------------------------------------------------------- 1 | <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 | 3 | 4 | 5 | 7 | Account 8 | 9 | 10 |
11 |

Enter account data

12 |
13 |
14 | 15 |
16 |
17 | 18 |
19 |
20 | 21 |
22 |
23 | 24 |
25 | 26 | 27 |
28 |
29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /mvc-basics/src/main/webapp/WEB-INF/views/welcome.jsp: -------------------------------------------------------------------------------- 1 | <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 | 3 | 4 | 5 | Welcome to Bobocode! 6 | 7 | 8 |

Welcome to

9 |
10 | 12 |
13 | 14 | 15 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.bobocode 8 | spring-framework-tutorial 9 | 1.0-SNAPSHOT 10 | pom 11 | 12 | 13 | spring-framework-tutorial-model 14 | spring-framework-tutorial-util 15 | ioc-basics 16 | aop-basics 17 | mvc-basics 18 | rest-basics 19 | jpa-tx-management 20 | bean-overriding 21 | profiles-and-properties 22 | advanced-ioc 23 | 24 | 25 | 26 | 1.10 27 | 1.10 28 | 29 | 30 | 31 | 32 | org.projectlombok 33 | lombok 34 | 1.18.0 35 | 36 | 37 | org.springframework 38 | spring-context 39 | 5.0.7.RELEASE 40 | 41 | 42 | org.springframework 43 | spring-tx 44 | 5.0.7.RELEASE 45 | 46 | 47 | javax.annotation 48 | javax.annotation-api 49 | 1.3.2 50 | 51 | 52 | org.slf4j 53 | slf4j-simple 54 | 1.7.24 55 | 56 | 57 | 58 | 59 | 60 | 61 | org.apache.maven.plugins 62 | maven-war-plugin 63 | 2.6 64 | 65 | false 66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /profiles-and-properties/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-framework-tutorial 7 | com.bobocode 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | profiles-and-properties 13 | 14 | 15 | 16 | org.springframework 17 | spring-orm 18 | 5.0.7.RELEASE 19 | 20 | 21 | com.h2database 22 | h2 23 | 1.4.197 24 | 25 | 26 | org.postgresql 27 | postgresql 28 | 9.4-1202-jdbc4 29 | 30 | 31 | org.slf4j 32 | slf4j-simple 33 | 1.7.24 34 | 35 | 36 | org.hibernate.javax.persistence 37 | hibernate-jpa-2.1-api 38 | 1.0.2.Final 39 | 40 | 41 | org.hibernate 42 | hibernate-core 43 | 5.3.2.Final 44 | 45 | 46 | com.zaxxer 47 | HikariCP 48 | 3.2.0 49 | 50 | 51 | 52 | 53 | 54 | javax.xml.bind 55 | jaxb-api 56 | 2.2.11 57 | 58 | 59 | 60 | com.bobocode 61 | spring-framework-tutorial-util 62 | 1.0-SNAPSHOT 63 | 64 | 65 | -------------------------------------------------------------------------------- /profiles-and-properties/src/main/java/com/bobocode/ProfilesAndPropertiesExample.java: -------------------------------------------------------------------------------- 1 | package com.bobocode; 2 | 3 | import com.bobocode.config.RootConfig; 4 | import com.bobocode.model.Account; 5 | import com.bobocode.util.TestDataGenerator; 6 | import org.springframework.context.ApplicationContext; 7 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 8 | 9 | import javax.persistence.EntityManager; 10 | import javax.persistence.EntityManagerFactory; 11 | 12 | public class ProfilesAndPropertiesExample { 13 | private static EntityManagerFactory entityManagerFactory; 14 | 15 | public static void main(String[] args) { 16 | init(); 17 | Account account = TestDataGenerator.getAccount(); 18 | saveAccount(account); 19 | System.out.println(account); 20 | } 21 | 22 | private static void init() { 23 | ApplicationContext applicationContext = new AnnotationConfigApplicationContext(RootConfig.class); 24 | entityManagerFactory = applicationContext.getBean(EntityManagerFactory.class); 25 | } 26 | 27 | private static void saveAccount(Account account) { 28 | EntityManager entityManager = entityManagerFactory.createEntityManager(); 29 | entityManager.getTransaction().begin(); 30 | try { 31 | entityManager.persist(account); 32 | entityManager.getTransaction().commit(); 33 | } catch (Exception e) { 34 | entityManager.getTransaction().rollback(); 35 | throw e; 36 | } finally { 37 | entityManager.close(); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /profiles-and-properties/src/main/java/com/bobocode/config/JpaConfig.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.config; 2 | 3 | import com.zaxxer.hikari.HikariConfig; 4 | import com.zaxxer.hikari.HikariDataSource; 5 | import org.postgresql.ds.PGSimpleDataSource; 6 | import org.springframework.beans.factory.annotation.Value; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.context.annotation.Profile; 10 | import org.springframework.orm.jpa.JpaVendorAdapter; 11 | import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; 12 | import org.springframework.orm.jpa.vendor.Database; 13 | import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; 14 | 15 | import javax.sql.DataSource; 16 | 17 | @Configuration 18 | public class JpaConfig { 19 | @Value("${spring.datasource.url}") 20 | private String url; 21 | @Value("${spring.datasource.username}") 22 | private String user; 23 | @Value("${spring.datasource.password}") 24 | private String password; 25 | @Value("${spring.datasource.driver-class-name}") 26 | private String driverClassName; 27 | @Value("${spring.datasource.hikari.maximum-pool-size}") 28 | private Integer maxPoolSize; 29 | @Value("${spring.jpa.generate-ddl}") 30 | private boolean generateDdl; 31 | @Value("${spring.jpa.show-sql}") 32 | private boolean showSql; 33 | 34 | 35 | @Bean 36 | @Profile("dev") 37 | public DataSource dataSource() { 38 | PGSimpleDataSource dataSource = new PGSimpleDataSource(); 39 | dataSource.setUrl(url); 40 | dataSource.setUser(user); 41 | dataSource.setPassword(password); 42 | return dataSource; 43 | } 44 | 45 | @Bean 46 | @Profile("prod") 47 | public DataSource pooledDataSource(HikariConfig config) { 48 | return new HikariDataSource(config); 49 | } 50 | 51 | @Bean("dataSource") 52 | @Profile("prod") 53 | public HikariConfig hikariConfig() { 54 | HikariConfig hikariConfig = new HikariConfig(); 55 | hikariConfig.setJdbcUrl(url); 56 | hikariConfig.setUsername(user); 57 | hikariConfig.setPassword(password); 58 | hikariConfig.setDriverClassName(driverClassName); 59 | hikariConfig.setMaximumPoolSize(maxPoolSize); 60 | hikariConfig.setPoolName("springHikariCP"); 61 | hikariConfig.setConnectionTestQuery("SELECT 1"); 62 | 63 | return hikariConfig; 64 | } 65 | 66 | @Bean 67 | public JpaVendorAdapter jpaVendorAdapter() { 68 | HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter(); 69 | adapter.setDatabase(Database.POSTGRESQL); 70 | adapter.setShowSql(showSql); 71 | adapter.setGenerateDdl(generateDdl); 72 | return adapter; 73 | } 74 | 75 | @Bean("entityManagerFactory") 76 | public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(DataSource dataSource, JpaVendorAdapter vendorAdapter) { 77 | LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); 78 | emf.setDataSource(dataSource); 79 | emf.setJpaVendorAdapter(jpaVendorAdapter()); 80 | emf.setPackagesToScan("com.bobocode.model"); 81 | return emf; 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /profiles-and-properties/src/main/java/com/bobocode/config/RootConfig.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.ComponentScan; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.context.annotation.PropertySource; 7 | import org.springframework.orm.jpa.JpaTransactionManager; 8 | import org.springframework.transaction.PlatformTransactionManager; 9 | 10 | import javax.persistence.EntityManagerFactory; 11 | 12 | @Configuration 13 | @ComponentScan("com.bobocode") 14 | @PropertySource("classpath:application.properties") 15 | public class RootConfig { 16 | 17 | @Bean 18 | PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { 19 | return new JpaTransactionManager(entityManagerFactory); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /profiles-and-properties/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.profiles.active=dev 2 | spring.datasource.url=jdbc:postgresql://localhost:5432/bobocode_db 3 | spring.datasource.username=postgres 4 | spring.datasource.password=postgres 5 | spring.datasource.driver-class-name=org.postgresql.Driver 6 | spring.datasource.hikari.maximum-pool-size=20 7 | spring.jpa.generate-ddl=true 8 | spring.jpa.show-sql=true 9 | -------------------------------------------------------------------------------- /rest-basics/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | 8 | com.bobocode 9 | spring-framework-tutorial 10 | 1.0-SNAPSHOT 11 | 12 | rest-basics 13 | war 14 | 15 | 16 | 17 | org.springframework 18 | spring-webmvc 19 | 5.0.7.RELEASE 20 | 21 | 22 | javax.servlet 23 | javax.servlet-api 24 | 4.0.1 25 | provided 26 | 27 | 28 | com.bobocode 29 | spring-framework-tutorial-util 30 | 1.0-SNAPSHOT 31 | 32 | 33 | com.fasterxml.jackson.core 34 | jackson-core 35 | 2.9.7 36 | 37 | 38 | com.fasterxml.jackson.core 39 | jackson-databind 40 | 2.9.7 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | org.apache.maven.plugins 50 | maven-war-plugin 51 | 2.6 52 | 53 | false 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /rest-basics/src/main/java/com/bobocode/configs/AccountRestApiWebInitializer.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.configs; 2 | 3 | import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; 4 | 5 | 6 | public class AccountRestApiWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { 7 | @Override 8 | protected Class[] getRootConfigClasses() { 9 | return new Class[]{RootConfig.class}; 10 | } 11 | 12 | @Override 13 | protected Class[] getServletConfigClasses() { 14 | return new Class[]{WebConfig.class}; 15 | } 16 | 17 | @Override 18 | protected String[] getServletMappings() { 19 | return new String[]{"/"}; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /rest-basics/src/main/java/com/bobocode/configs/RootConfig.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.configs; 2 | 3 | import org.springframework.context.annotation.ComponentScan; 4 | import org.springframework.context.annotation.ComponentScan.Filter; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.context.annotation.FilterType; 7 | import org.springframework.stereotype.Controller; 8 | import org.springframework.web.servlet.config.annotation.EnableWebMvc; 9 | 10 | @Configuration 11 | @ComponentScan(basePackages = "com.bobocode", excludeFilters = { 12 | @Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class), 13 | @Filter(type = FilterType.ANNOTATION, value = Controller.class) 14 | }) 15 | public class RootConfig { 16 | } 17 | -------------------------------------------------------------------------------- /rest-basics/src/main/java/com/bobocode/configs/WebConfig.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.configs; 2 | 3 | import org.springframework.context.annotation.ComponentScan; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.web.servlet.config.annotation.EnableWebMvc; 6 | 7 | @Configuration 8 | @ComponentScan(basePackages = "com.bobocode.web") 9 | @EnableWebMvc 10 | public class WebConfig { 11 | 12 | } 13 | -------------------------------------------------------------------------------- /rest-basics/src/main/java/com/bobocode/exception/EntityNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.exception; 2 | 3 | public class EntityNotFoundException extends RuntimeException { 4 | public EntityNotFoundException(String message) { 5 | super(message); 6 | } 7 | 8 | public EntityNotFoundException(String message, Throwable cause) { 9 | super(message, cause); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /rest-basics/src/main/java/com/bobocode/service/AccountService.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.service; 2 | 3 | 4 | import com.bobocode.exception.EntityNotFoundException; 5 | import com.bobocode.model.Account; 6 | import com.bobocode.model.User; 7 | import org.springframework.stereotype.Service; 8 | 9 | import java.util.*; 10 | 11 | @Service 12 | public class AccountService { 13 | 14 | private Map accountMap = new HashMap<>(); 15 | 16 | public List findAll() { 17 | return new ArrayList<>(accountMap.values()); 18 | } 19 | 20 | public void save(Account account) { 21 | if (account.getId() == null) { 22 | long id = accountMap.size() + 1; 23 | account.setId(id); 24 | accountMap.put(id, account); 25 | } else { 26 | accountMap.put(account.getId(), account); 27 | } 28 | } 29 | 30 | public void save(Long id, Account account){ 31 | 32 | } 33 | 34 | public Account findById(Long id) { 35 | Account account = accountMap.get(id); 36 | if (account == null) { 37 | throw new EntityNotFoundException("Account not found by id=" + id); 38 | } else { 39 | return account; 40 | } 41 | } 42 | 43 | public void remove(Account account) { 44 | if (account.getId() != null) { 45 | accountMap.remove(account.getId()); 46 | } 47 | } 48 | 49 | 50 | } 51 | -------------------------------------------------------------------------------- /rest-basics/src/main/java/com/bobocode/web/WebAppExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.web; 2 | 3 | import com.bobocode.exception.EntityNotFoundException; 4 | import org.springframework.http.HttpStatus; 5 | import org.springframework.http.ResponseEntity; 6 | import org.springframework.web.bind.annotation.ControllerAdvice; 7 | import org.springframework.web.bind.annotation.ExceptionHandler; 8 | 9 | @ControllerAdvice 10 | public class WebAppExceptionHandler { 11 | 12 | @ExceptionHandler(EntityNotFoundException.class) 13 | public ResponseEntity handleEntityNotFound(EntityNotFoundException e){ 14 | return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /rest-basics/src/main/java/com/bobocode/web/controller/AccountRestController.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.web.controller; 2 | 3 | import com.bobocode.model.Account; 4 | import com.bobocode.service.AccountService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.web.bind.annotation.*; 7 | 8 | import java.util.List; 9 | import java.util.Objects; 10 | 11 | @RestController 12 | @RequestMapping(value = "/accounts") 13 | public class AccountRestController { 14 | 15 | @Autowired 16 | private AccountService accountService; 17 | 18 | @GetMapping 19 | public List getAll() { 20 | return accountService.findAll(); 21 | } 22 | 23 | @GetMapping(value = "/{id}") 24 | public Account get(@PathVariable Long id) { 25 | return accountService.findById(id); 26 | } 27 | 28 | @PostMapping 29 | public void postUser(@RequestBody Account account) { 30 | accountService.save(account); 31 | } 32 | 33 | @PutMapping("/{id}") 34 | public void updateUser(@PathVariable Long id, @RequestBody Account account) { 35 | if (!Objects.equals(id, account.getId())) { 36 | throw new IllegalStateException("Invalid account id"); 37 | } 38 | accountService.save(account); 39 | } 40 | 41 | @DeleteMapping("/{id}") 42 | public void removeUser(@PathVariable Long id) { 43 | Account account = accountService.findById(id); 44 | accountService.remove(account); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /rest-basics/src/main/java/com/bobocode/web/controller/WelcomeController.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.web.controller; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RestController; 5 | 6 | @RestController 7 | public class WelcomeController { 8 | 9 | @GetMapping 10 | public String welcome() { 11 | return "

Welcome to Spring REST example

"; 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /spring-framework-tutorial-model/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | 8 | com.bobocode 9 | spring-framework-tutorial 10 | 1.0-SNAPSHOT 11 | 12 | spring-framework-tutorial-model 13 | 14 | 15 | 16 | org.hibernate.javax.persistence 17 | hibernate-jpa-2.1-api 18 | 1.0.2.Final 19 | 20 | 21 | org.hibernate 22 | hibernate-core 23 | 5.3.2.Final 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /spring-framework-tutorial-model/src/main/java/com/bobocode/model/Account.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.model; 2 | 3 | import lombok.*; 4 | 5 | import javax.persistence.*; 6 | import java.math.BigDecimal; 7 | import java.time.LocalDate; 8 | import java.time.LocalDateTime; 9 | 10 | @NoArgsConstructor 11 | @Getter @Setter 12 | @ToString 13 | @EqualsAndHashCode(of = "email") 14 | @Entity 15 | @Table(name = "accounts") 16 | public class Account { 17 | @Id 18 | @GeneratedValue 19 | private Long id; 20 | 21 | @Column(name = "first_name") 22 | private String firstName; 23 | 24 | @Column(name = "last_name") 25 | private String lastName; 26 | 27 | @Column(name = "email", unique = true) 28 | private String email; 29 | 30 | @Column(name = "birthday") 31 | private LocalDate birthday; 32 | 33 | @Column(name = "gender") 34 | @Enumerated(EnumType.STRING) 35 | private Gender gender; 36 | 37 | @Column(name = "creation_time") 38 | private LocalDateTime creationTime; 39 | 40 | @Column(name = "balance") 41 | private BigDecimal balance = BigDecimal.ZERO; 42 | } 43 | -------------------------------------------------------------------------------- /spring-framework-tutorial-model/src/main/java/com/bobocode/model/Address.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.model; 2 | 3 | 4 | import lombok.Data; 5 | import lombok.EqualsAndHashCode; 6 | import lombok.ToString; 7 | 8 | import java.time.LocalDateTime; 9 | 10 | @Data 11 | @ToString(exclude = {"user", "creationDate"}) 12 | @EqualsAndHashCode(exclude = "id") 13 | public class Address { 14 | private Long id; 15 | private String city; 16 | private String street; 17 | private String streetNumber; 18 | private String apartmentNumber; 19 | private String zipCode; 20 | private LocalDateTime creationDate; 21 | private User user; 22 | } 23 | -------------------------------------------------------------------------------- /spring-framework-tutorial-model/src/main/java/com/bobocode/model/Credentials.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.model; 2 | 3 | import lombok.*; 4 | 5 | import java.time.LocalDateTime; 6 | 7 | @Data 8 | @EqualsAndHashCode(of = "email") 9 | @ToString(exclude = {"lastModifiedPassword"}) 10 | public class Credentials { 11 | private String email; 12 | private String password; 13 | private LocalDateTime lastModifiedPassword; 14 | } 15 | -------------------------------------------------------------------------------- /spring-framework-tutorial-model/src/main/java/com/bobocode/model/Gender.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.model; 2 | 3 | public enum Gender { 4 | MALE, 5 | FEMALE 6 | } 7 | -------------------------------------------------------------------------------- /spring-framework-tutorial-model/src/main/java/com/bobocode/model/Role.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.model; 2 | 3 | import lombok.*; 4 | 5 | import java.time.LocalDateTime; 6 | 7 | @Data 8 | @ToString(exclude = {"user","creationDate"}) 9 | @EqualsAndHashCode(of = {"roleType", "user"}) 10 | public class Role { 11 | private Long id; 12 | private RoleType roleType; 13 | private LocalDateTime creationDate = LocalDateTime.now(); 14 | 15 | private User user; 16 | 17 | public Role(RoleType roleType) { 18 | this.roleType = roleType; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /spring-framework-tutorial-model/src/main/java/com/bobocode/model/RoleType.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.model; 2 | 3 | public enum RoleType { 4 | USER, ADMIN, OPERATOR, CUSTOMER 5 | } 6 | -------------------------------------------------------------------------------- /spring-framework-tutorial-model/src/main/java/com/bobocode/model/User.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.model; 2 | 3 | import lombok.*; 4 | 5 | import java.time.LocalDate; 6 | import java.util.HashSet; 7 | import java.util.Set; 8 | 9 | 10 | @NoArgsConstructor 11 | @Getter @Setter @ToString 12 | @EqualsAndHashCode(of = "credentials") 13 | public class User { 14 | private Long id; 15 | private String firstName; 16 | private String lastName; 17 | private LocalDate birthday; 18 | private LocalDate creationDate; 19 | private Credentials credentials; 20 | private Address address; 21 | private Set roles = new HashSet<>(); 22 | 23 | public User(String firstName, String lastName, LocalDate birthday, Credentials credentials) { 24 | this.firstName = firstName; 25 | this.lastName = lastName; 26 | this.birthday = birthday; 27 | this.credentials = credentials; 28 | this.creationDate = LocalDate.now(); 29 | } 30 | 31 | public void addRole(Role role) { 32 | roles.add(role); 33 | role.setUser(this); 34 | } 35 | 36 | 37 | } 38 | -------------------------------------------------------------------------------- /spring-framework-tutorial-util/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | 8 | com.bobocode 9 | spring-framework-tutorial 10 | 1.0-SNAPSHOT 11 | 12 | spring-framework-tutorial-util 13 | 14 | 15 | 16 | com.bobocode 17 | spring-framework-tutorial-model 18 | 1.0-SNAPSHOT 19 | 20 | 21 | io.codearte.jfairy 22 | jfairy 23 | 0.5.7 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /spring-framework-tutorial-util/src/main/java/com/bobocode/util/TestDataGenerator.java: -------------------------------------------------------------------------------- 1 | package com.bobocode.util; 2 | 3 | 4 | import com.bobocode.model.*; 5 | import io.codearte.jfairy.Fairy; 6 | import io.codearte.jfairy.producer.person.Person; 7 | 8 | import java.math.BigDecimal; 9 | import java.time.LocalDate; 10 | import java.time.LocalDateTime; 11 | import java.util.List; 12 | import java.util.Random; 13 | import java.util.Set; 14 | import java.util.function.Predicate; 15 | import java.util.stream.LongStream; 16 | import java.util.stream.Stream; 17 | 18 | import static java.util.stream.Collectors.toList; 19 | import static java.util.stream.Collectors.toSet; 20 | import static java.util.stream.IntStream.range; 21 | 22 | public class TestDataGenerator { 23 | 24 | public static Set generateRoleSet() { 25 | Random random = new Random(); 26 | Predicate randomPredicate = i -> random.nextBoolean(); 27 | 28 | return Stream.of(RoleType.values()) 29 | .filter(randomPredicate) 30 | .map(Role::new) 31 | .collect(toSet()); 32 | } 33 | 34 | public static User generateUser(RoleType... roles) { 35 | User user = generateUser(); 36 | Stream.of(roles) 37 | .map(Role::new) 38 | .forEach(user::addRole); 39 | 40 | return user; 41 | } 42 | 43 | 44 | public static User generateUser() { 45 | Fairy fairy = Fairy.create(); 46 | Person person = fairy.person(); 47 | 48 | User user = new User(); 49 | user.setFirstName(person.getFirstName()); 50 | user.setLastName(person.getLastName()); 51 | user.setBirthday(LocalDate.of( 52 | person.getDateOfBirth().getYear(), 53 | person.getDateOfBirth().getMonthOfYear(), 54 | person.getDateOfBirth().getDayOfMonth())); 55 | user.setCreationDate(LocalDate.now()); 56 | 57 | Credentials credentials = new Credentials(); 58 | credentials.setEmail(person.getEmail()); 59 | credentials.setPassword(person.getPassword()); 60 | credentials.setLastModifiedPassword(LocalDateTime.now()); 61 | 62 | user.setCredentials(credentials); 63 | 64 | return user; 65 | } 66 | 67 | public static Address generateAddess() { 68 | Fairy fairy = Fairy.create(); 69 | Person person = fairy.person(); 70 | 71 | Address address = new Address(); 72 | address.setCity(person.getAddress().getCity()); 73 | address.setStreet(person.getAddress().getStreet()); 74 | address.setStreetNumber(person.getAddress().getStreetNumber()); 75 | address.setApartmentNumber(person.getAddress().getApartmentNumber()); 76 | address.setCreationDate(LocalDateTime.now()); 77 | address.setZipCode(person.getAddress().getPostalCode()); 78 | 79 | return address; 80 | } 81 | 82 | public static User generateUserWithAddressAndRoles(){ 83 | User user = generateUser(); 84 | user.setAddress(generateAddess()); 85 | user.setRoles(generateRoleSet()); 86 | return user; 87 | } 88 | 89 | public static List generateUserList(int maxSize){ 90 | Random random = new Random(); 91 | int size = random.nextInt(maxSize); 92 | 93 | return LongStream.rangeClosed(1L, size) 94 | .mapToObj(i-> { 95 | User user = generateUserWithAddressAndRoles(); 96 | user.setId(i); 97 | return user; 98 | }) 99 | .collect(toList()); 100 | } 101 | 102 | public static Account getAccount(){ 103 | Fairy fairy = Fairy.create(); 104 | Person person = fairy.person(); 105 | Random random = new Random(); 106 | 107 | 108 | Account fakeAccount = new Account(); 109 | fakeAccount.setFirstName(person.getFirstName()); 110 | fakeAccount.setLastName(person.getLastName()); 111 | fakeAccount.setEmail(person.getEmail()); 112 | fakeAccount.setBirthday(LocalDate.of( 113 | person.getDateOfBirth().getYear(), 114 | person.getDateOfBirth().getMonthOfYear(), 115 | person.getDateOfBirth().getDayOfMonth())); 116 | fakeAccount.setGender(Gender.valueOf(person.getSex().name())); 117 | fakeAccount.setBalance(BigDecimal.valueOf(random.nextInt(200_000))); 118 | fakeAccount.setCreationTime(LocalDateTime.now()); 119 | 120 | return fakeAccount; 121 | } 122 | 123 | public static List getAccountList(int size){ 124 | return Stream.generate(TestDataGenerator::getAccount) 125 | .limit(size) 126 | .collect(toList()); 127 | } 128 | 129 | } --------------------------------------------------------------------------------