From 3bebbd4c0295740c95e6e75e17023154001bd2af Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 19 Jul 2020 14:32:35 +0530 Subject: [PATCH] JAVA-66: removed old modules spring-data-jpa-* --- .../spring-data-jpa-2/README.md | 12 - persistence-modules/spring-data-jpa-2/pom.xml | 48 -- .../main/java/com/baeldung/Application.java | 13 - .../baeldung/aggregation/model/Comment.java | 85 --- .../com/baeldung/aggregation/model/Post.java | 75 --- .../model/custom/CommentCount.java | 27 - .../model/custom/ICommentCount.java | 8 - .../repository/CommentRepository.java | 27 - .../com/baeldung/config/JpaPopulators.java | 35 -- .../baeldung/datajpadelete/entity/Book.java | 51 -- .../datajpadelete/entity/Category.java | 60 -- .../repository/BookRepository.java | 19 - .../repository/CategoryRepository.java | 9 - .../baeldung/embeddable/model/Company.java | 71 --- .../embeddable/model/ContactPerson.java | 38 -- .../repositories/CompanyRepository.java | 18 - .../java/com/baeldung/entity/Customer.java | 37 -- .../main/java/com/baeldung/entity/Fruit.java | 40 -- .../java/com/baeldung/entity/Passenger.java | 78 --- .../main/java/com/baeldung/entity/Song.java | 75 --- .../entitygraph/model/Characteristic.java | 43 -- .../com/baeldung/entitygraph/model/Item.java | 48 -- .../repository/CharacteristicsRepository.java | 13 - .../repository/ItemRepository.java | 13 - .../main/java/com/baeldung/exists/Car.java | 48 -- .../com/baeldung/exists/CarRepository.java | 24 - .../com/baeldung/joins/model/Department.java | 45 -- .../com/baeldung/joins/model/Employee.java | 69 --- .../java/com/baeldung/joins/model/Phone.java | 44 -- .../baeldung/projection/model/Address.java | 57 -- .../com/baeldung/projection/model/Person.java | 47 -- .../repository/AddressRepository.java | 11 - .../repository/PersonRepository.java | 14 - .../baeldung/projection/view/AddressView.java | 7 - .../baeldung/projection/view/PersonDto.java | 34 -- .../baeldung/projection/view/PersonView.java | 12 - .../repository/CustomerRepository.java | 19 - .../baeldung/repository/FruitRepository.java | 27 - .../repository/PassengerRepository.java | 14 - .../baeldung/repository/SongRepository.java | 21 - .../src/main/resources/apple-fruit-data.xml | 7 - .../resources/application-joins.properties | 1 - .../src/main/resources/application.properties | 1 - .../src/main/resources/db/import_joins.sql | 13 - .../src/main/resources/fruit-data.json | 14 - .../src/main/resources/guava-fruit-data.xml | 7 - .../SpringDataAggregateIntegrationTest.java | 107 ---- .../DeleteFromRepositoryUnitTest.java | 72 --- .../DeleteInRelationshipsUnitTest.java | 60 -- .../embeddable/EmbeddableIntegrationTest.java | 125 ---- .../EntityGraphIntegrationTest.java | 39 -- .../exists/CarRepositoryIntegrationTest.java | 87 --- .../joins/JpaJoinsIntegrationTest.java | 142 ----- .../JpaProjectionIntegrationTest.java | 63 -- .../CustomerRepositoryIntegrationTest.java | 64 -- .../FruitPopulatorIntegrationTest.java | 38 -- .../FruitRepositoryIntegrationTest.java | 75 --- .../PassengerRepositoryIntegrationTest.java | 54 -- .../SongRepositoryIntegrationTest.java | 58 -- .../src/test/resources/entitygraph-data.sql | 7 - .../resources/projection-clean-up-data.sql | 2 - .../test/resources/projection-insert-data.sql | 2 - .../test/resources/test-aggregation-data.sql | 7 - .../src/test/resources/test-fruit-data.sql | 6 - .../src/test/resources/test-song-data.sql | 8 - .../spring-data-jpa-3/README.md | 20 - persistence-modules/spring-data-jpa-3/pom.xml | 71 --- .../main/java/com/baeldung/Application.java | 14 - .../DatasourceProxyBeanPostProcessor.java | 53 -- .../baeldung/batchinserts/model/School.java | 45 -- .../baeldung/batchinserts/model/Student.java | 44 -- .../java/com/baeldung/boot/Application.java | 17 - .../boot/daos/CustomerRepository.java | 19 - .../daos/impl/PersonInsertRepository.java | 31 - .../boot/daos/user/UserRepository.java | 99 ---- .../boot/daos/user/UserRepositoryCustom.java | 14 - .../daos/user/UserRepositoryCustomImpl.java | 57 -- .../com/baeldung/boot/domain/Customer.java | 56 -- .../java/com/baeldung/boot/domain/Person.java | 47 -- .../com/baeldung/boot/domain/Possession.java | 83 --- .../java/com/baeldung/boot/domain/User.java | 132 ----- .../passenger/CustomPassengerRepository.java | 8 - .../baeldung/boot/passenger/Passenger.java | 82 --- .../boot/passenger/PassengerRepository.java | 22 - .../passenger/PassengerRepositoryImpl.java | 20 - .../web/controllers/CustomerController.java | 41 -- .../java/com/baeldung/entity/Employee.java | 36 -- .../java/com/baeldung/model/BasicUser.java | 42 -- .../multipledb/MultipleDbApplication.java | 14 - .../PersistenceProductConfiguration.java | 68 --- .../dao/product/ProductRepository.java | 13 - .../multipledb/model/product/Product.java | 67 --- .../repository/EmployeeRepository.java | 9 - .../baeldung/repository/UserRepository.java | 14 - .../src/main/resources/application.properties | 6 - .../src/main/resources/logback.xml | 13 - .../persistence-multiple-db.properties | 13 - .../java/com/baeldung/SpringContextTest.java | 17 - .../SpringJpaContextIntegrationTest.java | 19 - .../BatchInsertIntegrationTest.java | 40 -- .../JpaBatchInsertsIntegrationTest.java | 98 ---- .../JpaNoBatchInsertsIntegrationTest.java | 41 -- .../batchinserts/TestObjectHelper.java | 20 - ...PersonInsertRepositoryIntegrationTest.java | 82 --- .../boot/daos/UserRepositoryCommon.java | 545 ------------------ .../daos/UserRepositoryTCAutoLiveTest.java | 43 -- .../boot/daos/UserRepositoryTCLiveTest.java | 58 -- .../PassengerRepositoryIntegrationTest.java | 190 ------ .../ProductRepositoryIntegrationTest.java | 142 ----- .../EmployeeRepositoryIntegrationTest.java | 40 -- .../util/BaeldungPostgresqlContainer.java | 35 -- .../application-batchinserts.properties | 6 - .../resources/application-tc-auto.properties | 4 - .../test/resources/application-tc.properties | 4 - .../resources/application-test.properties | 2 - .../spring-data-jpa-4/README.md | 18 - .../spring-data-jpa-4/create.sql | 2 - persistence-modules/spring-data-jpa-4/pom.xml | 47 -- .../derivedquery/QueryApplication.java | 13 - .../baeldung/derivedquery/entity/User.java | 70 --- .../repository/UserRepository.java | 60 -- .../ElementCollectionApplication.java | 11 - .../elementcollection/model/Employee.java | 68 --- .../elementcollection/model/Phone.java | 62 -- .../repository/EmployeeRepository.java | 46 -- .../SpringBootLifecycleEventApplication.java | 11 - .../model/AuditTrailListener.java | 39 -- .../baeldung/lifecycleevents/model/User.java | 104 ---- .../repository/UserRepository.java | 9 - .../com/baeldung/like/LikeApplication.java | 13 - .../java/com/baeldung/like/model/Movie.java | 58 -- .../like/repository/MovieRepository.java | 41 -- .../com/baeldung/namingstrategy/Person.java | 35 -- .../namingstrategy/PersonRepository.java | 6 - .../QuotedLowerCaseNamingStrategy.java | 12 - .../QuotedUpperCaseNamingStrategy.java | 12 - ...ingDataJpaNamingConventionApplication.java | 7 - .../UnquotedLowerCaseNamingStrategy.java | 12 - .../UnquotedUpperCaseNamingStrategy.java | 12 - .../com/baeldung/osiv/OsivApplication.java | 13 - .../com/baeldung/osiv/model/BasicUser.java | 42 -- .../osiv/repository/BasicUserRepository.java | 19 - .../osiv/service/SimpleUserService.java | 25 - .../baeldung/osiv/service/UserService.java | 9 - .../baeldung/osiv/web/DetailedUserDto.java | 45 -- .../com/baeldung/osiv/web/UserController.java | 27 - .../StoredProcedureApplication.java | 13 - .../controller/CarController.java | 47 -- .../baeldung/storedprocedure/entity/Car.java | 41 -- .../repository/CarRepository.java | 34 -- .../storedprocedure/service/CarService.java | 39 -- .../java/com/baeldung/tx/TxApplication.java | 13 - .../java/com/baeldung/tx/model/Payment.java | 55 -- .../src/main/resources/application.properties | 5 - .../src/main/resources/car-mysql.sql | 27 - .../UserRepositoryIntegrationTest.java | 172 ------ .../ElementCollectionIntegrationTest.java | 64 -- .../like/MovieRepositoryIntegrationTest.java | 87 --- ...erCaseNamingStrategyH2IntegrationTest.java | 81 --- ...werCaseNamingStrategyPostgresLiveTest.java | 85 --- ...erCaseNamingStrategyH2IntegrationTest.java | 85 --- ...perCaseNamingStrategyPostgresLiveTest.java | 81 --- ...ysicalNamingStrategyH2IntegrationTest.java | 85 --- ...hysicalNamingStrategyPostgresLiveTest.java | 85 --- ...erCaseNamingStrategyH2IntegrationTest.java | 86 --- ...werCaseNamingStrategyPostgresLiveTest.java | 85 --- ...erCaseNamingStrategyH2IntegrationTest.java | 85 --- ...perCaseNamingStrategyPostgresLiveTest.java | 85 --- .../osiv/UserControllerIntegrationTest.java | 56 -- .../tx/ManualTransactionIntegrationTest.java | 152 ----- .../UserRepositoryIntegrationTest.java | 80 --- .../resources/application-test.properties | 2 - ...ase-naming-strategy-on-postgres.properties | 9 - ...oted-lower-case-naming-strategy.properties | 9 - ...ase-naming-strategy-on-postgres.properties | 9 - ...oted-upper-case-naming-strategy.properties | 9 - ...cal-naming-strategy-on-postgres.properties | 9 - ...spring-physical-naming-strategy.properties | 9 - ...ase-naming-strategy-on-postgres.properties | 9 - ...oted-lower-case-naming-strategy.properties | 9 - ...ase-naming-strategy-on-postgres.properties | 9 - ...oted-upper-case-naming-strategy.properties | 9 - .../src/test/resources/test-movie-cleanup.sql | 1 - .../src/test/resources/test-movie-data.sql | 7 - .../spring-data-jpa-5/README.md | 15 - persistence-modules/spring-data-jpa-5/pom.xml | 80 --- .../baeldung/composite/BookApplication.java | 12 - .../com/baeldung/composite/entity/Book.java | 47 -- .../com/baeldung/composite/entity/BookId.java | 51 -- .../composite/repository/BookRepository.java | 18 - .../PartialUpdateApplication.java | 12 - .../partialupdate/model/ContactPhone.java | 22 - .../partialupdate/model/Customer.java | 23 - .../partialupdate/model/CustomerDto.java | 31 - .../model/CustomerStructured.java | 27 - .../repository/ContactPhoneRepository.java | 12 - .../repository/CustomerRepository.java | 18 - .../CustomerStructuredRepository.java | 11 - .../service/CustomerService.java | 87 --- .../partialupdate/util/CustomerMapper.java | 15 - .../schemageneration/AccountApplication.java | 12 - .../schemageneration/HibernateUtil.java | 39 -- .../schemageneration/model/Account.java | 74 --- .../model/AccountSetting.java | 68 --- .../repository/AccountRepository.java | 8 - .../repository/AccountSettingRepository.java | 8 - .../src/main/resources/application.properties | 13 - .../BookRepositoryIntegrationTest.java | 64 -- .../partialupdate/PartialUpdateUnitTest.java | 63 -- .../AccountRepositoryIntegrationTest.java | 72 --- .../resources/application-test.properties | 3 - persistence-modules/spring-data-jpa/README.md | 25 - persistence-modules/spring-data-jpa/pom.xml | 77 --- .../java/com/baeldung/boot/Application.java | 17 - .../boot/config/PersistenceConfiguration.java | 23 - .../baeldung/boot/daos/ArticleRepository.java | 23 - .../boot/daos/CustomItemRepository.java | 16 - .../boot/daos/CustomItemTypeRepository.java | 13 - .../boot/daos/ExtendedRepository.java | 14 - .../boot/daos/ExtendedStudentRepository.java | 6 - .../boot/daos/IBarCrudRepository.java | 11 - .../java/com/baeldung/boot/daos/IFooDao.java | 13 - .../boot/daos/InventoryRepository.java | 8 - .../boot/daos/ItemTypeRepository.java | 10 - .../boot/daos/LocationRepository.java | 10 - .../boot/daos/ReadOnlyLocationRepository.java | 15 - .../baeldung/boot/daos/StoreRepository.java | 13 - .../daos/impl/CustomItemRepositoryImpl.java | 33 -- .../impl/CustomItemTypeRepositoryImpl.java | 27 - .../daos/impl/ExtendedRepositoryImpl.java | 37 -- .../boot/daos/user/PossessionRepository.java | 9 - .../boot/daos/user/UserRepository.java | 99 ---- .../boot/daos/user/UserRepositoryCustom.java | 14 - .../daos/user/UserRepositoryCustomImpl.java | 57 -- .../baeldung/boot/ddd/event/Aggregate.java | 46 -- .../baeldung/boot/ddd/event/Aggregate2.java | 44 -- .../boot/ddd/event/Aggregate2Repository.java | 10 - .../baeldung/boot/ddd/event/Aggregate3.java | 23 - .../boot/ddd/event/Aggregate3Repository.java | 14 - .../boot/ddd/event/AggregateRepository.java | 10 - .../baeldung/boot/ddd/event/DddConfig.java | 15 - .../baeldung/boot/ddd/event/DomainEvent.java | 8 - .../boot/ddd/event/DomainService.java | 31 - .../com/baeldung/boot/domain/Article.java | 23 - .../java/com/baeldung/boot/domain/Bar.java | 220 ------- .../java/com/baeldung/boot/domain/Foo.java | 94 --- .../java/com/baeldung/boot/domain/Item.java | 81 --- .../com/baeldung/boot/domain/ItemType.java | 46 -- .../java/com/baeldung/boot/domain/KVTag.java | 34 -- .../com/baeldung/boot/domain/Location.java | 55 -- .../boot/domain/MerchandiseEntity.java | 66 --- .../com/baeldung/boot/domain/Possession.java | 83 --- .../com/baeldung/boot/domain/SkillTag.java | 30 - .../java/com/baeldung/boot/domain/Store.java | 76 --- .../com/baeldung/boot/domain/Student.java | 74 --- .../java/com/baeldung/boot/domain/User.java | 132 ----- .../baeldung/boot/services/IBarService.java | 7 - .../baeldung/boot/services/IFooService.java | 14 - .../baeldung/boot/services/IOperations.java | 26 - .../boot/services/impl/AbstractService.java | 61 -- .../impl/AbstractSpringDataJpaService.java | 45 -- .../impl/BarSpringDataJpaService.java | 31 - .../boot/services/impl/FooService.java | 55 -- .../multipledb/MultipleDbApplication.java | 14 - .../PersistenceProductAutoConfiguration.java | 71 --- .../PersistenceProductConfiguration.java | 68 --- .../PersistenceUserAutoConfiguration.java | 75 --- .../PersistenceUserConfiguration.java | 69 --- .../dao/product/ProductRepository.java | 14 - .../dao/user/PossessionRepository.java | 9 - .../multipledb/dao/user/UserRepository.java | 8 - .../multipledb/model/product/Product.java | 67 --- .../model/user/PossessionMultipleDB.java | 82 --- .../multipledb/model/user/UserMultipleDB.java | 88 --- .../src/main/resources/application.properties | 6 - .../src/main/resources/ddd.properties | 1 - .../src/main/resources/import_entities.sql | 21 - .../src/main/resources/logback.xml | 13 - .../persistence-multiple-db-boot.properties | 11 - .../persistence-multiple-db.properties | 13 - .../src/main/resources/persistence.properties | 14 - .../java/com/baeldung/SpringContextTest.java | 17 - .../SpringJpaContextIntegrationTest.java | 25 - .../ArticleRepositoryIntegrationTest.java | 67 --- ...endedStudentRepositoryIntegrationTest.java | 41 -- .../InventoryRepositoryIntegrationTest.java | 61 -- .../daos/JpaRepositoriesIntegrationTest.java | 93 --- .../boot/daos/UserRepositoryCommon.java | 545 ------------------ .../daos/UserRepositoryIntegrationTest.java | 37 -- .../daos/UserRepositoryTCAutoLiveTest.java | 43 -- .../boot/daos/UserRepositoryTCLiveTest.java | 58 -- .../Aggregate2EventsIntegrationTest.java | 72 --- .../Aggregate3EventsIntegrationTest.java | 67 --- .../event/AggregateEventsIntegrationTest.java | 87 --- .../boot/ddd/event/TestEventHandler.java | 14 - ...ractServicePersistenceIntegrationTest.java | 252 -------- .../FooServicePersistenceIntegrationTest.java | 75 --- .../SpringDataJPABarAuditIntegrationTest.java | 75 --- .../JpaMultipleDBIntegrationTest.java | 96 --- .../ProductRepositoryIntegrationTest.java | 144 ----- .../util/BaeldungPostgresqlContainer.java | 35 -- .../test/java/com/baeldung/util/IDUtil.java | 33 -- .../resources/application-tc-auto.properties | 4 - .../test/resources/application-tc.properties | 4 - 304 files changed, 13445 deletions(-) delete mode 100644 persistence-modules/spring-data-jpa-2/README.md delete mode 100644 persistence-modules/spring-data-jpa-2/pom.xml delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/Application.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/Comment.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/Post.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/custom/CommentCount.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/custom/ICommentCount.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/repository/CommentRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/config/JpaPopulators.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/entity/Book.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/entity/Category.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/repository/BookRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/repository/CategoryRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/model/Company.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/model/ContactPerson.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/repositories/CompanyRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Customer.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Fruit.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Passenger.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Song.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/model/Characteristic.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/model/Item.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/repository/CharacteristicsRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/repository/ItemRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/exists/Car.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/exists/CarRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Department.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Employee.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Phone.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/model/Address.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/model/Person.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/repository/AddressRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/repository/PersonRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/AddressView.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/PersonDto.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/PersonView.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/CustomerRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/FruitRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/PassengerRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/SongRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/resources/apple-fruit-data.xml delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/resources/application-joins.properties delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/resources/application.properties delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/resources/db/import_joins.sql delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/resources/fruit-data.json delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/resources/guava-fruit-data.xml delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteFromRepositoryUnitTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteInRelationshipsUnitTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/embeddable/EmbeddableIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/entitygraph/EntityGraphIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/joins/JpaJoinsIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/projection/JpaProjectionIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/CustomerRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitPopulatorIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/PassengerRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/SongRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/resources/entitygraph-data.sql delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/resources/projection-clean-up-data.sql delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/resources/projection-insert-data.sql delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/resources/test-aggregation-data.sql delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/resources/test-fruit-data.sql delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/resources/test-song-data.sql delete mode 100644 persistence-modules/spring-data-jpa-3/README.md delete mode 100644 persistence-modules/spring-data-jpa-3/pom.xml delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/Application.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/DatasourceProxyBeanPostProcessor.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/model/School.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/model/Student.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/Application.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/CustomerRepository.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/impl/PersonInsertRepository.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepository.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustom.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustomImpl.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Customer.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Person.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Possession.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/User.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/CustomPassengerRepository.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/Passenger.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/PassengerRepository.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/PassengerRepositoryImpl.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/web/controllers/CustomerController.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/entity/Employee.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/model/BasicUser.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/Product.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/repository/EmployeeRepository.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/repository/UserRepository.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/resources/application.properties delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/resources/logback.xml delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/resources/persistence-multiple-db.properties delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/SpringContextTest.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/BatchInsertIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/JpaBatchInsertsIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/JpaNoBatchInsertsIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/TestObjectHelper.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/PersonInsertRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/passenger/PassengerRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/repository/EmployeeRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/resources/application-batchinserts.properties delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/resources/application-tc-auto.properties delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/resources/application-tc.properties delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/resources/application-test.properties delete mode 100644 persistence-modules/spring-data-jpa-4/README.md delete mode 100644 persistence-modules/spring-data-jpa-4/create.sql delete mode 100644 persistence-modules/spring-data-jpa-4/pom.xml delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/QueryApplication.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/entity/User.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/repository/UserRepository.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/ElementCollectionApplication.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Employee.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Phone.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/SpringBootLifecycleEventApplication.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/model/AuditTrailListener.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/model/User.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/repository/UserRepository.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/LikeApplication.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/model/Movie.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/repository/MovieRepository.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/PersonRepository.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/OsivApplication.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/model/BasicUser.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/repository/BasicUserRepository.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/service/SimpleUserService.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/service/UserService.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/web/DetailedUserDto.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/web/UserController.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/StoredProcedureApplication.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/controller/CarController.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/entity/Car.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/repository/CarRepository.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/service/CarService.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/tx/TxApplication.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/tx/model/Payment.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/resources/application.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/resources/car-mysql.sql delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/osiv/UserControllerIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/tx/ManualTransactionIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/lifecycleevents/UserRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/application-test.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/test-movie-cleanup.sql delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/test-movie-data.sql delete mode 100644 persistence-modules/spring-data-jpa-5/README.md delete mode 100644 persistence-modules/spring-data-jpa-5/pom.xml delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/BookApplication.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/entity/Book.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/entity/BookId.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/repository/BookRepository.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/PartialUpdateApplication.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/ContactPhone.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/Customer.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/CustomerDto.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/CustomerStructured.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/ContactPhoneRepository.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/CustomerRepository.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/CustomerStructuredRepository.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/service/CustomerService.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/util/CustomerMapper.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/AccountApplication.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/HibernateUtil.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/model/Account.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/model/AccountSetting.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/repository/AccountRepository.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/repository/AccountSettingRepository.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/resources/application.properties delete mode 100644 persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/composite/repository/BookRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/partialupdate/PartialUpdateUnitTest.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/schemageneration/AccountRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/test/resources/application-test.properties delete mode 100644 persistence-modules/spring-data-jpa/README.md delete mode 100644 persistence-modules/spring-data-jpa/pom.xml delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/Application.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/config/PersistenceConfiguration.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ArticleRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/CustomItemRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/CustomItemTypeRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ExtendedRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ExtendedStudentRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/IBarCrudRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/IFooDao.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/InventoryRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ItemTypeRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/LocationRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ReadOnlyLocationRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/StoreRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/CustomItemRepositoryImpl.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/CustomItemTypeRepositoryImpl.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/ExtendedRepositoryImpl.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/PossessionRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustom.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustomImpl.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate2.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate2Repository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate3.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate3Repository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/AggregateRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DddConfig.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DomainEvent.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DomainService.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Article.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Bar.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Foo.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Item.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/ItemType.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/KVTag.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Location.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/MerchandiseEntity.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Possession.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/SkillTag.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Store.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Student.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/User.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IBarService.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IFooService.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IOperations.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/AbstractService.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/AbstractSpringDataJpaService.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/BarSpringDataJpaService.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/FooService.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceProductAutoConfiguration.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceUserAutoConfiguration.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceUserConfiguration.java delete mode 100755 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/user/PossessionRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/user/UserRepository.java delete mode 100755 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/product/Product.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/user/PossessionMultipleDB.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/user/UserMultipleDB.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/resources/application.properties delete mode 100644 persistence-modules/spring-data-jpa/src/main/resources/ddd.properties delete mode 100644 persistence-modules/spring-data-jpa/src/main/resources/import_entities.sql delete mode 100644 persistence-modules/spring-data-jpa/src/main/resources/logback.xml delete mode 100644 persistence-modules/spring-data-jpa/src/main/resources/persistence-multiple-db-boot.properties delete mode 100644 persistence-modules/spring-data-jpa/src/main/resources/persistence-multiple-db.properties delete mode 100644 persistence-modules/spring-data-jpa/src/main/resources/persistence.properties delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/SpringContextTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/ArticleRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/ExtendedStudentRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/JpaRepositoriesIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/Aggregate2EventsIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/Aggregate3EventsIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/AggregateEventsIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/TestEventHandler.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/AbstractServicePersistenceIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/FooServicePersistenceIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/SpringDataJPABarAuditIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/multipledb/JpaMultipleDBIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/util/IDUtil.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/resources/application-tc-auto.properties delete mode 100644 persistence-modules/spring-data-jpa/src/test/resources/application-tc.properties diff --git a/persistence-modules/spring-data-jpa-2/README.md b/persistence-modules/spring-data-jpa-2/README.md deleted file mode 100644 index e59aca7c69..0000000000 --- a/persistence-modules/spring-data-jpa-2/README.md +++ /dev/null @@ -1,12 +0,0 @@ -### Relevant Articles: -- [Spring Data JPA – Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby) -- [JPA Join Types](https://www.baeldung.com/jpa-join-types) -- [Case Insensitive Queries with Spring Data Repository](https://www.baeldung.com/spring-data-case-insensitive-queries) -- [The Exists Query in Spring Data](https://www.baeldung.com/spring-data-exists-query) -- [Spring Data JPA Repository Populators](https://www.baeldung.com/spring-data-jpa-repository-populators) -- [Spring Data JPA and Null Parameters](https://www.baeldung.com/spring-data-jpa-null-parameters) -- [Spring Data JPA Projections](https://www.baeldung.com/spring-data-jpa-projections) -- [JPA @Embedded And @Embeddable](https://www.baeldung.com/jpa-embedded-embeddable) -- [Spring Data JPA Delete and Relationships](https://www.baeldung.com/spring-data-jpa-delete) -- [Spring Data JPA and Named Entity Graphs](https://www.baeldung.com/spring-data-jpa-named-entity-graphs) -- [Customizing the Result of JPA Queries with Aggregation Functions](https://www.baeldung.com/jpa-queries-custom-result-with-aggregation-functions) diff --git a/persistence-modules/spring-data-jpa-2/pom.xml b/persistence-modules/spring-data-jpa-2/pom.xml deleted file mode 100644 index 838327de89..0000000000 --- a/persistence-modules/spring-data-jpa-2/pom.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - 4.0.0 - spring-data-jpa-2 - spring-data-jpa-2 - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - com.h2database - h2 - - - - net.ttddyy - datasource-proxy - ${datasource-proxy.version} - - - - com.fasterxml.jackson.core - jackson-databind - - - - org.springframework - spring-oxm - - - - - 1.4.1 - - - \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/Application.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/Application.java deleted file mode 100644 index 3ea3d113da..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/Application.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/Comment.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/Comment.java deleted file mode 100644 index 26c2373cbe..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/Comment.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.baeldung.aggregation.model; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.ManyToOne; -import java.util.Objects; - -@Entity -public class Comment { - @Id - private Integer id; - private Integer year; - private boolean approved; - private String content; - @ManyToOne - private Post post; - - public Comment() { - } - - public Comment(int id, int year, boolean approved, String content, Post post) { - this.id = id; - this.year = year; - this.approved = approved; - this.content = content; - this.post = post; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public Integer getYear() { - return year; - } - - public void setYear(Integer year) { - this.year = year; - } - - public boolean isApproved() { - return approved; - } - - public void setApproved(boolean approved) { - this.approved = approved; - } - - public String getContent() { - return content; - } - - public void setContent(String content) { - this.content = content; - } - - public Post getPost() { - return post; - } - - public void setPost(Post post) { - this.post = post; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof Comment)) { - return false; - } - Comment comment = (Comment) o; - return getId().equals(comment.getId()); - } - - @Override - public int hashCode() { - return Objects.hash(getId()); - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/Post.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/Post.java deleted file mode 100644 index f396e080ae..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/Post.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.aggregation.model; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import java.util.List; -import java.util.Objects; - -@Entity -public class Post { - @Id - private Integer id; - private String title; - private String content; - @OneToMany(mappedBy = "post") - private List comments; - - public Post() { - } - - public Post(Integer id, String title, String content) { - this.id = id; - this.title = title; - this.content = content; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getContent() { - return content; - } - - public void setContent(String content) { - this.content = content; - } - - public List getComments() { - return comments; - } - - public void setComments(List comments) { - this.comments = comments; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof Post)) { - return false; - } - Post post = (Post) o; - return getId().equals(post.getId()); - } - - @Override - public int hashCode() { - return Objects.hash(getId()); - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/custom/CommentCount.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/custom/CommentCount.java deleted file mode 100644 index 510b52a47c..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/custom/CommentCount.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.aggregation.model.custom; - -public class CommentCount { - private Integer year; - private Long total; - - public CommentCount(Integer year, Long total) { - this.year = year; - this.total = total; - } - - public Integer getYear() { - return year; - } - - public void setYear(Integer year) { - this.year = year; - } - - public Long getTotal() { - return total; - } - - public void setTotal(Long total) { - this.total = total; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/custom/ICommentCount.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/custom/ICommentCount.java deleted file mode 100644 index acb25cfd49..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/custom/ICommentCount.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.aggregation.model.custom; - -public interface ICommentCount { - - Integer getYearComment(); - - Long getTotalComment(); -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/repository/CommentRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/repository/CommentRepository.java deleted file mode 100644 index 89e9345e94..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/repository/CommentRepository.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.aggregation.repository; - -import com.baeldung.aggregation.model.Comment; -import com.baeldung.aggregation.model.custom.CommentCount; -import com.baeldung.aggregation.model.custom.ICommentCount; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.stereotype.Repository; - -import java.util.List; - -@Repository -public interface CommentRepository extends JpaRepository { - - @Query("SELECT c.year, COUNT(c.year) FROM Comment AS c GROUP BY c.year ORDER BY c.year DESC") - List countTotalCommentsByYear(); - - @Query("SELECT new com.baeldung.aggregation.model.custom.CommentCount(c.year, COUNT(c.year)) FROM Comment AS c GROUP BY c.year ORDER BY c.year DESC") - List countTotalCommentsByYearClass(); - - @Query("SELECT c.year AS yearComment, COUNT(c.year) AS totalComment FROM Comment AS c GROUP BY c.year ORDER BY c.year DESC") - List countTotalCommentsByYearInterface(); - - @Query(value = "SELECT c.year AS yearComment, COUNT(c.*) AS totalComment FROM comment AS c GROUP BY c.year ORDER BY c.year DESC", nativeQuery = true) - List countTotalCommentsByYearNative(); - -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/config/JpaPopulators.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/config/JpaPopulators.java deleted file mode 100644 index 24348d31c5..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/config/JpaPopulators.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; -import org.springframework.data.repository.init.Jackson2RepositoryPopulatorFactoryBean; -import org.springframework.data.repository.init.UnmarshallerRepositoryPopulatorFactoryBean; -import org.springframework.oxm.jaxb.Jaxb2Marshaller; - -import com.baeldung.entity.Fruit; - -@Configuration -public class JpaPopulators { - - @Bean - public Jackson2RepositoryPopulatorFactoryBean getRespositoryPopulator() throws Exception { - Jackson2RepositoryPopulatorFactoryBean factory = new Jackson2RepositoryPopulatorFactoryBean(); - factory.setResources(new Resource[] { new ClassPathResource("fruit-data.json") }); - return factory; - } - - @Bean - public UnmarshallerRepositoryPopulatorFactoryBean repositoryPopulator() { - - Jaxb2Marshaller unmarshaller = new Jaxb2Marshaller(); - unmarshaller.setClassesToBeBound(Fruit.class); - - UnmarshallerRepositoryPopulatorFactoryBean factory = new UnmarshallerRepositoryPopulatorFactoryBean(); - factory.setUnmarshaller(unmarshaller); - factory.setResources(new Resource[] { new ClassPathResource("apple-fruit-data.xml"), new ClassPathResource("guava-fruit-data.xml") }); - return factory; - } - -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/entity/Book.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/entity/Book.java deleted file mode 100644 index deac24548a..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/entity/Book.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.datajpadelete.entity; - -import javax.persistence.*; - -@Entity -public class Book { - - @Id - @GeneratedValue - private Long id; - private String title; - - @ManyToOne - private Category category; - - public Book() { - } - - public Book(String title) { - this.title = title; - } - - public Book(String title, Category category) { - this.title = title; - this.category = category; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public Category getCategory() { - return category; - } - - public void setCategory(Category category) { - this.category = category; - } -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/entity/Category.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/entity/Category.java deleted file mode 100644 index 16f1a4157f..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/entity/Category.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.datajpadelete.entity; - -import javax.persistence.*; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -@Entity -public class Category { - - @Id - @GeneratedValue - private Long id; - private String name; - - @OneToMany(mappedBy = "category", cascade = CascadeType.ALL, orphanRemoval = true) - private List books; - - public Category() { - } - - public Category(String name) { - this.name = name; - } - - public Category(String name, Book... books) { - this.name = name; - this.books = Stream.of(books).collect(Collectors.toList()); - this.books.forEach(x -> x.setCategory(this)); - } - - public Category(String name, List books) { - this.name = name; - this.books = books; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getBooks() { - return books; - } - - public void setBooks(List books) { - this.books = books; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/repository/BookRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/repository/BookRepository.java deleted file mode 100644 index 5d0f45f127..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/repository/BookRepository.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.datajpadelete.repository; - -import com.baeldung.datajpadelete.entity.Book; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.CrudRepository; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -@Repository -public interface BookRepository extends CrudRepository { - - long deleteByTitle(String title); - - @Modifying - @Query("delete from Book b where b.title=:title") - void deleteBooks(@Param("title") String title); - -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/repository/CategoryRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/repository/CategoryRepository.java deleted file mode 100644 index 6fe7058a78..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/repository/CategoryRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.datajpadelete.repository; - -import com.baeldung.datajpadelete.entity.Category; -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface CategoryRepository extends CrudRepository { -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/model/Company.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/model/Company.java deleted file mode 100644 index 203cff1e35..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/model/Company.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.baeldung.embeddable.model; - -import javax.persistence.AttributeOverride; -import javax.persistence.AttributeOverrides; -import javax.persistence.Column; -import javax.persistence.Embedded; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; - -@Entity -public class Company { - - @Id - @GeneratedValue - private Integer id; - - private String name; - - private String address; - - private String phone; - - @Embedded - @AttributeOverrides(value = { - @AttributeOverride( name = "firstName", column = @Column(name = "contact_first_name")), - @AttributeOverride( name = "lastName", column = @Column(name = "contact_last_name")), - @AttributeOverride( name = "phone", column = @Column(name = "contact_phone")) - }) - private ContactPerson contactPerson; - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - - public String getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone; - } - - public ContactPerson getContactPerson() { - return contactPerson; - } - - public void setContactPerson(ContactPerson contactPerson) { - this.contactPerson = contactPerson; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/model/ContactPerson.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/model/ContactPerson.java deleted file mode 100644 index 561da80878..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/model/ContactPerson.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.embeddable.model; - -import javax.persistence.Embeddable; - -@Embeddable -public class ContactPerson { - - private String firstName; - - private String lastName; - - private String phone; - - 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 getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone; - } - -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/repositories/CompanyRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/repositories/CompanyRepository.java deleted file mode 100644 index f456b15652..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/repositories/CompanyRepository.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.embeddable.repositories; - -import com.baeldung.embeddable.model.Company; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; - -import java.util.List; - -public interface CompanyRepository extends JpaRepository { - - List findByContactPersonFirstName(String firstName); - - @Query("SELECT C FROM Company C WHERE C.contactPerson.firstName = ?1") - List findByContactPersonFirstNameWithJPQL(String firstName); - - @Query(value = "SELECT * FROM company WHERE contact_first_name = ?1", nativeQuery = true) - List findByContactPersonFirstNameWithNativeQuery(String firstName); -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Customer.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Customer.java deleted file mode 100644 index efcae73853..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Customer.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.entity; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; - -@Entity -public class Customer { - - @Id - @GeneratedValue - private long id; - private String name; - private String email; - - public Customer(String name, String email) { - this.name = name; - this.email = email; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Fruit.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Fruit.java deleted file mode 100644 index d45ac33db8..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Fruit.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.entity; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement -@Entity -public class Fruit { - - @Id - private long id; - private String name; - private String color; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Passenger.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Passenger.java deleted file mode 100644 index 3aafbe9afa..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Passenger.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.baeldung.entity; - -import javax.persistence.Basic; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import java.util.Objects; - -@Entity -public class Passenger { - - @Id - @GeneratedValue - @Column(nullable = false) - private Long id; - - @Basic(optional = false) - @Column(nullable = false) - private String firstName; - - @Basic(optional = false) - @Column(nullable = false) - private String lastName; - - private Passenger(String firstName, String lastName) { - this.firstName = firstName; - this.lastName = lastName; - } - - public static Passenger from(String firstName, String lastName) { - return new Passenger(firstName, lastName); - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - 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; - } - - @Override - public String toString() { - return "Passenger{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + '}'; - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - Passenger passenger = (Passenger) o; - return Objects.equals(firstName, passenger.firstName) && Objects.equals(lastName, passenger.lastName); - } - - @Override - public int hashCode() { - return Objects.hash(firstName, lastName); - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Song.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Song.java deleted file mode 100644 index 395527c1eb..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Song.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.entity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import java.time.LocalDateTime; - -@Entity -public class Song { - - @Id private long id; - private String name; - @Column(name = "length_in_seconds") - private int lengthInSeconds; - private String compositor; - private String singer; - private LocalDateTime released; - private String genre; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getLengthInSeconds() { - return lengthInSeconds; - } - - public void setLengthInSeconds(int lengthInSeconds) { - this.lengthInSeconds = lengthInSeconds; - } - - public String getCompositor() { - return compositor; - } - - public void setCompositor(String compositor) { - this.compositor = compositor; - } - - public String getSinger() { - return singer; - } - - public void setSinger(String singer) { - this.singer = singer; - } - - public LocalDateTime getReleased() { - return released; - } - - public void setReleased(LocalDateTime released) { - this.released = released; - } - - public String getGenre() { - return genre; - } - - public void setGenre(String genre) { - this.genre = genre; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/model/Characteristic.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/model/Characteristic.java deleted file mode 100644 index ae20375572..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/model/Characteristic.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.entitygraph.model; - -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; - -@Entity -public class Characteristic { - - @Id - private Long id; - private String type; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn - private Item item; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public Item getItem() { - return item; - } - - public void setItem(Item item) { - this.item = item; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/model/Item.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/model/Item.java deleted file mode 100644 index e90a22ef62..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/model/Item.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.entitygraph.model; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.NamedAttributeNode; -import javax.persistence.NamedEntityGraph; -import javax.persistence.OneToMany; - -@Entity -@NamedEntityGraph(name = "Item.characteristics", - attributeNodes = @NamedAttributeNode("characteristics") -) -public class Item { - - @Id - private Long id; - private String name; - - @OneToMany(mappedBy = "item") - private List characteristics = new ArrayList<>(); - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getCharacteristics() { - return characteristics; - } - - public void setCharacteristics(List characteristics) { - this.characteristics = characteristics; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/repository/CharacteristicsRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/repository/CharacteristicsRepository.java deleted file mode 100644 index 9f923ab241..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/repository/CharacteristicsRepository.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.entitygraph.repository; - -import org.springframework.data.jpa.repository.EntityGraph; -import org.springframework.data.jpa.repository.JpaRepository; - -import com.baeldung.entitygraph.model.Characteristic; - -public interface CharacteristicsRepository extends JpaRepository { - - @EntityGraph(attributePaths = {"item"}) - Characteristic findByType(String type); - -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/repository/ItemRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/repository/ItemRepository.java deleted file mode 100644 index b2a5f223b3..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/repository/ItemRepository.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.entitygraph.repository; - -import org.springframework.data.jpa.repository.EntityGraph; -import org.springframework.data.jpa.repository.EntityGraph.EntityGraphType; -import org.springframework.data.jpa.repository.JpaRepository; - -import com.baeldung.entitygraph.model.Item; - -public interface ItemRepository extends JpaRepository { - - @EntityGraph(value = "Item.characteristics", type = EntityGraphType.FETCH) - Item findByName(String name); -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/exists/Car.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/exists/Car.java deleted file mode 100644 index bf09caf6ff..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/exists/Car.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.exists; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; - -/** - * @author paullatzelsperger - * @since 2019-03-20 - */ -@Entity -public class Car { - - @Id - @GeneratedValue - private int id; - private Integer power; - private String model; - - Car() { - - } - - public Car(int power, String model) { - this.power = power; - this.model = model; - } - - public Integer getPower() { - return power; - } - - public void setPower(Integer power) { - this.power = power; - } - - public String getModel() { - return model; - } - - public void setModel(String model) { - this.model = model; - } - - public int getId() { - return id; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/exists/CarRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/exists/CarRepository.java deleted file mode 100644 index a54f19f4cd..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/exists/CarRepository.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.exists; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -/** - * @author paullatzelsperger - * @since 2019-03-20 - */ -@Repository -public interface CarRepository extends JpaRepository { - - boolean existsCarByPower(int power); - - boolean existsCarByModel(String model); - - @Query("select case when count(c)> 0 then true else false end from Car c where c.model = :model") - boolean existsCarExactCustomQuery(@Param("model") String model); - - @Query("select case when count(c)> 0 then true else false end from Car c where lower(c.model) like lower(:model)") - boolean existsCarLikeCustomQuery(@Param("model") String model); -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Department.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Department.java deleted file mode 100644 index 439f7532f5..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Department.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.baeldung.joins.model; - -import java.util.List; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; - -@Entity -public class Department { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - private String name; - - @OneToMany(mappedBy = "department") - private List employees; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getEmployees() { - return employees; - } - - public void setEmployees(List employees) { - this.employees = employees; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Employee.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Employee.java deleted file mode 100644 index 277274e61c..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Employee.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.baeldung.joins.model; - -import java.util.List; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.Table; - -@Entity -@Table(name = "joins_employee") -public class Employee { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private long id; - - private String name; - - private int age; - - @ManyToOne - private Department department; - - @OneToMany(mappedBy = "employee") - private List phones; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - public Department getDepartment() { - return department; - } - - public void setDepartment(Department department) { - this.department = department; - } - - public List getPhones() { - return phones; - } - - public void setPhones(List phones) { - this.phones = phones; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Phone.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Phone.java deleted file mode 100644 index 41382915b1..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Phone.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.joins.model; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; - -@Entity -public class Phone { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private long id; - - private String number; - - @ManyToOne - private Employee employee; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getNumber() { - return number; - } - - public void setNumber(String number) { - this.number = number; - } - - public Employee getEmployee() { - return employee; - } - - public void setEmployee(Employee employee) { - this.employee = employee; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/model/Address.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/model/Address.java deleted file mode 100644 index 0c5a3eac60..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/model/Address.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.projection.model; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.OneToOne; - -@Entity -public class Address { - @Id - private Long id; - @OneToOne - private Person person; - private String state; - private String city; - private String street; - private String zipCode; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getState() { - return state; - } - - public void setState(String state) { - this.state = state; - } - - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city; - } - - public String getStreet() { - return street; - } - - public void setStreet(String street) { - this.street = street; - } - - public String getZipCode() { - return zipCode; - } - - public void setZipCode(String zipCode) { - this.zipCode = zipCode; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/model/Person.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/model/Person.java deleted file mode 100644 index d18bd1c72d..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/model/Person.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.projection.model; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.OneToOne; - -@Entity -public class Person { - @Id - private Long id; - private String firstName; - private String lastName; - @OneToOne(mappedBy = "person") - private Address address; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - 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 Address getAddress() { - return address; - } - - public void setAddress(Address address) { - this.address = address; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/repository/AddressRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/repository/AddressRepository.java deleted file mode 100644 index c1053f4867..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/repository/AddressRepository.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.projection.repository; - -import com.baeldung.projection.view.AddressView; -import com.baeldung.projection.model.Address; -import org.springframework.data.repository.Repository; - -import java.util.List; - -public interface AddressRepository extends Repository { - List getAddressByState(String state); -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/repository/PersonRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/repository/PersonRepository.java deleted file mode 100644 index 64bc7471e6..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/repository/PersonRepository.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.projection.repository; - -import com.baeldung.projection.model.Person; -import com.baeldung.projection.view.PersonDto; -import com.baeldung.projection.view.PersonView; -import org.springframework.data.repository.Repository; - -public interface PersonRepository extends Repository { - PersonView findByLastName(String lastName); - - PersonDto findByFirstName(String firstName); - - T findByLastName(String lastName, Class type); -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/AddressView.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/AddressView.java deleted file mode 100644 index 7a24a1e9b9..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/AddressView.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.projection.view; - -public interface AddressView { - String getZipCode(); - - PersonView getPerson(); -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/PersonDto.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/PersonDto.java deleted file mode 100644 index 1fd924450b..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/PersonDto.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.projection.view; - -import java.util.Objects; - -public class PersonDto { - private final String firstName; - private final String lastName; - - public PersonDto(String firstName, String lastName) { - this.firstName = firstName; - this.lastName = lastName; - } - - public String getFirstName() { - return firstName; - } - - public String getLastName() { - return lastName; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - PersonDto personDto = (PersonDto) o; - return Objects.equals(firstName, personDto.firstName) && Objects.equals(lastName, personDto.lastName); - } - - @Override - public int hashCode() { - return Objects.hash(firstName, lastName); - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/PersonView.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/PersonView.java deleted file mode 100644 index 36777ec26f..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/PersonView.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.projection.view; - -import org.springframework.beans.factory.annotation.Value; - -public interface PersonView { - String getFirstName(); - - String getLastName(); - - @Value("#{target.firstName + ' ' + target.lastName}") - String getFullName(); -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/CustomerRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/CustomerRepository.java deleted file mode 100644 index 65b22bbd84..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/CustomerRepository.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.repository; - -import com.baeldung.entity.Customer; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; - -import java.util.List; - -public interface CustomerRepository extends JpaRepository { - - List findByName(String name); - - List findByNameAndEmail(String name, String email); - - @Query("SELECT c FROM Customer c WHERE (:name is null or c.name = :name) and (:email is null or c.email = :email)") - List findCustomerByNameAndEmail(@Param("name") String name, @Param("email") String email); - -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/FruitRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/FruitRepository.java deleted file mode 100644 index 5055252adf..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/FruitRepository.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.repository; - -import java.util.List; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -import com.baeldung.entity.Fruit; - -@Repository -public interface FruitRepository extends JpaRepository { - - Long deleteByName(String name); - - List deleteByColor(String color); - - Long removeByName(String name); - - List removeByColor(String color); - - @Modifying - @Query("delete from Fruit f where f.name=:name or f.color=:color") - int deleteFruits(@Param("name") String name, @Param("color") String color); -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/PassengerRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/PassengerRepository.java deleted file mode 100644 index a295a74f1b..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/PassengerRepository.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.repository; - -import com.baeldung.entity.Passenger; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.List; - -@Repository -interface PassengerRepository extends JpaRepository { - - List findByFirstNameIgnoreCase(String firstName); - -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/SongRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/SongRepository.java deleted file mode 100644 index ad887fe680..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/SongRepository.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.repository; - -import com.baeldung.entity.Song; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.List; - -@Repository -public interface SongRepository extends JpaRepository { - - List findByNameLike(String name); - - List findByNameNotLike(String name); - - List findByNameStartingWith(String startingWith); - - List findByNameEndingWith(String endingWith); - - List findBySingerContaining(String singer); -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/resources/apple-fruit-data.xml b/persistence-modules/spring-data-jpa-2/src/main/resources/apple-fruit-data.xml deleted file mode 100644 index d87ae28f1e..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/resources/apple-fruit-data.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - 1 - apple - red - diff --git a/persistence-modules/spring-data-jpa-2/src/main/resources/application-joins.properties b/persistence-modules/spring-data-jpa-2/src/main/resources/application-joins.properties deleted file mode 100644 index fe2270293b..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/resources/application-joins.properties +++ /dev/null @@ -1 +0,0 @@ -spring.datasource.data=classpath:db/import_joins.sql diff --git a/persistence-modules/spring-data-jpa-2/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-2/src/main/resources/application.properties deleted file mode 100644 index 72fc330767..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -spring.jpa.show-sql=true \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/main/resources/db/import_joins.sql b/persistence-modules/spring-data-jpa-2/src/main/resources/db/import_joins.sql deleted file mode 100644 index e4772d6ff2..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/resources/db/import_joins.sql +++ /dev/null @@ -1,13 +0,0 @@ -INSERT INTO department (id, name) VALUES (1, 'Infra'); -INSERT INTO department (id, name) VALUES (2, 'Accounting'); -INSERT INTO department (id, name) VALUES (3, 'Management'); - -INSERT INTO joins_employee (id, name, age, department_id) VALUES (1, 'Baeldung', '35', 1); -INSERT INTO joins_employee (id, name, age, department_id) VALUES (2, 'John', '35', 2); -INSERT INTO joins_employee (id, name, age, department_id) VALUES (3, 'Jane', '35', 2); - -INSERT INTO phone (id, number, employee_id) VALUES (1, '111', 1); -INSERT INTO phone (id, number, employee_id) VALUES (2, '222', 1); -INSERT INTO phone (id, number, employee_id) VALUES (3, '333', 1); - -COMMIT; diff --git a/persistence-modules/spring-data-jpa-2/src/main/resources/fruit-data.json b/persistence-modules/spring-data-jpa-2/src/main/resources/fruit-data.json deleted file mode 100644 index 6dc44e2586..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/resources/fruit-data.json +++ /dev/null @@ -1,14 +0,0 @@ -[ - { - "_class": "com.baeldung.entity.Fruit", - "name": "apple", - "color": "red", - "id": 1 - }, - { - "_class": "com.baeldung.entity.Fruit", - "name": "guava", - "color": "green", - "id": 2 - } -] \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/main/resources/guava-fruit-data.xml b/persistence-modules/spring-data-jpa-2/src/main/resources/guava-fruit-data.xml deleted file mode 100644 index ffd75bb4bb..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/resources/guava-fruit-data.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - 2 - guava - green - diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java deleted file mode 100644 index 779ade7a3f..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.baeldung.aggregation; - -import com.baeldung.aggregation.model.custom.CommentCount; -import com.baeldung.aggregation.model.custom.ICommentCount; -import com.baeldung.aggregation.repository.CommentRepository; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.jdbc.Sql; -import org.springframework.test.context.junit4.SpringRunner; - -import java.util.List; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -@RunWith(SpringRunner.class) -@DataJpaTest - -@Sql(scripts = "/test-aggregation-data.sql") -public class SpringDataAggregateIntegrationTest { - - @Autowired - private CommentRepository commentRepository; - - @Test - public void whenQueryWithAggregation_thenReturnResult() { - List commentCountsByYear = commentRepository.countTotalCommentsByYear(); - - Object[] countYear2019 = commentCountsByYear.get(0); - - assertThat(countYear2019[0], is(Integer.valueOf(2019))); - assertThat(countYear2019[1], is(1l)); - - Object[] countYear2018 = commentCountsByYear.get(1); - - assertThat(countYear2018[0], is(Integer.valueOf(2018))); - assertThat(countYear2018[1], is(2l)); - - Object[] countYear2017 = commentCountsByYear.get(2); - - assertThat(countYear2017[0], is(Integer.valueOf(2017))); - assertThat(countYear2017[1], is(1l)); - } - - @Test - public void whenQueryWithAggregation_thenReturnCustomResult() { - List commentCountsByYear = commentRepository.countTotalCommentsByYearClass(); - - CommentCount countYear2019 = commentCountsByYear.get(0); - - assertThat(countYear2019.getYear(), is(Integer.valueOf(2019))); - assertThat(countYear2019.getTotal(), is(1l)); - - CommentCount countYear2018 = commentCountsByYear.get(1); - - assertThat(countYear2018.getYear(), is(Integer.valueOf(2018))); - assertThat(countYear2018.getTotal(), is(2l)); - - CommentCount countYear2017 = commentCountsByYear.get(2); - - assertThat(countYear2017.getYear(), is(Integer.valueOf(2017))); - assertThat(countYear2017.getTotal(), is(1l)); - } - - @Test - public void whenQueryWithAggregation_thenReturnInterfaceResult() { - List commentCountsByYear = commentRepository.countTotalCommentsByYearInterface(); - - ICommentCount countYear2019 = commentCountsByYear.get(0); - - assertThat(countYear2019.getYearComment(), is(Integer.valueOf(2019))); - assertThat(countYear2019.getTotalComment(), is(1l)); - - ICommentCount countYear2018 = commentCountsByYear.get(1); - - assertThat(countYear2018.getYearComment(), is(Integer.valueOf(2018))); - assertThat(countYear2018.getTotalComment(), is(2l)); - - ICommentCount countYear2017 = commentCountsByYear.get(2); - - assertThat(countYear2017.getYearComment(), is(Integer.valueOf(2017))); - assertThat(countYear2017.getTotalComment(), is(1l)); - } - - @Test - public void whenNativeQueryWithAggregation_thenReturnInterfaceResult() { - List commentCountsByYear = commentRepository.countTotalCommentsByYearNative(); - - ICommentCount countYear2019 = commentCountsByYear.get(0); - - assertThat(countYear2019.getYearComment(), is(Integer.valueOf(2019))); - assertThat(countYear2019.getTotalComment(), is(1l)); - - ICommentCount countYear2018 = commentCountsByYear.get(1); - - assertThat(countYear2018.getYearComment(), is(Integer.valueOf(2018))); - assertThat(countYear2018.getTotalComment(), is(2l)); - - ICommentCount countYear2017 = commentCountsByYear.get(2); - - assertThat(countYear2017.getYearComment(), is(Integer.valueOf(2017))); - assertThat(countYear2017.getTotalComment(), is(1l)); - } - -} diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteFromRepositoryUnitTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteFromRepositoryUnitTest.java deleted file mode 100644 index 5f4a36bc0e..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteFromRepositoryUnitTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.baeldung.datajpadelete; - -import com.baeldung.Application; -import com.baeldung.datajpadelete.entity.Book; -import com.baeldung.datajpadelete.repository.BookRepository; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; - -import java.util.Arrays; - -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = {Application.class}) -public class DeleteFromRepositoryUnitTest { - - @Autowired - private BookRepository repository; - - Book book1; - Book book2; - - @Before - public void setup() { - book1 = new Book("The Hobbit"); - book2 = new Book("All Quiet on the Western Front"); - - repository.saveAll(Arrays.asList(book1, book2)); - } - - @After - public void teardown() { - repository.deleteAll(); - } - - @Test - public void whenDeleteByIdFromRepository_thenDeletingShouldBeSuccessful() { - repository.deleteById(book1.getId()); - - assertThat(repository.count()).isEqualTo(1); - } - - @Test - public void whenDeleteAllFromRepository_thenRepositoryShouldBeEmpty() { - repository.deleteAll(); - - assertThat(repository.count()).isEqualTo(0); - } - - @Test - @Transactional - public void whenDeleteFromDerivedQuery_thenDeletingShouldBeSuccessful() { - long deletedRecords = repository.deleteByTitle("The Hobbit"); - - assertThat(deletedRecords).isEqualTo(1); - } - - @Test - @Transactional - public void whenDeleteFromCustomQuery_thenDeletingShouldBeSuccessful() { - repository.deleteBooks("The Hobbit"); - - assertThat(repository.count()).isEqualTo(1); - } - -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteInRelationshipsUnitTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteInRelationshipsUnitTest.java deleted file mode 100644 index 6275ace6e0..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteInRelationshipsUnitTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.datajpadelete; - -import com.baeldung.Application; -import com.baeldung.datajpadelete.entity.Book; -import com.baeldung.datajpadelete.entity.Category; -import com.baeldung.datajpadelete.repository.BookRepository; -import com.baeldung.datajpadelete.repository.CategoryRepository; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = {Application.class}) -public class DeleteInRelationshipsUnitTest { - - @Autowired - private BookRepository bookRepository; - - @Autowired - private CategoryRepository categoryRepository; - - @Before - public void setup() { - Book book1 = new Book("The Hobbit"); - Category category1 = new Category("Cat1", book1); - categoryRepository.save(category1); - - Book book2 = new Book("All Quiet on the Western Front"); - Category category2 = new Category("Cat2", book2); - categoryRepository.save(category2); - } - - @After - public void teardown() { - bookRepository.deleteAll(); - categoryRepository.deleteAll(); - } - - @Test - public void whenDeletingCategories_thenBooksShouldAlsoBeDeleted() { - categoryRepository.deleteAll(); - - assertThat(bookRepository.count()).isEqualTo(0); - assertThat(categoryRepository.count()).isEqualTo(0); - } - - @Test - public void whenDeletingBooks_thenCategoriesShouldAlsoBeDeleted() { - bookRepository.deleteAll(); - - assertThat(bookRepository.count()).isEqualTo(0); - assertThat(categoryRepository.count()).isEqualTo(2); - } -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/embeddable/EmbeddableIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/embeddable/EmbeddableIntegrationTest.java deleted file mode 100644 index b4c365a2d9..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/embeddable/EmbeddableIntegrationTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.baeldung.embeddable; - -import com.baeldung.Application; -import com.baeldung.embeddable.model.Company; -import com.baeldung.embeddable.model.ContactPerson; -import com.baeldung.embeddable.repositories.CompanyRepository; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -import static org.junit.Assert.assertEquals; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = {Application.class}) -public class EmbeddableIntegrationTest { - - @Autowired - private CompanyRepository companyRepository; - - @Test - @Transactional - public void whenInsertingCompany_thenEmbeddedContactPersonDetailsAreMapped() { - ContactPerson contactPerson = new ContactPerson(); - contactPerson.setFirstName("First"); - contactPerson.setLastName("Last"); - contactPerson.setPhone("123-456-789"); - - Company company = new Company(); - company.setName("Company"); - company.setAddress("1st street"); - company.setPhone("987-654-321"); - company.setContactPerson(contactPerson); - - companyRepository.save(company); - - Company result = companyRepository.getOne(company.getId()); - - assertEquals("Company", result.getName()); - assertEquals("1st street", result.getAddress()); - assertEquals("987-654-321", result.getPhone()); - assertEquals("First", result.getContactPerson().getFirstName()); - assertEquals("Last", result.getContactPerson().getLastName()); - assertEquals("123-456-789", result.getContactPerson().getPhone()); - } - - @Test - @Transactional - public void whenFindingCompanyByContactPersonAttribute_thenCompanyIsReturnedProperly() { - ContactPerson contactPerson = new ContactPerson(); - contactPerson.setFirstName("Name"); - contactPerson.setLastName("Last"); - contactPerson.setPhone("123-456-789"); - - Company company = new Company(); - company.setName("Company"); - company.setAddress("1st street"); - company.setPhone("987-654-321"); - company.setContactPerson(contactPerson); - - companyRepository.save(company); - - List result = companyRepository.findByContactPersonFirstName("Name"); - - assertEquals(1, result.size()); - - result = companyRepository.findByContactPersonFirstName("FirstName"); - - assertEquals(0, result.size()); - } - - @Test - @Transactional - public void whenFindingCompanyByContactPersonAttributeWithJPQL_thenCompanyIsReturnedProperly() { - ContactPerson contactPerson = new ContactPerson(); - contactPerson.setFirstName("@QueryName"); - contactPerson.setLastName("Last"); - contactPerson.setPhone("123-456-789"); - - Company company = new Company(); - company.setName("Company"); - company.setAddress("1st street"); - company.setPhone("987-654-321"); - company.setContactPerson(contactPerson); - - companyRepository.save(company); - - List result = companyRepository.findByContactPersonFirstNameWithJPQL("@QueryName"); - - assertEquals(1, result.size()); - - result = companyRepository.findByContactPersonFirstNameWithJPQL("FirstName"); - - assertEquals(0, result.size()); - } - - @Test - @Transactional - public void whenFindingCompanyByContactPersonAttributeWithNativeQuery_thenCompanyIsReturnedProperly() { - ContactPerson contactPerson = new ContactPerson(); - contactPerson.setFirstName("NativeQueryName"); - contactPerson.setLastName("Last"); - contactPerson.setPhone("123-456-789"); - - Company company = new Company(); - company.setName("Company"); - company.setAddress("1st street"); - company.setPhone("987-654-321"); - company.setContactPerson(contactPerson); - - companyRepository.save(company); - - List result = companyRepository.findByContactPersonFirstNameWithNativeQuery("NativeQueryName"); - - assertEquals(1, result.size()); - - result = companyRepository.findByContactPersonFirstNameWithNativeQuery("FirstName"); - - assertEquals(0, result.size()); - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/entitygraph/EntityGraphIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/entitygraph/EntityGraphIntegrationTest.java deleted file mode 100644 index 24880a5dff..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/entitygraph/EntityGraphIntegrationTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.entitygraph; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.jdbc.Sql; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.entitygraph.model.Characteristic; -import com.baeldung.entitygraph.model.Item; -import com.baeldung.entitygraph.repository.CharacteristicsRepository; -import com.baeldung.entitygraph.repository.ItemRepository; - -@DataJpaTest -@RunWith(SpringRunner.class) -@Sql(scripts = "/entitygraph-data.sql") -public class EntityGraphIntegrationTest { - - @Autowired - private ItemRepository itemRepo; - - @Autowired - private CharacteristicsRepository characteristicsRepo; - - @Test - public void givenEntityGraph_whenCalled_shouldRetrunDefinedFields() { - Item item = itemRepo.findByName("Table"); - assertThat(item.getId()).isEqualTo(1L); - } - - @Test - public void givenAdhocEntityGraph_whenCalled_shouldRetrunDefinedFields() { - Characteristic characteristic = characteristicsRepo.findByType("Rigid"); - assertThat(characteristic.getId()).isEqualTo(1L); - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java deleted file mode 100644 index d99f6671a3..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.baeldung.exists; - -import com.baeldung.Application; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.data.domain.Example; -import org.springframework.data.domain.ExampleMatcher; -import org.springframework.test.context.junit4.SpringRunner; - -import java.util.Arrays; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.ignoreCase; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = {Application.class}) -public class CarRepositoryIntegrationTest { - - @Autowired - private CarRepository repository; - private int searchId; - - @Before - public void setup() { - List cars = repository.saveAll(Arrays.asList(new Car(200, "BMW"), new Car(300, "Audi"))); - searchId = cars.get(0).getId(); - } - - @After - public void teardown() { - repository.deleteAll(); - } - - @Test - public void whenIdIsCorrect_thenExistsShouldReturnTrue() { - assertThat(repository.existsById(searchId)).isTrue(); - } - - @Test - public void givenExample_whenExists_thenIsTrue() { - ExampleMatcher modelMatcher = ExampleMatcher.matching() - .withIgnorePaths("id") // must explicitly ignore -> PK - .withMatcher("model", ignoreCase()); - Car probe = new Car(); - probe.setModel("bmw"); - - Example example = Example.of(probe, modelMatcher); - - assertThat(repository.exists(example)).isTrue(); - } - - @Test - public void givenPower_whenExists_thenIsFalse() { - assertThat(repository.existsCarByPower(200)).isTrue(); - assertThat(repository.existsCarByPower(800)).isFalse(); - } - - @Test - public void existsByDerivedQuery_byModel() { - assertThat(repository.existsCarByModel("Audi")).isTrue(); - assertThat(repository.existsCarByModel("audi")).isFalse(); - assertThat(repository.existsCarByModel("AUDI")).isFalse(); - assertThat(repository.existsCarByModel("")).isFalse(); - } - - @Test - public void givenModelName_whenExistsExact_thenIsTrue() { - assertThat(repository.existsCarExactCustomQuery("BMW")).isTrue(); - assertThat(repository.existsCarExactCustomQuery("Bmw")).isFalse(); - assertThat(repository.existsCarExactCustomQuery("bmw")).isFalse(); - assertThat(repository.existsCarExactCustomQuery("")).isFalse(); - } - - @Test - public void givenModelName_whenExistsLike_thenIsTrue() { - assertThat(repository.existsCarLikeCustomQuery("BMW")).isTrue(); - assertThat(repository.existsCarLikeCustomQuery("Bmw")).isTrue(); - assertThat(repository.existsCarLikeCustomQuery("bmw")).isTrue(); - assertThat(repository.existsCarLikeCustomQuery("")).isFalse(); - } - -} diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/joins/JpaJoinsIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/joins/JpaJoinsIntegrationTest.java deleted file mode 100644 index 9b0d23f3e4..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/joins/JpaJoinsIntegrationTest.java +++ /dev/null @@ -1,142 +0,0 @@ -package com.baeldung.joins; - -import static org.assertj.core.api.Assertions.assertThat; - -import com.baeldung.joins.model.Department; -import com.baeldung.joins.model.Phone; -import java.util.Collection; -import java.util.List; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.TypedQuery; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@DataJpaTest -@ActiveProfiles("joins") -public class JpaJoinsIntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - @Test - public void whenPathExpressionIsUsedForSingleValuedAssociation_thenCreatesImplicitInnerJoin() { - TypedQuery query = entityManager.createQuery("SELECT e.department FROM Employee e", Department.class); - - List resultList = query.getResultList(); - - assertThat(resultList).hasSize(3); - assertThat(resultList).extracting("name") - .containsOnly("Infra", "Accounting", "Accounting"); - } - - @Test - public void whenJoinKeywordIsUsed_thenCreatesExplicitInnerJoin() { - TypedQuery query = entityManager.createQuery("SELECT d FROM Employee e JOIN e.department d", Department.class); - - List resultList = query.getResultList(); - - assertThat(resultList).hasSize(3); - assertThat(resultList).extracting("name") - .containsOnly("Infra", "Accounting", "Accounting"); - } - - @Test - public void whenInnerJoinKeywordIsUsed_thenCreatesExplicitInnerJoin() { - TypedQuery query = entityManager.createQuery("SELECT d FROM Employee e INNER JOIN e.department d", Department.class); - - List resultList = query.getResultList(); - - assertThat(resultList).hasSize(3); - assertThat(resultList).extracting("name") - .containsOnly("Infra", "Accounting", "Accounting"); - } - - @Test - public void whenEntitiesAreListedInFromAndMatchedInWhere_ThenCreatesJoin() { - TypedQuery query = entityManager.createQuery("SELECT d FROM Employee e, Department d WHERE e.department = d", Department.class); - - List resultList = query.getResultList(); - - assertThat(resultList).hasSize(3); - assertThat(resultList).extracting("name") - .containsOnly("Infra", "Accounting", "Accounting"); - } - - @Test - public void whenEntitiesAreListedInFrom_ThenCreatesCartesianProduct() { - TypedQuery query = entityManager.createQuery("SELECT d FROM Employee e, Department d", Department.class); - - List resultList = query.getResultList(); - - assertThat(resultList).hasSize(9); - assertThat(resultList).extracting("name") - .containsOnly("Infra", "Accounting", "Management", "Infra", "Accounting", "Management", "Infra", "Accounting", "Management"); - } - - @Test - public void whenCollectionValuedAssociationIsJoined_ThenCanSelect() { - TypedQuery query = entityManager.createQuery("SELECT ph FROM Employee e JOIN e.phones ph WHERE ph LIKE '1%'", Phone.class); - - List resultList = query.getResultList(); - - assertThat(resultList).hasSize(1); - } - - @Test - public void whenMultipleEntitiesAreListedWithJoin_ThenCreatesMultipleJoins() { - TypedQuery query = entityManager.createQuery("SELECT ph FROM Employee e JOIN e.department d JOIN e.phones ph WHERE d.name IS NOT NULL", Phone.class); - - List resultList = query.getResultList(); - - assertThat(resultList).hasSize(3); - assertThat(resultList).extracting("number") - .containsOnly("111", "222", "333"); - } - - @Test - public void whenLeftKeywordIsSpecified_thenCreatesOuterJoinAndIncludesNonMatched() { - TypedQuery query = entityManager.createQuery("SELECT DISTINCT d FROM Department d LEFT JOIN d.employees e", Department.class); - - List resultList = query.getResultList(); - - assertThat(resultList).hasSize(3); - assertThat(resultList).extracting("name") - .containsOnly("Infra", "Accounting", "Management"); - } - - @Test - public void whenFetchKeywordIsSpecified_ThenCreatesFetchJoin() { - TypedQuery query = entityManager.createQuery("SELECT d FROM Department d JOIN FETCH d.employees", Department.class); - - List resultList = query.getResultList(); - - assertThat(resultList).hasSize(3); - assertThat(resultList).extracting("name") - .containsOnly("Infra", "Accounting", "Accounting"); - } - - @Test - public void whenLeftAndFetchKeywordsAreSpecified_ThenCreatesOuterFetchJoin() { - TypedQuery query = entityManager.createQuery("SELECT d FROM Department d LEFT JOIN FETCH d.employees", Department.class); - - List resultList = query.getResultList(); - - assertThat(resultList).hasSize(4); - assertThat(resultList).extracting("name") - .containsOnly("Infra", "Accounting", "Accounting", "Management"); - } - - @Test - public void whenCollectionValuedAssociationIsSpecifiedInSelect_ThenReturnsCollections() { - TypedQuery query = entityManager.createQuery("SELECT e.phones FROM Employee e", Collection.class); - - List resultList = query.getResultList(); - - assertThat(resultList).extracting("number").containsOnly("111", "222", "333"); - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/projection/JpaProjectionIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/projection/JpaProjectionIntegrationTest.java deleted file mode 100644 index 96eaf4ed07..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/projection/JpaProjectionIntegrationTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.baeldung.projection; - -import com.baeldung.projection.model.Person; -import com.baeldung.projection.repository.AddressRepository; -import com.baeldung.projection.repository.PersonRepository; -import com.baeldung.projection.view.AddressView; -import com.baeldung.projection.view.PersonDto; -import com.baeldung.projection.view.PersonView; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.jdbc.Sql; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; - -@DataJpaTest -@RunWith(SpringRunner.class) -@Sql(scripts = "/projection-insert-data.sql") -@Sql(scripts = "/projection-clean-up-data.sql", executionPhase = AFTER_TEST_METHOD) -public class JpaProjectionIntegrationTest { - @Autowired - private AddressRepository addressRepository; - - @Autowired - private PersonRepository personRepository; - - @Test - public void whenUsingClosedProjections_thenViewWithRequiredPropertiesIsReturned() { - AddressView addressView = addressRepository.getAddressByState("CA").get(0); - assertThat(addressView.getZipCode()).isEqualTo("90001"); - - PersonView personView = addressView.getPerson(); - assertThat(personView.getFirstName()).isEqualTo("John"); - assertThat(personView.getLastName()).isEqualTo("Doe"); - } - - @Test - public void whenUsingOpenProjections_thenViewWithRequiredPropertiesIsReturned() { - PersonView personView = personRepository.findByLastName("Doe"); - assertThat(personView.getFullName()).isEqualTo("John Doe"); - } - - @Test - public void whenUsingClassBasedProjections_thenDtoWithRequiredPropertiesIsReturned() { - PersonDto personDto = personRepository.findByFirstName("John"); - assertThat(personDto.getFirstName()).isEqualTo("John"); - assertThat(personDto.getLastName()).isEqualTo("Doe"); - } - - @Test - public void whenUsingDynamicProjections_thenObjectWithRequiredPropertiesIsReturned() { - Person person = personRepository.findByLastName("Doe", Person.class); - PersonView personView = personRepository.findByLastName("Doe", PersonView.class); - PersonDto personDto = personRepository.findByLastName("Doe", PersonDto.class); - - assertThat(person.getFirstName()).isEqualTo("John"); - assertThat(personView.getFirstName()).isEqualTo("John"); - assertThat(personDto.getFirstName()).isEqualTo("John"); - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/CustomerRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/CustomerRepositoryIntegrationTest.java deleted file mode 100644 index 5d6457ce30..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/CustomerRepositoryIntegrationTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.baeldung.repository; - -import com.baeldung.entity.Customer; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.junit4.SpringRunner; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -@DataJpaTest -@RunWith(SpringRunner.class) -public class CustomerRepositoryIntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private CustomerRepository repository; - - @Before - public void before() { - entityManager.persist(new Customer("A", "A@example.com")); - entityManager.persist(new Customer("D", null)); - entityManager.persist(new Customer("D", "D@example.com")); - } - - @Test - public void givenQueryMethod_whenEmailIsNull_thenFoundByNullEmail() { - List customers = repository.findByNameAndEmail("D", null); - - assertEquals(1, customers.size()); - Customer actual = customers.get(0); - - assertEquals(null, actual.getEmail()); - assertEquals("D", actual.getName()); - } - - @Test - public void givenQueryMethod_whenEmailIsAbsent_thenIgnoreEmail() { - List customers = repository.findByName("D"); - - assertEquals(2, customers.size()); - } - - @Test - public void givenQueryAnnotation_whenEmailIsNull_thenIgnoreEmail() { - List customers = repository.findCustomerByNameAndEmail("D", null); - - assertEquals(2, customers.size()); - } - - @After - public void cleanUp() { - repository.deleteAll(); - } -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitPopulatorIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitPopulatorIntegrationTest.java deleted file mode 100644 index 4d3661e717..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitPopulatorIntegrationTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.repository; - -import static org.junit.Assert.assertEquals; - -import java.util.List; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.entity.Fruit; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class FruitPopulatorIntegrationTest { - - @Autowired - private FruitRepository fruitRepository; - - @Test - public void givenFruitJsonPopulatorThenShouldInsertRecordOnStart() { - - List fruits = fruitRepository.findAll(); - assertEquals("record count is not matching", 2, fruits.size()); - - fruits.forEach(fruit -> { - if (1 == fruit.getId()) { - assertEquals("apple", fruit.getName()); - assertEquals("red", fruit.getColor()); - } else if (2 == fruit.getId()) { - assertEquals("guava", fruit.getName()); - assertEquals("green", fruit.getColor()); - } - }); - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java deleted file mode 100644 index cf771dc833..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.repository; - -import static org.junit.Assert.assertEquals; - -import java.util.List; - -import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.jdbc.Sql; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.entity.Fruit; - -@RunWith(SpringRunner.class) -@SpringBootTest -class FruitRepositoryIntegrationTest { - - @Autowired - private FruitRepository fruitRepository; - - @Transactional - @Test - @Sql(scripts = { "/test-fruit-data.sql" }) - public void givenFruits_WhenDeletedByColor_ThenDeletedFruitsShouldReturn() { - - List fruits = fruitRepository.deleteByColor("green"); - - assertEquals("number of fruits are not matching", 2, fruits.size()); - fruits.forEach(fruit -> assertEquals("Its not a green fruit", "green", fruit.getColor())); - } - - @Transactional - @Test - @Sql(scripts = { "/test-fruit-data.sql" }) - public void givenFruits_WhenDeletedByName_ThenDeletedFruitCountShouldReturn() { - - Long deletedFruitCount = fruitRepository.deleteByName("apple"); - - assertEquals("deleted fruit count is not matching", 1, deletedFruitCount.intValue()); - } - - @Transactional - @Test - @Sql(scripts = { "/test-fruit-data.sql" }) - public void givenFruits_WhenRemovedByColor_ThenDeletedFruitsShouldReturn() { - - List fruits = fruitRepository.removeByColor("green"); - - assertEquals("number of fruits are not matching", 2, fruits.size()); - fruits.forEach(fruit -> assertEquals("Its not a green fruit", "green", fruit.getColor())); - } - - @Transactional - @Test - @Sql(scripts = { "/test-fruit-data.sql" }) - public void givenFruits_WhenRemovedByName_ThenDeletedFruitCountShouldReturn() { - - Long deletedFruitCount = fruitRepository.removeByName("apple"); - - assertEquals("deleted fruit count is not matching", 1, deletedFruitCount.intValue()); - } - - @Transactional - @Test - @Sql(scripts = { "/test-fruit-data.sql" }) - public void givenFruits_WhenDeletedByColorOrName_ThenDeletedFruitsShouldReturn() { - - int deletedCount = fruitRepository.deleteFruits("apple", "green"); - - assertEquals("number of fruits are not matching", 3, deletedCount); - } -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/PassengerRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/PassengerRepositoryIntegrationTest.java deleted file mode 100644 index f96f0249d7..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/PassengerRepositoryIntegrationTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.repository; - -import com.baeldung.entity.Passenger; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.junit4.SpringRunner; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import java.util.List; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.core.IsNot.not; - -@DataJpaTest -@RunWith(SpringRunner.class) -public class PassengerRepositoryIntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - @Autowired - private PassengerRepository repository; - - @Before - public void before() { - entityManager.persist(Passenger.from("Jill", "Smith")); - entityManager.persist(Passenger.from("Eve", "Jackson")); - entityManager.persist(Passenger.from("Fred", "Bloggs")); - entityManager.persist(Passenger.from("Ricki", "Bobbie")); - entityManager.persist(Passenger.from("Siya", "Kolisi")); - } - - @Test - public void givenPassengers_whenMatchingIgnoreCase_thenExpectedReturned() { - Passenger jill = Passenger.from("Jill", "Smith"); - Passenger eve = Passenger.from("Eve", "Jackson"); - Passenger fred = Passenger.from("Fred", "Bloggs"); - Passenger siya = Passenger.from("Siya", "Kolisi"); - Passenger ricki = Passenger.from("Ricki", "Bobbie"); - - List passengers = repository.findByFirstNameIgnoreCase("FRED"); - - assertThat(passengers, contains(fred)); - assertThat(passengers, not(contains(eve))); - assertThat(passengers, not(contains(siya))); - assertThat(passengers, not(contains(jill))); - assertThat(passengers, not(contains(ricki))); - - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/SongRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/SongRepositoryIntegrationTest.java deleted file mode 100644 index 14912a4ecb..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/SongRepositoryIntegrationTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.repository; - -import static org.junit.Assert.assertEquals; - -import java.util.List; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.jdbc.Sql; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.entity.Song; - -@RunWith(SpringRunner.class) -@SpringBootTest -@Sql(scripts = { "/test-song-data.sql" }) -public class SongRepositoryIntegrationTest { - - @Autowired private SongRepository songRepository; - - @Transactional - @Test - public void givenSong_WhenFindLikeByName_ThenShouldReturnOne() { - List songs = songRepository.findByNameLike("Despacito"); - assertEquals(1, songs.size()); - } - - @Transactional - @Test - public void givenSong_WhenFindByNameNotLike_thenShouldReturn3Songs() { - List songs = songRepository.findByNameNotLike("Despacito"); - assertEquals(5, songs.size()); - } - - @Transactional - @Test - public void givenSong_WhenFindByNameStartingWith_thenShouldReturn2Songs() { - List songs = songRepository.findByNameStartingWith("Co"); - assertEquals(2, songs.size()); - } - - @Transactional - @Test - public void givenSong_WhenFindByNameEndingWith_thenShouldReturn2Songs() { - List songs = songRepository.findByNameEndingWith("Life"); - assertEquals(2, songs.size()); - } - - @Transactional - @Test - public void givenSong_WhenFindBySingerContaining_thenShouldReturn2Songs() { - List songs = songRepository.findBySingerContaining("Luis"); - assertEquals(2, songs.size()); - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/test/resources/entitygraph-data.sql b/persistence-modules/spring-data-jpa-2/src/test/resources/entitygraph-data.sql deleted file mode 100644 index 685ec2c605..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/resources/entitygraph-data.sql +++ /dev/null @@ -1,7 +0,0 @@ -INSERT INTO Item(id,name) VALUES (1,'Table'); -INSERT INTO Item(id,name) VALUES (2,'Bottle'); - -INSERT INTO Characteristic(id,item_id, type) VALUES (1,1,'Rigid'); -INSERT INTO Characteristic(id,item_id,type) VALUES (2,1,'Big'); -INSERT INTO Characteristic(id,item_id,type) VALUES (3,2,'Fragile'); -INSERT INTO Characteristic(id,item_id,type) VALUES (4,2,'Small'); \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/resources/projection-clean-up-data.sql b/persistence-modules/spring-data-jpa-2/src/test/resources/projection-clean-up-data.sql deleted file mode 100644 index d34f6f0636..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/resources/projection-clean-up-data.sql +++ /dev/null @@ -1,2 +0,0 @@ -DELETE FROM address; -DELETE FROM person; \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/resources/projection-insert-data.sql b/persistence-modules/spring-data-jpa-2/src/test/resources/projection-insert-data.sql deleted file mode 100644 index 544dcc4b88..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/resources/projection-insert-data.sql +++ /dev/null @@ -1,2 +0,0 @@ -INSERT INTO person(id,first_name,last_name) VALUES (1,'John','Doe'); -INSERT INTO address(id,person_id,state,city,street,zip_code) VALUES (1,1,'CA', 'Los Angeles', 'Standford Ave', '90001'); \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/resources/test-aggregation-data.sql b/persistence-modules/spring-data-jpa-2/src/test/resources/test-aggregation-data.sql deleted file mode 100644 index 12409a124e..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/resources/test-aggregation-data.sql +++ /dev/null @@ -1,7 +0,0 @@ -INSERT INTO post (id, title, content) VALUES (1, 'Comment 1', 'Content 1'); -INSERT INTO post (id, title, content) VALUES (2, 'Comment 2', 'Content 2'); -INSERT INTO post (id, title, content) VALUES (3, 'Comment 3', 'Content 3'); -INSERT INTO comment (id, year, approved, content, post_id) VALUES (1, 2019, false, 'Comment 1', 1); -INSERT INTO comment (id, year, approved, content, post_id) VALUES (2, 2018, true, 'Comment 2', 1); -INSERT INTO comment (id, year, approved, content, post_id) VALUES (3, 2018, true, 'Comment 3', 2); -INSERT INTO comment (id, year, approved, content, post_id) VALUES (4, 2017, false, 'Comment 4', 3); \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/resources/test-fruit-data.sql b/persistence-modules/spring-data-jpa-2/src/test/resources/test-fruit-data.sql deleted file mode 100644 index d99f42e5a7..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/resources/test-fruit-data.sql +++ /dev/null @@ -1,6 +0,0 @@ -truncate table fruit; - -insert into fruit(id,name,color) values (1,'apple','red'); -insert into fruit(id,name,color) values (2,'custard apple','green'); -insert into fruit(id,name,color) values (3,'mango','yellow'); -insert into fruit(id,name,color) values (4,'guava','green'); \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/resources/test-song-data.sql b/persistence-modules/spring-data-jpa-2/src/test/resources/test-song-data.sql deleted file mode 100644 index 5a2b1a5555..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/resources/test-song-data.sql +++ /dev/null @@ -1,8 +0,0 @@ -INSERT INTO song(id,name,length_in_seconds,compositor,singer,released,genre) -VALUES -(1,'Despacito',209,'Luis Fonsi','Luis Fonsi, Daddy Yankee','2017-01-12','Reggaeton'), -(2,'Con calma',188,'Daddy Yankee','Daddy Yankee','2019-01-24','Reggaeton'), -(3,'It''s My Life',205,'Bon Jovi','Jon Bon Jovi','2000-05-23','Pop'), -(4,'Live is Life',242,'Opus','Opus','1985-01-01','Reggae'), -(5,'Countdown to Extinction',249,'Megadeth','Megadeth','1992-07-14','Heavy Metal'), -(6, 'Si nos dejan',139,'Luis Miguel','Luis Miguel','1995-10-17','Bolero'); \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-3/README.md b/persistence-modules/spring-data-jpa-3/README.md deleted file mode 100644 index bac52bf114..0000000000 --- a/persistence-modules/spring-data-jpa-3/README.md +++ /dev/null @@ -1,20 +0,0 @@ -### Relevant Articles: -- [Limiting Query Results with JPA and Spring Data JPA](https://www.baeldung.com/jpa-limit-query-results) -- [Sorting Query Results with Spring Data](https://www.baeldung.com/spring-data-sorting) -- [INSERT Statement in JPA](https://www.baeldung.com/jpa-insert) -- [Pagination and Sorting using Spring Data JPA](https://www.baeldung.com/spring-data-jpa-pagination-sorting) -- [Spring Data JPA Query by Example](https://www.baeldung.com/spring-data-query-by-example) -- [DB Integration Tests with Spring Boot and Testcontainers](https://www.baeldung.com/spring-boot-testcontainers-integration-test) -- [Spring Data JPA @Modifying Annotation](https://www.baeldung.com/spring-data-jpa-modifying-annotation) -- [Spring Data JPA Batch Inserts](https://www.baeldung.com/spring-data-jpa-batch-inserts) -- [Batch Insert/Update with Hibernate/JPA](https://www.baeldung.com/jpa-hibernate-batch-insert-update) -- [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush) - -### Eclipse Config -After importing the project into Eclipse, you may see the following error: -"No persistence xml file found in project" - -This can be ignored: -- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" -Or: -- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator diff --git a/persistence-modules/spring-data-jpa-3/pom.xml b/persistence-modules/spring-data-jpa-3/pom.xml deleted file mode 100644 index d02d089ba3..0000000000 --- a/persistence-modules/spring-data-jpa-3/pom.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - 4.0.0 - spring-data-jpa-3 - spring-data-jpa-3 - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.boot - spring-boot-starter-web - - - com.google.guava - guava - ${guava.version} - - - com.h2database - h2 - - - net.ttddyy - datasource-proxy - ${datasource-proxy.version} - - - org.postgresql - postgresql - - - com.h2database - h2 - runtime - - - - - org.testcontainers - postgresql - ${testcontainers.version} - test - - - - - - 1.4.1 - 21.0 - 1.12.2 - - - diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/Application.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/Application.java deleted file mode 100644 index ce10072031..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/Application.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; - -@SpringBootApplication -@EnableJpaRepositories -public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/DatasourceProxyBeanPostProcessor.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/DatasourceProxyBeanPostProcessor.java deleted file mode 100644 index 504357db44..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/DatasourceProxyBeanPostProcessor.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.baeldung.batchinserts; - -import java.lang.reflect.Method; -import javax.sql.DataSource; -import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder; -import org.aopalliance.intercept.MethodInterceptor; -import org.aopalliance.intercept.MethodInvocation; -import org.springframework.aop.framework.ProxyFactory; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.config.BeanPostProcessor; -import org.springframework.context.annotation.Profile; -import org.springframework.stereotype.Component; -import org.springframework.util.ReflectionUtils; - -@Component -@Profile("batchinserts") -public class DatasourceProxyBeanPostProcessor implements BeanPostProcessor { - - @Override - public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException { - return bean; - } - - @Override - public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException { - if (bean instanceof DataSource) { - ProxyFactory factory = new ProxyFactory(bean); - factory.setProxyTargetClass(true); - factory.addAdvice(new ProxyDataSourceInterceptor((DataSource) bean)); - return factory.getProxy(); - } - - return bean; - } - - private static class ProxyDataSourceInterceptor implements MethodInterceptor { - - private final DataSource dataSource; - - public ProxyDataSourceInterceptor(final DataSource dataSource) { - this.dataSource = ProxyDataSourceBuilder.create(dataSource).name("Batch-Insert-Logger").asJson().countQuery().logQueryToSysOut().build(); - } - - @Override - public Object invoke(final MethodInvocation invocation) throws Throwable { - Method proxyMethod = ReflectionUtils.findMethod(dataSource.getClass(), invocation.getMethod().getName()); - if (proxyMethod != null) { - return proxyMethod.invoke(dataSource, invocation.getArguments()); - } - return invocation.proceed(); - } - } -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/model/School.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/model/School.java deleted file mode 100644 index 6d2f333ac7..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/model/School.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.baeldung.batchinserts.model; - -import java.util.List; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; - -@Entity -public class School { - - @Id - @GeneratedValue(strategy = GenerationType.SEQUENCE) - private long id; - - private String name; - - @OneToMany(mappedBy = "school") - private List students; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getStudents() { - return students; - } - - public void setStudents(List students) { - this.students = students; - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/model/Student.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/model/Student.java deleted file mode 100644 index d38214f122..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/model/Student.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.batchinserts.model; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; - -@Entity -public class Student { - - @Id - @GeneratedValue(strategy = GenerationType.SEQUENCE) - private long id; - - private String name; - - @ManyToOne - private School school; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public School getSchool() { - return school; - } - - public void setSchool(School school) { - this.school = school; - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/Application.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/Application.java deleted file mode 100644 index aaca760499..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/Application.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.boot; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.domain.EntityScan; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; - -@SpringBootApplication -@EnableJpaRepositories("com.baeldung") -@EntityScan("com.baeldung") -public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/CustomerRepository.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/CustomerRepository.java deleted file mode 100644 index 7cb7e45b27..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/CustomerRepository.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.boot.daos; - -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.boot.domain.Customer; - -/** - * JPA CrudRepository interface - * - * @author ysharma2512 - * - */ -@Repository -@Transactional -public interface CustomerRepository extends CrudRepository{ - -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/impl/PersonInsertRepository.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/impl/PersonInsertRepository.java deleted file mode 100644 index 373532e1c3..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/impl/PersonInsertRepository.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.boot.daos.impl; - -import org.springframework.stereotype.Repository; - -import com.baeldung.boot.domain.Person; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.transaction.Transactional; - -@Repository -public class PersonInsertRepository { - - @PersistenceContext - private EntityManager entityManager; - - @Transactional - public void insertWithQuery(Person person) { - entityManager.createNativeQuery("INSERT INTO person (id, first_name, last_name) VALUES (?,?,?)") - .setParameter(1, person.getId()) - .setParameter(2, person.getFirstName()) - .setParameter(3, person.getLastName()) - .executeUpdate(); - } - - @Transactional - public void insertWithEntityManager(Person person) { - this.entityManager.persist(person); - } - -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepository.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepository.java deleted file mode 100644 index 53f692ff28..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepository.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.baeldung.boot.daos.user; - -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; - -import com.baeldung.boot.domain.User; - -import java.time.LocalDate; -import java.util.Collection; -import java.util.List; -import java.util.stream.Stream; - -public interface UserRepository extends JpaRepository , UserRepositoryCustom{ - - Stream findAllByName(String name); - - @Query("SELECT u FROM User u WHERE u.status = 1") - Collection findAllActiveUsers(); - - @Query("select u from User u where u.email like '%@gmail.com'") - List findUsersWithGmailAddress(); - - @Query(value = "SELECT * FROM Users u WHERE u.status = 1", nativeQuery = true) - Collection findAllActiveUsersNative(); - - @Query("SELECT u FROM User u WHERE u.status = ?1") - User findUserByStatus(Integer status); - - @Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true) - User findUserByStatusNative(Integer status); - - @Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2") - User findUserByStatusAndName(Integer status, String name); - - @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") - User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name); - - @Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true) - User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name); - - @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") - User findUserByUserStatusAndUserName(@Param("status") Integer userStatus, @Param("name") String userName); - - @Query("SELECT u FROM User u WHERE u.name like ?1%") - User findUserByNameLike(String name); - - @Query("SELECT u FROM User u WHERE u.name like :name%") - User findUserByNameLikeNamedParam(@Param("name") String name); - - @Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true) - User findUserByNameLikeNative(String name); - - @Query(value = "SELECT u FROM User u") - List findAllUsers(Sort sort); - - @Query(value = "SELECT u FROM User u ORDER BY id") - Page findAllUsersWithPagination(Pageable pageable); - - @Query(value = "SELECT * FROM Users ORDER BY id", countQuery = "SELECT count(*) FROM Users", nativeQuery = true) - Page findAllUsersWithPaginationNative(Pageable pageable); - - @Modifying - @Query("update User u set u.status = :status where u.name = :name") - int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name); - - @Modifying - @Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true) - int updateUserSetStatusForNameNative(Integer status, String name); - - @Query(value = "INSERT INTO Users (name, age, email, status, active) VALUES (:name, :age, :email, :status, :active)", nativeQuery = true) - @Modifying - void insertUser(@Param("name") String name, @Param("age") Integer age, @Param("email") String email, @Param("status") Integer status, @Param("active") boolean active); - - @Modifying - @Query(value = "UPDATE Users u SET status = ? WHERE u.name = ?", nativeQuery = true) - int updateUserSetStatusForNameNativePostgres(Integer status, String name); - - @Query(value = "SELECT u FROM User u WHERE u.name IN :names") - List findUserByNameList(@Param("names") Collection names); - - void deleteAllByCreationDateAfter(LocalDate date); - - @Modifying(clearAutomatically = true, flushAutomatically = true) - @Query("update User u set u.active = false where u.lastLoginDate < :date") - void deactivateUsersNotLoggedInSince(@Param("date") LocalDate date); - - @Modifying(clearAutomatically = true, flushAutomatically = true) - @Query("delete User u where u.active = false") - int deleteDeactivatedUsers(); - - @Modifying(clearAutomatically = true, flushAutomatically = true) - @Query(value = "alter table USERS add column deleted int(1) not null default 0", nativeQuery = true) - void addDeletedColumn(); -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustom.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustom.java deleted file mode 100644 index c586b54027..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustom.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.boot.daos.user; - -import java.util.Collection; -import java.util.List; -import java.util.Set; -import java.util.function.Predicate; - -import com.baeldung.boot.domain.User; - -public interface UserRepositoryCustom { - List findUserByEmails(Set emails); - - List findAllUsersByPredicates(Collection> predicates); -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustomImpl.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustomImpl.java deleted file mode 100644 index 63a743b6b5..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustomImpl.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.boot.daos.user; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Path; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; - -import com.baeldung.boot.domain.User; - -public class UserRepositoryCustomImpl implements UserRepositoryCustom { - - @PersistenceContext - private EntityManager entityManager; - - @Override - public List findUserByEmails(Set emails) { - CriteriaBuilder cb = entityManager.getCriteriaBuilder(); - CriteriaQuery query = cb.createQuery(User.class); - Root user = query.from(User.class); - - Path emailPath = user.get("email"); - - List predicates = new ArrayList<>(); - for (String email : emails) { - - predicates.add(cb.like(emailPath, email)); - - } - query.select(user) - .where(cb.or(predicates.toArray(new Predicate[predicates.size()]))); - - return entityManager.createQuery(query) - .getResultList(); - } - - @Override - public List findAllUsersByPredicates(Collection> predicates) { - List allUsers = entityManager.createQuery("select u from User u", User.class).getResultList(); - Stream allUsersStream = allUsers.stream(); - for (java.util.function.Predicate predicate : predicates) { - allUsersStream = allUsersStream.filter(predicate); - } - - return allUsersStream.collect(Collectors.toList()); - } - -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Customer.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Customer.java deleted file mode 100644 index af88be0be6..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Customer.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.baeldung.boot.domain; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -/** - * Customer Entity class - * @author ysharma2512 - * - */ -@Entity -public class Customer { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - private String firstName; - private String lastName; - - public Customer(String firstName, String lastName) { - this.firstName = firstName; - this.lastName = lastName; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - 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; - } - - @Override - public String toString() { - return String.format("Customer[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); - } - -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Person.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Person.java deleted file mode 100644 index 88894ccc72..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Person.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.boot.domain; - -import javax.persistence.Entity; -import javax.persistence.Id; - -@Entity -public class Person { - - @Id - private Long id; - private String firstName; - private String lastName; - - public Person() { - } - - public Person(Long id, String firstName, String lastName) { - this.id = id; - this.firstName = firstName; - this.lastName = lastName; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - 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; - } - -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Possession.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Possession.java deleted file mode 100644 index f13491ad82..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Possession.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.baeldung.boot.domain; - -import javax.persistence.*; -import com.baeldung.boot.domain.Possession; - -@Entity -@Table -public class Possession { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private long id; - - private String name; - - public Possession() { - super(); - } - - public Possession(final String name) { - super(); - - this.name = name; - } - - public long getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) + (int) (id ^ (id >>> 32)); - result = (prime * result) + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final Possession other = (Possession) obj; - if (id != other.id) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - return true; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]"); - return builder.toString(); - } - -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/User.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/User.java deleted file mode 100644 index cca00e52a2..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/User.java +++ /dev/null @@ -1,132 +0,0 @@ -package com.baeldung.boot.domain; - -import javax.persistence.*; - -import java.time.LocalDate; -import java.util.List; -import java.util.Objects; - -@Entity -@Table(name = "users") -public class User { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private int id; - private String name; - private LocalDate creationDate; - private LocalDate lastLoginDate; - private boolean active; - private int age; - @Column(unique = true, nullable = false) - private String email; - private Integer status; - @OneToMany - List possessionList; - - public User() { - super(); - } - - public User(String name, LocalDate creationDate,String email, Integer status) { - this.name = name; - this.creationDate = creationDate; - this.email = email; - this.status = status; - this.active = true; - } - - public int getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public String getEmail() { - return email; - } - - public void setEmail(final String email) { - this.email = email; - } - - public Integer getStatus() { - return status; - } - - public void setStatus(Integer status) { - this.status = status; - } - - public int getAge() { - return age; - } - - public void setAge(final int age) { - this.age = age; - } - - public LocalDate getCreationDate() { - return creationDate; - } - - public List getPossessionList() { - return possessionList; - } - - public void setPossessionList(List possessionList) { - this.possessionList = possessionList; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("User [name=").append(name).append(", id=").append(id).append("]"); - return builder.toString(); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - User user = (User) o; - return id == user.id && - age == user.age && - Objects.equals(name, user.name) && - Objects.equals(creationDate, user.creationDate) && - Objects.equals(email, user.email) && - Objects.equals(status, user.status); - } - - @Override - public int hashCode() { - return Objects.hash(id, name, creationDate, age, email, status); - } - - public LocalDate getLastLoginDate() { - return lastLoginDate; - } - - public void setLastLoginDate(LocalDate lastLoginDate) { - this.lastLoginDate = lastLoginDate; - } - - public boolean isActive() { - return active; - } - - public void setActive(boolean active) { - this.active = active; - } - -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/CustomPassengerRepository.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/CustomPassengerRepository.java deleted file mode 100644 index 7152286c83..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/CustomPassengerRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.boot.passenger; - -import java.util.List; - -interface CustomPassengerRepository { - - List findOrderedBySeatNumberLimitedTo(int limit); -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/Passenger.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/Passenger.java deleted file mode 100644 index c75107a783..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/Passenger.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.baeldung.boot.passenger; - -import javax.persistence.Basic; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import java.util.Objects; - -@Entity -class Passenger { - - @Id - @GeneratedValue - @Column(nullable = false) - private Long id; - - @Basic(optional = false) - @Column(nullable = false) - private String firstName; - - @Basic(optional = false) - @Column(nullable = false) - private String lastName; - - @Basic(optional = false) - @Column(nullable = false) - private Integer seatNumber; - - private Passenger(String firstName, String lastName, Integer seatNumber) { - this.firstName = firstName; - this.lastName = lastName; - this.seatNumber = seatNumber; - } - - static Passenger from(String firstName, String lastName, Integer seatNumber) { - return new Passenger(firstName, lastName, seatNumber); - } - - @Override - public boolean equals(Object object) { - if (this == object) - return true; - if (object == null || getClass() != object.getClass()) - return false; - Passenger passenger = (Passenger) object; - return getSeatNumber() == passenger.getSeatNumber() && Objects.equals(getFirstName(), passenger.getFirstName()) - && Objects.equals(getLastName(), passenger.getLastName()); - } - - @Override - public int hashCode() { - return Objects.hash(getFirstName(), getLastName(), getSeatNumber()); - } - - @Override - public String toString() { - final StringBuilder toStringBuilder = new StringBuilder(getClass().getSimpleName()); - toStringBuilder.append("{ id=").append(id); - toStringBuilder.append(", firstName='").append(firstName).append('\''); - toStringBuilder.append(", lastName='").append(lastName).append('\''); - toStringBuilder.append(", seatNumber=").append(seatNumber); - toStringBuilder.append('}'); - return toStringBuilder.toString(); - } - - Long getId() { - return id; - } - - String getFirstName() { - return firstName; - } - - String getLastName() { - return lastName; - } - - Integer getSeatNumber() { - return seatNumber; - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/PassengerRepository.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/PassengerRepository.java deleted file mode 100644 index 14d5403cb5..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/PassengerRepository.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.boot.passenger; - -import java.util.List; - -import org.springframework.data.domain.Sort; -import org.springframework.data.jpa.repository.JpaRepository; - -interface PassengerRepository extends JpaRepository, CustomPassengerRepository { - - Passenger findFirstByOrderBySeatNumberAsc(); - - Passenger findTopByOrderBySeatNumberAsc(); - - List findByOrderBySeatNumberAsc(); - - List findByFirstNameIgnoreCase(String firstName); - - List findByLastNameOrderBySeatNumberAsc(String lastName); - - List findByLastName(String lastName, Sort sort); - -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/PassengerRepositoryImpl.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/PassengerRepositoryImpl.java deleted file mode 100644 index 508c669066..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/PassengerRepositoryImpl.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.boot.passenger; - -import org.springframework.stereotype.Repository; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import java.util.List; - -@Repository -class PassengerRepositoryImpl implements CustomPassengerRepository { - - @PersistenceContext - private EntityManager entityManager; - - @Override - public List findOrderedBySeatNumberLimitedTo(int limit) { - return entityManager.createQuery("SELECT p FROM Passenger p ORDER BY p.seatNumber", - Passenger.class).setMaxResults(limit).getResultList(); - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/web/controllers/CustomerController.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/web/controllers/CustomerController.java deleted file mode 100644 index e13afd9b45..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/web/controllers/CustomerController.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.boot.web.controllers; - -import java.net.URISyntaxException; -import java.util.Arrays; -import java.util.List; - -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RestController; - -import com.baeldung.boot.daos.CustomerRepository; -import com.baeldung.boot.domain.Customer; - -/** - * A simple controller to test the JPA CrudRepository operations - * controllers - * - * @author ysharma2512 - * - */ -@RestController -public class CustomerController { - - CustomerRepository customerRepository; - - public CustomerController(CustomerRepository customerRepository2) { - this.customerRepository = customerRepository2; - } - - @PostMapping("/customers") - public ResponseEntity> insertCustomers() throws URISyntaxException { - Customer c1 = new Customer("James", "Gosling"); - Customer c2 = new Customer("Doug", "Lea"); - Customer c3 = new Customer("Martin", "Fowler"); - Customer c4 = new Customer("Brian", "Goetz"); - List customers = Arrays.asList(c1, c2, c3, c4); - customerRepository.saveAll(customers); - return ResponseEntity.ok(customers); - } - -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/entity/Employee.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/entity/Employee.java deleted file mode 100644 index 4c3dbd25b7..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/entity/Employee.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.entity; - -import javax.persistence.Entity; -import javax.persistence.Id; - -@Entity -public class Employee { - - @Id - private Long id; - private String name; - - public Employee() { - } - - public Employee(Long id, String name) { - this.id = id; - this.name = name; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/model/BasicUser.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/model/BasicUser.java deleted file mode 100644 index 2dc9c18cf6..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/model/BasicUser.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.model; - -import javax.persistence.*; -import java.util.Set; - -@Entity -@Table(name = "users") -public class BasicUser { - - @Id - @GeneratedValue - private Long id; - - private String username; - - @ElementCollection - private Set permissions; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public Set getPermissions() { - return permissions; - } - - public void setPermissions(Set permissions) { - this.permissions = permissions; - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java deleted file mode 100644 index 3b9aa2cc18..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.multipledb; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class MultipleDbApplication { - - public static void main(String[] args) { - SpringApplication.run(MultipleDbApplication.class, args); - } - -} - diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java deleted file mode 100644 index bcf2cd84eb..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.baeldung.multipledb; - -import com.google.common.base.Preconditions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.PlatformTransactionManager; - -import javax.sql.DataSource; -import java.util.HashMap; - -@Configuration -@PropertySource({"classpath:persistence-multiple-db.properties"}) -@EnableJpaRepositories(basePackages = "com.baeldung.multipledb.dao.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager") -@Profile("!tc") -public class PersistenceProductConfiguration { - @Autowired - private Environment env; - - public PersistenceProductConfiguration() { - super(); - } - - // - - @Bean - public LocalContainerEntityManagerFactoryBean productEntityManager() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(productDataSource()); - em.setPackagesToScan("com.baeldung.multipledb.model.product"); - - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - em.setJpaVendorAdapter(vendorAdapter); - final HashMap properties = new HashMap(); - properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); - em.setJpaPropertyMap(properties); - - return em; - } - - @Bean - public DataSource productDataSource() { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); - dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("product.jdbc.url"))); - dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); - dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); - - return dataSource; - } - - @Bean - public PlatformTransactionManager productTransactionManager() { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(productEntityManager().getObject()); - return transactionManager; - } - -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java deleted file mode 100644 index 6ce9bcad45..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.multipledb.dao.product; - -import java.util.List; - -import org.springframework.data.domain.Pageable; -import org.springframework.data.repository.PagingAndSortingRepository; - -import com.baeldung.multipledb.model.product.Product; - -public interface ProductRepository extends PagingAndSortingRepository { - - List findAllByPrice(double price, Pageable pageable); -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/Product.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/Product.java deleted file mode 100644 index eaf471043c..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/Product.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.baeldung.multipledb.model.product; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(schema = "products") -public class Product { - - @Id - private int id; - - private String name; - - private double price; - - public Product() { - super(); - } - - private Product(int id, String name, double price) { - super(); - this.id = id; - this.name = name; - this.price = price; - } - - public static Product from(int id, String name, double price) { - return new Product(id, name, price); - } - - public int getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public double getPrice() { - return price; - } - - public void setPrice(final double price) { - this.price = price; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Product [name=") - .append(name) - .append(", id=") - .append(id) - .append("]"); - return builder.toString(); - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/repository/EmployeeRepository.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/repository/EmployeeRepository.java deleted file mode 100644 index 8f0a80814b..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/repository/EmployeeRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.repository; - -import org.springframework.data.jpa.repository.JpaRepository; - -import com.baeldung.entity.Employee; - -public interface EmployeeRepository extends JpaRepository { - -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/repository/UserRepository.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/repository/UserRepository.java deleted file mode 100644 index f683be402f..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/repository/UserRepository.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.repository; - -import java.util.Optional; - -import org.springframework.data.jpa.repository.JpaRepository; - -import com.baeldung.model.BasicUser; - -public interface UserRepository extends JpaRepository { - - Optional findSummaryByUsername(String username); - - Optional findByUsername(String username); -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-3/src/main/resources/application.properties deleted file mode 100644 index f127dd5e50..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/resources/application.properties +++ /dev/null @@ -1,6 +0,0 @@ -spring.main.allow-bean-definition-overriding=true - -spring.jpa.properties.hibernate.jdbc.batch_size=4 -spring.jpa.properties.hibernate.order_inserts=true -spring.jpa.properties.hibernate.order_updates=true -spring.jpa.properties.hibernate.generate_statistics=true diff --git a/persistence-modules/spring-data-jpa-3/src/main/resources/logback.xml b/persistence-modules/spring-data-jpa-3/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-3/src/main/resources/persistence-multiple-db.properties b/persistence-modules/spring-data-jpa-3/src/main/resources/persistence-multiple-db.properties deleted file mode 100644 index 75534e8a54..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/resources/persistence-multiple-db.properties +++ /dev/null @@ -1,13 +0,0 @@ -# jdbc.X -jdbc.driverClassName=org.h2.Driver -user.jdbc.url=jdbc:h2:mem:spring_jpa_user;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS USERS -product.jdbc.url=jdbc:h2:mem:spring_jpa_product;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS PRODUCTS -jdbc.user=sa -jdbc.pass=sa - -# hibernate.X -hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=false -hibernate.hbm2ddl.auto=create-drop -hibernate.cache.use_second_level_cache=false -hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/SpringContextTest.java deleted file mode 100644 index eaccf4acba..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.Application; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java deleted file mode 100644 index 27c71c5bcc..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.Application; - -@RunWith(SpringRunner.class) -@DataJpaTest -@ContextConfiguration(classes = Application.class) -public class SpringJpaContextIntegrationTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/BatchInsertIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/BatchInsertIntegrationTest.java deleted file mode 100644 index 7ddf36d3f0..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/BatchInsertIntegrationTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.batchinserts; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; - -import com.baeldung.boot.Application; -import com.baeldung.boot.daos.CustomerRepository; -import com.baeldung.boot.web.controllers.CustomerController; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes=Application.class) -@AutoConfigureMockMvc -public class BatchInsertIntegrationTest { - - @Autowired - private CustomerRepository customerRepository; - private MockMvc mockMvc; - @Before - public void setUp() throws Exception { - mockMvc = MockMvcBuilders.standaloneSetup( new CustomerController(customerRepository)) - .build(); - } - - @Test - public void whenInsertingCustomers_thenCustomersAreCreated() throws Exception { - this.mockMvc.perform(post("/customers")) - .andExpect(status().isOk()); - } - -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/JpaBatchInsertsIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/JpaBatchInsertsIntegrationTest.java deleted file mode 100644 index 311f227322..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/JpaBatchInsertsIntegrationTest.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.baeldung.batchinserts; - -import static com.baeldung.batchinserts.TestObjectHelper.createSchool; -import static com.baeldung.batchinserts.TestObjectHelper.createStudent; - -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.TypedQuery; - -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.batchinserts.model.School; -import com.baeldung.batchinserts.model.Student; -import com.baeldung.boot.Application; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -@Transactional -@ActiveProfiles("batchinserts") -public class JpaBatchInsertsIntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - private static final int BATCH_SIZE = 5; - - @Transactional - @Test - public void whenInsertingSingleTypeOfEntity_thenCreatesSingleBatch() { - for (int i = 0; i < 10; i++) { - School school = createSchool(i); - entityManager.persist(school); - } - } - - @Transactional - @Test - public void whenFlushingAfterBatch_ThenClearsMemory() { - for (int i = 0; i < 10; i++) { - if (i > 0 && i % BATCH_SIZE == 0) { - entityManager.flush(); - entityManager.clear(); - } - - School school = createSchool(i); - entityManager.persist(school); - } - } - - @Transactional - @Test - public void whenThereAreMultipleEntities_ThenCreatesNewBatch() { - for (int i = 0; i < 10; i++) { - if (i > 0 && i % BATCH_SIZE == 0) { - entityManager.flush(); - entityManager.clear(); - } - - School school = createSchool(i); - entityManager.persist(school); - Student firstStudent = createStudent(school); - Student secondStudent = createStudent(school); - entityManager.persist(firstStudent); - entityManager.persist(secondStudent); - } - } - - @Transactional - @Test - public void whenUpdatingEntities_thenCreatesBatch() { - for (int i = 0; i < 10; i++) { - School school = createSchool(i); - entityManager.persist(school); - } - - entityManager.flush(); - - TypedQuery schoolQuery = entityManager.createQuery("SELECT s from School s", School.class); - List allSchools = schoolQuery.getResultList(); - - for (School school : allSchools) { - school.setName("Updated_" + school.getName()); - } - } - - @After - public void tearDown() { - entityManager.flush(); - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/JpaNoBatchInsertsIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/JpaNoBatchInsertsIntegrationTest.java deleted file mode 100644 index 75b3f1f3aa..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/JpaNoBatchInsertsIntegrationTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.batchinserts; - -import static com.baeldung.batchinserts.TestObjectHelper.createSchool; - -import com.baeldung.batchinserts.model.School; -import com.baeldung.boot.Application; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -@Transactional -@ActiveProfiles("batchinserts") -@TestPropertySource(properties = "spring.jpa.properties.hibernate.jdbc.batch_size=-1") -public class JpaNoBatchInsertsIntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - @Test - public void whenNotConfigured_ThenSendsInsertsSeparately() { - for (int i = 0; i < 10; i++) { - School school = createSchool(i); - entityManager.persist(school); - } - } - - @After - public void tearDown() { - entityManager.flush(); - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/TestObjectHelper.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/TestObjectHelper.java deleted file mode 100644 index fcd26cb721..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/TestObjectHelper.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.batchinserts; - -import com.baeldung.batchinserts.model.School; -import com.baeldung.batchinserts.model.Student; - -public class TestObjectHelper { - - public static School createSchool(int nameIdentifier) { - School school = new School(); - school.setName("School" + (nameIdentifier + 1)); - return school; - } - - public static Student createStudent(School school) { - Student student = new Student(); - student.setName("Student-" + school.getName()); - student.setSchool(school); - return student; - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/PersonInsertRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/PersonInsertRepositoryIntegrationTest.java deleted file mode 100644 index 9d45c17035..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/PersonInsertRepositoryIntegrationTest.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.baeldung.boot.daos; - -import com.baeldung.boot.daos.impl.PersonInsertRepository; -import com.baeldung.boot.domain.Person; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit4.SpringRunner; - -import javax.persistence.EntityExistsException; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceException; - -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; - -@RunWith(SpringRunner.class) -@DataJpaTest -@Import(PersonInsertRepository.class) -public class PersonInsertRepositoryIntegrationTest { - - private static final Long ID = 1L; - private static final String FIRST_NAME = "firstname"; - private static final String LAST_NAME = "lastname"; - private static final Person PERSON = new Person(ID, FIRST_NAME, LAST_NAME); - - @Autowired - private PersonInsertRepository personInsertRepository; - - @Autowired - private EntityManager entityManager; - - @Test - public void givenPersonEntity_whenInsertWithNativeQuery_ThenPersonIsPersisted() { - insertWithQuery(); - - assertPersonPersisted(); - } - - @Test - public void givenPersonEntity_whenInsertedTwiceWithNativeQuery_thenPersistenceExceptionExceptionIsThrown() { - assertThatExceptionOfType(PersistenceException.class).isThrownBy(() -> { - insertWithQuery(); - insertWithQuery(); - }); - } - - @Test - public void givenPersonEntity_whenInsertWithEntityManager_thenPersonIsPersisted() { - insertPersonWithEntityManager(); - - assertPersonPersisted(); - } - - @Test - public void givenPersonEntity_whenInsertedTwiceWithEntityManager_thenEntityExistsExceptionIsThrown() { - assertThatExceptionOfType(EntityExistsException.class).isThrownBy(() -> { - insertPersonWithEntityManager(); - insertPersonWithEntityManager(); - }); - } - - private void insertWithQuery() { - personInsertRepository.insertWithQuery(PERSON); - } - - private void insertPersonWithEntityManager() { - personInsertRepository.insertWithEntityManager(new Person(ID, FIRST_NAME, LAST_NAME)); - } - - private void assertPersonPersisted() { - Person person = entityManager.find(Person.class, ID); - - assertThat(person).isNotNull(); - assertThat(person.getId()).isEqualTo(PERSON.getId()); - assertThat(person.getFirstName()).isEqualTo(PERSON.getFirstName()); - assertThat(person.getLastName()).isEqualTo(PERSON.getLastName()); - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java deleted file mode 100644 index b2581b8034..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java +++ /dev/null @@ -1,545 +0,0 @@ -package com.baeldung.boot.daos; - -import org.junit.After; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Sort; -import org.springframework.data.jpa.domain.JpaSort; -import org.springframework.data.mapping.PropertyReferenceException; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.boot.daos.user.UserRepository; -import com.baeldung.boot.domain.User; - -import javax.persistence.EntityManager; -import javax.persistence.Query; -import java.time.LocalDate; -import java.util.*; -import java.util.function.Predicate; -import java.util.stream.Stream; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.*; - -public class UserRepositoryCommon { - - final String USER_EMAIL = "email@example.com"; - final String USER_EMAIL2 = "email2@example.com"; - final String USER_EMAIL3 = "email3@example.com"; - final String USER_EMAIL4 = "email4@example.com"; - final Integer INACTIVE_STATUS = 0; - final Integer ACTIVE_STATUS = 1; - final String USER_EMAIL5 = "email5@example.com"; - final String USER_EMAIL6 = "email6@example.com"; - final String USER_NAME_ADAM = "Adam"; - final String USER_NAME_PETER = "Peter"; - - @Autowired - protected UserRepository userRepository; - @Autowired - private EntityManager entityManager; - - @Test - @Transactional - public void givenUsersWithSameNameInDB_WhenFindAllByName_ThenReturnStreamOfUsers() { - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setEmail(USER_EMAIL); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_ADAM); - user2.setEmail(USER_EMAIL2); - userRepository.save(user2); - - User user3 = new User(); - user3.setName(USER_NAME_ADAM); - user3.setEmail(USER_EMAIL3); - userRepository.save(user3); - - User user4 = new User(); - user4.setName("SAMPLE"); - user4.setEmail(USER_EMAIL4); - userRepository.save(user4); - - try (Stream foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) { - assertThat(foundUsersStream.count()).isEqualTo(3l); - } - } - - @Test - public void givenUsersInDB_WhenFindAllWithQueryAnnotation_ThenReturnCollectionWithActiveUsers() { - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setEmail(USER_EMAIL); - user1.setStatus(ACTIVE_STATUS); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_ADAM); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User user3 = new User(); - user3.setName(USER_NAME_ADAM); - user3.setEmail(USER_EMAIL3); - user3.setStatus(INACTIVE_STATUS); - userRepository.save(user3); - - Collection allActiveUsers = userRepository.findAllActiveUsers(); - - assertThat(allActiveUsers.size()).isEqualTo(2); - } - - @Test - public void givenUsersInDB_WhenFindAllWithQueryAnnotationNative_ThenReturnCollectionWithActiveUsers() { - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setEmail(USER_EMAIL); - user1.setStatus(ACTIVE_STATUS); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_ADAM); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User user3 = new User(); - user3.setName(USER_NAME_ADAM); - user3.setEmail(USER_EMAIL3); - user3.setStatus(INACTIVE_STATUS); - userRepository.save(user3); - - Collection allActiveUsers = userRepository.findAllActiveUsersNative(); - - assertThat(allActiveUsers.size()).isEqualTo(2); - } - - @Test - public void givenUserInDB_WhenFindUserByStatusWithQueryAnnotation_ThenReturnActiveUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByStatus(ACTIVE_STATUS); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUserInDB_WhenFindUserByStatusWithQueryAnnotationNative_ThenReturnActiveUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByStatusNative(ACTIVE_STATUS); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationIndexedParams_ThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByStatusAndName(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNamedParams_ThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByStatusAndNameNamedParams(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParams_ThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByStatusAndNameNamedParamsNative(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNames_ThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByUserStatusAndUserName(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationIndexedParams_ThenReturnUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByNameLike("Ad"); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationNamedParams_ThenReturnUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByNameLikeNamedParam("Ad"); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationNative_ThenReturnUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByNameLikeNative("Ad"); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindAllWithSortByName_ThenReturnUsersSorted() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - - List usersSortByName = userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); - - assertThat(usersSortByName.get(0) - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test(expected = PropertyReferenceException.class) - public void givenUsersInDB_WhenFindAllSortWithFunction_ThenThrowException() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - - userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); - - List usersSortByNameLength = userRepository.findAll(Sort.by("LENGTH(name)")); - - assertThat(usersSortByNameLength.get(0) - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindAllSortWithFunctionQueryAnnotationJPQL_ThenReturnUsersSorted() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - - userRepository.findAllUsers(Sort.by("name")); - - List usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)")); - - assertThat(usersSortByNameLength.get(0) - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindAllWithPageRequestQueryAnnotationJPQL_ThenReturnPageOfUsers() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL4, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS)); - - Page usersPage = userRepository.findAllUsersWithPagination(PageRequest.of(1, 3)); - - assertThat(usersPage.getContent() - .get(0) - .getName()).isEqualTo("SAMPLE1"); - } - - @Test - public void givenUsersInDB_WhenFindAllWithPageRequestQueryAnnotationNative_ThenReturnPageOfUsers() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL4, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS)); - - Page usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(PageRequest.of(1, 3)); - - assertThat(usersSortByNameLength.getContent() - .get(0) - .getName()).isEqualTo(USER_NAME_PETER); - } - - @Test - @Transactional - public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationJPQL_ThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); - - int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE"); - - assertThat(updatedUsersSize).isEqualTo(2); - } - - @Test - public void givenUsersInDB_WhenFindByEmailsWithDynamicQuery_ThenReturnCollection() { - - User user1 = new User(); - user1.setEmail(USER_EMAIL); - userRepository.save(user1); - - User user2 = new User(); - user2.setEmail(USER_EMAIL2); - userRepository.save(user2); - - User user3 = new User(); - user3.setEmail(USER_EMAIL3); - userRepository.save(user3); - - Set emails = new HashSet<>(); - emails.add(USER_EMAIL2); - emails.add(USER_EMAIL3); - - Collection usersWithEmails = userRepository.findUserByEmails(emails); - - assertThat(usersWithEmails.size()).isEqualTo(2); - } - - @Test - public void givenUsersInDBWhenFindByNameListReturnCollection() { - - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setEmail(USER_EMAIL); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - userRepository.save(user2); - - List names = Arrays.asList(USER_NAME_ADAM, USER_NAME_PETER); - - List usersWithNames = userRepository.findUserByNameList(names); - - assertThat(usersWithNames.size()).isEqualTo(2); - } - - - @Test - @Transactional - public void whenInsertedWithQuery_ThenUserIsPersisted() { - userRepository.insertUser(USER_NAME_ADAM, 1, USER_EMAIL, ACTIVE_STATUS, true); - userRepository.insertUser(USER_NAME_PETER, 1, USER_EMAIL2, ACTIVE_STATUS, true); - - User userAdam = userRepository.findUserByNameLike(USER_NAME_ADAM); - User userPeter = userRepository.findUserByNameLike(USER_NAME_PETER); - - assertThat(userAdam).isNotNull(); - assertThat(userAdam.getEmail()).isEqualTo(USER_EMAIL); - assertThat(userPeter).isNotNull(); - assertThat(userPeter.getEmail()).isEqualTo(USER_EMAIL2); - } - - - @Test - @Transactional - public void givenTwoUsers_whenFindByNameUsr01_ThenUserUsr01() { - User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.now(), "usr02@baeldung.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - try (Stream users = userRepository.findAllByName("usr01")) { - assertTrue(users.allMatch(usr -> usr.equals(usr01))); - } - } - - @Test - @Transactional - public void givenTwoUsers_whenFindByNameUsr00_ThenNoUsers() { - User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.now(), "usr02@baeldung.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - try (Stream users = userRepository.findAllByName("usr00")) { - assertEquals(0, users.count()); - } - } - - @Test - public void givenTwoUsers_whenFindUsersWithGmailAddress_ThenUserUsr02() { - User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.now(), "usr02@gmail.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - List users = userRepository.findUsersWithGmailAddress(); - assertEquals(1, users.size()); - assertEquals(usr02, users.get(0)); - } - - @Test - @Transactional - public void givenTwoUsers_whenDeleteAllByCreationDateAfter_ThenOneUserRemains() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - userRepository.deleteAllByCreationDateAfter(LocalDate.of(2018, 5, 1)); - - List users = userRepository.findAll(); - - assertEquals(1, users.size()); - assertEquals(usr01, users.get(0)); - } - - @Test - public void givenTwoUsers_whenFindAllUsersByPredicates_ThenUserUsr01() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - List> predicates = new ArrayList<>(); - predicates.add(usr -> usr.getCreationDate().isAfter(LocalDate.of(2017, 12, 31))); - predicates.add(usr -> usr.getEmail().endsWith(".com")); - - List users = userRepository.findAllUsersByPredicates(predicates); - - assertEquals(1, users.size()); - assertEquals(usr01, users.get(0)); - } - - @Test - @Transactional - public void givenTwoUsers_whenDeactivateUsersNotLoggedInSince_ThenUserUsr02Deactivated() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - usr01.setLastLoginDate(LocalDate.now()); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); - usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); - - userRepository.save(usr01); - userRepository.save(usr02); - - userRepository.deactivateUsersNotLoggedInSince(LocalDate.of(2018, 8, 1)); - - List users = userRepository.findAllUsers(Sort.by(Sort.Order.asc("name"))); - assertTrue(users.get(0).isActive()); - assertFalse(users.get(1).isActive()); - } - - @Test - @Transactional - public void givenTwoUsers_whenDeleteDeactivatedUsers_ThenUserUsr02Deleted() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - usr01.setLastLoginDate(LocalDate.now()); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.com", 0); - usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); - usr02.setActive(false); - - userRepository.save(usr01); - userRepository.save(usr02); - - int deletedUsersCount = userRepository.deleteDeactivatedUsers(); - - List users = userRepository.findAll(); - assertEquals(1, users.size()); - assertEquals(usr01, users.get(0)); - assertEquals(1, deletedUsersCount); - } - - @Test - @Transactional - public void givenTwoUsers_whenAddDeletedColumn_ThenUsersHaveDeletedColumn() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - usr01.setLastLoginDate(LocalDate.now()); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); - usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); - usr02.setActive(false); - - userRepository.save(usr01); - userRepository.save(usr02); - - userRepository.addDeletedColumn(); - - Query nativeQuery = entityManager.createNativeQuery("select deleted from USERS where NAME = 'usr01'"); - assertEquals(0, nativeQuery.getResultList().get(0)); - } - - @After - public void cleanUp() { - userRepository.deleteAll(); - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java deleted file mode 100644 index 99eabc8271..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.boot.daos; - -import com.baeldung.boot.Application; -import com.baeldung.boot.domain.User; -import com.baeldung.util.BaeldungPostgresqlContainer; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; -import org.testcontainers.containers.PostgreSQLContainer; - -import java.time.LocalDate; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Created by adam. - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -@ActiveProfiles({"tc", "tc-auto"}) -public class UserRepositoryTCAutoLiveTest extends UserRepositoryCommon { - - @ClassRule - public static PostgreSQLContainer postgreSQLContainer = BaeldungPostgresqlContainer.getInstance(); - - @Test - @Transactional - public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationNativePostgres_ThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); - userRepository.flush(); - - int updatedUsersSize = userRepository.updateUserSetStatusForNameNativePostgres(INACTIVE_STATUS, "SAMPLE"); - - assertThat(updatedUsersSize).isEqualTo(2); - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java deleted file mode 100644 index be8843c166..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.boot.daos; - -import com.baeldung.boot.Application; -import com.baeldung.boot.domain.User; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.util.TestPropertyValues; -import org.springframework.context.ApplicationContextInitializer; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; -import org.testcontainers.containers.PostgreSQLContainer; - -import java.time.LocalDate; - -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -@ActiveProfiles("tc") -@ContextConfiguration(initializers = {UserRepositoryTCLiveTest.Initializer.class}) -public class UserRepositoryTCLiveTest extends UserRepositoryCommon { - - @ClassRule - public static PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer("postgres:11.1") - .withDatabaseName("integration-tests-db") - .withUsername("sa") - .withPassword("sa"); - - @Test - @Transactional - public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationNative_ThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); - userRepository.flush(); - - int updatedUsersSize = userRepository.updateUserSetStatusForNameNativePostgres(INACTIVE_STATUS, "SAMPLE"); - - assertThat(updatedUsersSize).isEqualTo(2); - } - - static class Initializer - implements ApplicationContextInitializer { - public void initialize(ConfigurableApplicationContext configurableApplicationContext) { - TestPropertyValues.of( - "spring.datasource.url=" + postgreSQLContainer.getJdbcUrl(), - "spring.datasource.username=" + postgreSQLContainer.getUsername(), - "spring.datasource.password=" + postgreSQLContainer.getPassword() - ).applyTo(configurableApplicationContext.getEnvironment()); - } - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/passenger/PassengerRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/passenger/PassengerRepositoryIntegrationTest.java deleted file mode 100644 index f082350019..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/passenger/PassengerRepositoryIntegrationTest.java +++ /dev/null @@ -1,190 +0,0 @@ -package com.baeldung.boot.passenger; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.data.domain.Example; -import org.springframework.data.domain.ExampleMatcher; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Sort; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.passenger.Passenger; -import com.baeldung.boot.passenger.PassengerRepository; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import java.util.List; -import java.util.Optional; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.core.IsNot.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - - -@DataJpaTest -@RunWith(SpringRunner.class) -public class PassengerRepositoryIntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - @Autowired - private PassengerRepository repository; - - @Before - public void before() { - entityManager.persist(Passenger.from("Jill", "Smith", 50)); - entityManager.persist(Passenger.from("Eve", "Jackson", 95)); - entityManager.persist(Passenger.from("Fred", "Bloggs", 22)); - entityManager.persist(Passenger.from("Ricki", "Bobbie", 36)); - entityManager.persist(Passenger.from("Siya", "Kolisi", 85)); - } - - @Test - public void givenSeveralPassengersWhenOrderedBySeatNumberLimitedToThenThePassengerInTheFirstFilledSeatIsReturned() { - Passenger expected = Passenger.from("Fred", "Bloggs", 22); - - List passengers = repository.findOrderedBySeatNumberLimitedTo(1); - - assertEquals(1, passengers.size()); - - Passenger actual = passengers.get(0); - assertEquals(expected, actual); - } - - @Test - public void givenSeveralPassengersWhenFindFirstByOrderBySeatNumberAscThenThePassengerInTheFirstFilledSeatIsReturned() { - Passenger expected = Passenger.from("Fred", "Bloggs", 22); - - Passenger actual = repository.findFirstByOrderBySeatNumberAsc(); - - assertEquals(expected, actual); - } - - @Test - public void givenSeveralPassengersWhenFindPageSortedByThenThePassengerInTheFirstFilledSeatIsReturned() { - Passenger expected = Passenger.from("Fred", "Bloggs", 22); - - Page page = repository.findAll(PageRequest.of(0, 1, - Sort.by(Sort.Direction.ASC, "seatNumber"))); - - assertEquals(1, page.getContent().size()); - - Passenger actual = page.getContent().get(0); - assertEquals(expected, actual); - } - - @Test - public void givenPassengers_whenOrderedBySeatNumberAsc_thenCorrectOrder() { - Passenger fred = Passenger.from("Fred", "Bloggs", 22); - Passenger ricki = Passenger.from("Ricki", "Bobbie", 36); - Passenger jill = Passenger.from("Jill", "Smith", 50); - Passenger siya = Passenger.from("Siya", "Kolisi", 85); - Passenger eve = Passenger.from("Eve", "Jackson", 95); - - List passengers = repository.findByOrderBySeatNumberAsc(); - - assertThat(passengers, contains(fred, ricki, jill, siya, eve)); - } - - @Test - public void givenPassengers_whenFindAllWithSortBySeatNumberAsc_thenCorrectOrder() { - Passenger fred = Passenger.from("Fred", "Bloggs", 22); - Passenger ricki = Passenger.from("Ricki", "Bobbie", 36); - Passenger jill = Passenger.from("Jill", "Smith", 50); - Passenger siya = Passenger.from("Siya", "Kolisi", 85); - Passenger eve = Passenger.from("Eve", "Jackson", 95); - - List passengers = repository.findAll(Sort.by(Sort.Direction.ASC, "seatNumber")); - - assertThat(passengers, contains(fred, ricki, jill, siya, eve)); - } - - @Test - public void givenPassengers_whenFindByExampleDefaultMatcher_thenExpectedReturned() { - Example example = Example.of(Passenger.from("Fred", "Bloggs", null)); - - Optional actual = repository.findOne(example); - - assertTrue(actual.isPresent()); - assertEquals(Passenger.from("Fred", "Bloggs", 22), actual.get()); - } - - @Test - public void givenPassengers_whenFindByExampleCaseInsensitiveMatcher_thenExpectedReturned() { - ExampleMatcher caseInsensitiveExampleMatcher = ExampleMatcher.matchingAll().withIgnoreCase(); - Example example = Example.of(Passenger.from("fred", "bloggs", null), - caseInsensitiveExampleMatcher); - - Optional actual = repository.findOne(example); - - assertTrue(actual.isPresent()); - assertEquals(Passenger.from("Fred", "Bloggs", 22), actual.get()); - } - - @Test - public void givenPassengers_whenFindByExampleCustomMatcher_thenExpectedReturned() { - Passenger jill = Passenger.from("Jill", "Smith", 50); - Passenger eve = Passenger.from("Eve", "Jackson", 95); - Passenger fred = Passenger.from("Fred", "Bloggs", 22); - Passenger siya = Passenger.from("Siya", "Kolisi", 85); - Passenger ricki = Passenger.from("Ricki", "Bobbie", 36); - - ExampleMatcher customExampleMatcher = ExampleMatcher.matchingAny().withMatcher("firstName", - ExampleMatcher.GenericPropertyMatchers.contains().ignoreCase()).withMatcher("lastName", - ExampleMatcher.GenericPropertyMatchers.contains().ignoreCase()); - - Example example = Example.of(Passenger.from("e", "s", null), - customExampleMatcher); - - List passengers = repository.findAll(example); - - assertThat(passengers, contains(jill, eve, fred, siya)); - assertThat(passengers, not(contains(ricki))); - } - - @Test - public void givenPassengers_whenFindByIgnoringMatcher_thenExpectedReturned() { - Passenger jill = Passenger.from("Jill", "Smith", 50); - Passenger eve = Passenger.from("Eve", "Jackson", 95); - Passenger fred = Passenger.from("Fred", "Bloggs", 22); - Passenger siya = Passenger.from("Siya", "Kolisi", 85); - Passenger ricki = Passenger.from("Ricki", "Bobbie", 36); - - ExampleMatcher ignoringExampleMatcher = ExampleMatcher.matchingAny().withMatcher("lastName", - ExampleMatcher.GenericPropertyMatchers.startsWith().ignoreCase()).withIgnorePaths("firstName", "seatNumber"); - - Example example = Example.of(Passenger.from(null, "b", null), - ignoringExampleMatcher); - - List passengers = repository.findAll(example); - - assertThat(passengers, contains(fred, ricki)); - assertThat(passengers, not(contains(jill))); - assertThat(passengers, not(contains(eve))); - assertThat(passengers, not(contains(siya))); - } - - @Test - public void givenPassengers_whenMatchingIgnoreCase_thenExpectedReturned() { - Passenger jill = Passenger.from("Jill", "Smith", 50); - Passenger eve = Passenger.from("Eve", "Jackson", 95); - Passenger fred = Passenger.from("Fred", "Bloggs", 22); - Passenger siya = Passenger.from("Siya", "Kolisi", 85); - Passenger ricki = Passenger.from("Ricki", "Bobbie", 36); - - List passengers = repository.findByFirstNameIgnoreCase("FRED"); - - assertThat(passengers, contains(fred)); - assertThat(passengers, not(contains(eve))); - assertThat(passengers, not(contains(siya))); - assertThat(passengers, not(contains(jill))); - assertThat(passengers, not(contains(ricki))); - - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java deleted file mode 100644 index 831790af95..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java +++ /dev/null @@ -1,142 +0,0 @@ -package com.baeldung.multipledb; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.EnableTransactionManagement; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.multipledb.dao.product.ProductRepository; -import com.baeldung.multipledb.model.product.Product; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes=MultipleDbApplication.class) -@EnableTransactionManagement -public class ProductRepositoryIntegrationTest { - - @Autowired - private ProductRepository productRepository; - - @Before - @Transactional("productTransactionManager") - public void setUp() { - productRepository.save(Product.from(1001, "Book", 21)); - productRepository.save(Product.from(1002, "Coffee", 10)); - productRepository.save(Product.from(1003, "Jeans", 30)); - productRepository.save(Product.from(1004, "Shirt", 32)); - productRepository.save(Product.from(1005, "Bacon", 10)); - } - - @Test - public void whenRequestingFirstPageOfSizeTwo_ThenReturnFirstPage() { - Pageable pageRequest = PageRequest.of(0, 2); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(2)); - assertTrue(result.stream() - .map(Product::getId) - .allMatch(id -> Arrays.asList(1001, 1002) - .contains(id))); - } - - @Test - public void whenRequestingSecondPageOfSizeTwo_ThenReturnSecondPage() { - Pageable pageRequest = PageRequest.of(1, 2); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(2)); - assertTrue(result.stream() - .map(Product::getId) - .allMatch(id -> Arrays.asList(1003, 1004) - .contains(id))); - } - - @Test - public void whenRequestingLastPage_ThenReturnLastPageWithRemData() { - Pageable pageRequest = PageRequest.of(2, 2); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(1)); - assertTrue(result.stream() - .map(Product::getId) - .allMatch(id -> Arrays.asList(1005) - .contains(id))); - } - - @Test - public void whenSortingByNameAscAndPaging_ThenReturnSortedPagedResult() { - Pageable pageRequest = PageRequest.of(0, 3, Sort.by("name")); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(3)); - assertThat(result.getContent() - .stream() - .map(Product::getId) - .collect(Collectors.toList()), equalTo(Arrays.asList(1005, 1001, 1002))); - - } - - @Test - public void whenSortingByPriceDescAndPaging_ThenReturnSortedPagedResult() { - Pageable pageRequest = PageRequest.of(0, 3, Sort.by("price") - .descending()); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(3)); - assertThat(result.getContent() - .stream() - .map(Product::getId) - .collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001))); - - } - - @Test - public void whenSortingByPriceDescAndNameAscAndPaging_ThenReturnSortedPagedResult() { - Pageable pageRequest = PageRequest.of(0, 5, Sort.by("price") - .descending() - .and(Sort.by("name"))); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(5)); - assertThat(result.getContent() - .stream() - .map(Product::getId) - .collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001, 1005, 1002))); - - } - - @Test - public void whenRequestingFirstPageOfSizeTwoUsingCustomMethod_ThenReturnFirstPage() { - Pageable pageRequest = PageRequest.of(0, 2); - - List result = productRepository.findAllByPrice(10, pageRequest); - - assertThat(result, hasSize(2)); - assertTrue(result.stream() - .map(Product::getId) - .allMatch(id -> Arrays.asList(1002, 1005) - .contains(id))); - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/repository/EmployeeRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/repository/EmployeeRepositoryIntegrationTest.java deleted file mode 100644 index 0fc9918701..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/repository/EmployeeRepositoryIntegrationTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.repository; - -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.Application; -import com.baeldung.entity.Employee; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -public class EmployeeRepositoryIntegrationTest { - - private static final Employee EMPLOYEE1 = new Employee(1L, "John"); - private static final Employee EMPLOYEE2 = new Employee(2L, "Alice"); - - @Autowired - private EmployeeRepository employeeRepository; - - @Test - public void givenEmployeeEntity_whenInsertWithSave_ThenEmployeeIsPersisted() { - employeeRepository.save(EMPLOYEE1); - assertEmployeePersisted(EMPLOYEE1); - } - - @Test - public void givenEmployeeEntity_whenInsertWithSaveAndFlush_ThenEmployeeIsPersisted() { - employeeRepository.saveAndFlush(EMPLOYEE2); - assertEmployeePersisted(EMPLOYEE2); - } - - private void assertEmployeePersisted(Employee input) { - Employee employee = employeeRepository.getOne(input.getId()); - assertThat(employee).isNotNull(); - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java deleted file mode 100644 index e5ad2dd448..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.util; - -import org.testcontainers.containers.PostgreSQLContainer; - -public class BaeldungPostgresqlContainer extends PostgreSQLContainer { - - private static final String IMAGE_VERSION = "postgres:11.1"; - - private static BaeldungPostgresqlContainer container; - - - private BaeldungPostgresqlContainer() { - super(IMAGE_VERSION); - } - - public static BaeldungPostgresqlContainer getInstance() { - if (container == null) { - container = new BaeldungPostgresqlContainer(); - } - return container; - } - - @Override - public void start() { - super.start(); - System.setProperty("DB_URL", container.getJdbcUrl()); - System.setProperty("DB_USERNAME", container.getUsername()); - System.setProperty("DB_PASSWORD", container.getPassword()); - } - - @Override - public void stop() { - //do nothing, JVM handles shut down - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/resources/application-batchinserts.properties b/persistence-modules/spring-data-jpa-3/src/test/resources/application-batchinserts.properties deleted file mode 100644 index 4141f5668e..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/resources/application-batchinserts.properties +++ /dev/null @@ -1,6 +0,0 @@ -spring.jpa.show-sql=false - -spring.jpa.properties.hibernate.jdbc.batch_size=5 -spring.jpa.properties.hibernate.order_inserts=true -spring.jpa.properties.hibernate.order_updates=true -spring.jpa.properties.hibernate.batch_versioned_data=true \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-3/src/test/resources/application-tc-auto.properties b/persistence-modules/spring-data-jpa-3/src/test/resources/application-tc-auto.properties deleted file mode 100644 index c3005d861f..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/resources/application-tc-auto.properties +++ /dev/null @@ -1,4 +0,0 @@ -# configuration for test containers testing -spring.datasource.url=${DB_URL} -spring.datasource.username=${DB_USERNAME} -spring.datasource.password=${DB_PASSWORD} diff --git a/persistence-modules/spring-data-jpa-3/src/test/resources/application-tc.properties b/persistence-modules/spring-data-jpa-3/src/test/resources/application-tc.properties deleted file mode 100644 index 3bf8693d53..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/resources/application-tc.properties +++ /dev/null @@ -1,4 +0,0 @@ -# configuration for Test Containers testing -spring.datasource.driver-class-name=org.postgresql.Driver -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false diff --git a/persistence-modules/spring-data-jpa-3/src/test/resources/application-test.properties b/persistence-modules/spring-data-jpa-3/src/test/resources/application-test.properties deleted file mode 100644 index f9497c8f37..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/resources/application-test.properties +++ /dev/null @@ -1,2 +0,0 @@ -spring.jpa.hibernate.ddl-auto=update -spring.datasource.url=jdbc:h2:mem:jpa3 \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/README.md b/persistence-modules/spring-data-jpa-4/README.md deleted file mode 100644 index 085dfcb366..0000000000 --- a/persistence-modules/spring-data-jpa-4/README.md +++ /dev/null @@ -1,18 +0,0 @@ -### Relevant Articles: -- [Derived Query Methods in Spring Data JPA Repositories](https://www.baeldung.com/spring-data-derived-queries) -- [LIKE Queries in Spring JPA Repositories](https://www.baeldung.com/spring-jpa-like-queries) -- [A Guide to Spring’s Open Session In View](https://www.baeldung.com/spring-open-session-in-view) -- [Programmatic Transaction Management in Spring](https://www.baeldung.com/spring-programmatic-transaction-management) -- [JPA Entity Lifecycle Events](https://www.baeldung.com/jpa-entity-lifecycle-events) -- [Working with Lazy Element Collections in JPA](https://www.baeldung.com/java-jpa-lazy-collections) -- [Calling Stored Procedures from Spring Data JPA Repositories](https://www.baeldung.com/spring-data-jpa-stored-procedures) -- [Custom Naming Convention with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-custom-naming) - -### Eclipse Config -After importing the project into Eclipse, you may see the following error: -"No persistence xml file found in project" - -This can be ignored: -- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" -Or: -- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator diff --git a/persistence-modules/spring-data-jpa-4/create.sql b/persistence-modules/spring-data-jpa-4/create.sql deleted file mode 100644 index 1bbe1640a7..0000000000 --- a/persistence-modules/spring-data-jpa-4/create.sql +++ /dev/null @@ -1,2 +0,0 @@ -create table PERSON (ID int8 not null, FIRST_NAME varchar(255), LAST_NAME varchar(255), primary key (ID)) -create table person (id int8 not null, first_name varchar(255), last_name varchar(255), primary key (id)) diff --git a/persistence-modules/spring-data-jpa-4/pom.xml b/persistence-modules/spring-data-jpa-4/pom.xml deleted file mode 100644 index 71fc21527f..0000000000 --- a/persistence-modules/spring-data-jpa-4/pom.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - 4.0.0 - spring-data-jpa-4 - spring-data-jpa-4 - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - org.springframework.boot - spring-boot-starter-data-jdbc - - - - mysql - mysql-connector-java - - - - org.postgresql - postgresql - - - - com.h2database - h2 - - - - \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/QueryApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/QueryApplication.java deleted file mode 100644 index d7a1950305..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/QueryApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.derivedquery; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class QueryApplication { - - public static void main(String[] args) { - SpringApplication.run(QueryApplication.class, args); - } - -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/entity/User.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/entity/User.java deleted file mode 100644 index 49e824f09f..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/entity/User.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.baeldung.derivedquery.entity; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; -import java.time.ZonedDateTime; - -@Table(name = "users") -@Entity -public class User { - - @Id - @GeneratedValue - private Integer id; - private String name; - private Integer age; - private ZonedDateTime birthDate; - private Boolean active; - - public User() { - } - - public User(String name, Integer age, ZonedDateTime birthDate, Boolean active) { - this.name = name; - this.age = age; - this.birthDate = birthDate; - this.active = active; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } - - public ZonedDateTime getBirthDate() { - return birthDate; - } - - public void setBirthDate(ZonedDateTime birthDate) { - this.birthDate = birthDate; - } - - public Boolean getActive() { - return active; - } - - public void setActive(Boolean active) { - this.active = active; - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/repository/UserRepository.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/repository/UserRepository.java deleted file mode 100644 index e613ee1531..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/repository/UserRepository.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.derivedquery.repository; - -import com.baeldung.derivedquery.entity.User; -import org.springframework.data.jpa.repository.JpaRepository; - -import java.time.ZonedDateTime; -import java.util.Collection; -import java.util.List; - -public interface UserRepository extends JpaRepository { - - List findByName(String name); - - List findByNameIs(String name); - - List findByNameEquals(String name); - - List findByNameIsNull(); - - List findByNameNot(String name); - - List findByNameIsNot(String name); - - List findByNameStartingWith(String name); - - List findByNameEndingWith(String name); - - List findByNameContaining(String name); - - List findByNameLike(String name); - - List findByAgeLessThan(Integer age); - - List findByAgeLessThanEqual(Integer age); - - List findByAgeGreaterThan(Integer age); - - List findByAgeGreaterThanEqual(Integer age); - - List findByAgeBetween(Integer startAge, Integer endAge); - - List findByBirthDateAfter(ZonedDateTime birthDate); - - List findByBirthDateBefore(ZonedDateTime birthDate); - - List findByActiveTrue(); - - List findByActiveFalse(); - - List findByAgeIn(Collection ages); - - List findByNameOrBirthDate(String name, ZonedDateTime birthDate); - - List findByNameOrBirthDateAndActive(String name, ZonedDateTime birthDate, Boolean active); - - List findByNameOrderByName(String name); - - List findByNameOrderByNameDesc(String name); - -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/ElementCollectionApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/ElementCollectionApplication.java deleted file mode 100644 index 3f152a6ffc..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/ElementCollectionApplication.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.elementcollection; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class ElementCollectionApplication { - public static void main(String[] args) { - SpringApplication.run(ElementCollectionApplication.class, args); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Employee.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Employee.java deleted file mode 100644 index 8b98164d63..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Employee.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.baeldung.elementcollection.model; - -import javax.persistence.*; -import java.util.List; -import java.util.Objects; - -@Entity -public class Employee { - @Id - private int id; - private String name; - @ElementCollection - @CollectionTable(name = "employee_phone", joinColumns = @JoinColumn(name = "employee_id")) - private List phones; - - public Employee() { - } - - public Employee(int id) { - this.id = id; - } - - public Employee(int id, String name) { - this.id = id; - this.name = name; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getPhones() { - return phones; - } - - public void setPhones(List phones) { - this.phones = phones; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof Employee)) { - return false; - } - Employee user = (Employee) o; - return getId() == user.getId(); - } - - @Override - public int hashCode() { - return Objects.hash(getId()); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Phone.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Phone.java deleted file mode 100644 index d73d30c47a..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Phone.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung.elementcollection.model; - -import javax.persistence.Embeddable; -import java.util.Objects; - -@Embeddable -public class Phone { - private String type; - private String areaCode; - private String number; - - public Phone() { - } - - public Phone(String type, String areaCode, String number) { - this.type = type; - this.areaCode = areaCode; - this.number = number; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getAreaCode() { - return areaCode; - } - - public void setAreaCode(String areaCode) { - this.areaCode = areaCode; - } - - public String getNumber() { - return number; - } - - public void setNumber(String number) { - this.number = number; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof Phone)) { - return false; - } - Phone phone = (Phone) o; - return getType().equals(phone.getType()) && getAreaCode().equals(phone.getAreaCode()) - && getNumber().equals(phone.getNumber()); - } - - @Override - public int hashCode() { - return Objects.hash(getType(), getAreaCode(), getNumber()); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java deleted file mode 100644 index 49180c35eb..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.elementcollection.repository; - -import com.baeldung.elementcollection.model.Employee; -import org.springframework.stereotype.Repository; -import org.springframework.transaction.annotation.Transactional; - -import javax.persistence.EntityGraph; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import java.util.HashMap; -import java.util.Map; - -@Repository -public class EmployeeRepository { - - @PersistenceContext - private EntityManager em; - - @Transactional - public void save(Employee employee) { - em.persist(employee); - } - - @Transactional - public void remove(int id) { - Employee employee = findById(id); - em.remove(employee); - } - - public Employee findById(int id) { - return em.find(Employee.class, id); - } - - public Employee findByJPQL(int id) { - return em.createQuery("SELECT u FROM Employee AS u JOIN FETCH u.phones WHERE u.id=:id", Employee.class) - .setParameter("id", id).getSingleResult(); - } - - public Employee findByEntityGraph(int id) { - EntityGraph entityGraph = em.createEntityGraph(Employee.class); - entityGraph.addAttributeNodes("name", "phones"); - Map properties = new HashMap<>(); - properties.put("javax.persistence.fetchgraph", entityGraph); - return em.find(Employee.class, id, properties); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/SpringBootLifecycleEventApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/SpringBootLifecycleEventApplication.java deleted file mode 100644 index fbc861c5fe..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/SpringBootLifecycleEventApplication.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.lifecycleevents; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class SpringBootLifecycleEventApplication { - public static void main(String[] args) { - SpringApplication.run(SpringBootLifecycleEventApplication.class, args); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/model/AuditTrailListener.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/model/AuditTrailListener.java deleted file mode 100644 index 26ebff42e4..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/model/AuditTrailListener.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.lifecycleevents.model; - -import javax.persistence.PostLoad; -import javax.persistence.PostPersist; -import javax.persistence.PostRemove; -import javax.persistence.PostUpdate; -import javax.persistence.PrePersist; -import javax.persistence.PreRemove; -import javax.persistence.PreUpdate; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class AuditTrailListener { - private static Log log = LogFactory.getLog(AuditTrailListener.class); - - @PrePersist - @PreUpdate - @PreRemove - private void beforeAnyUpdate(User user) { - if (user.getId() == 0) { - log.info("[USER AUDIT] About to add a user"); - } else { - log.info("[USER AUDIT] About to update/delete user: " + user.getId()); - } - } - - @PostPersist - @PostUpdate - @PostRemove - private void afterAnyUpdate(User user) { - log.info("[USER AUDIT] add/update/delete complete for user: " + user.getId()); - } - - @PostLoad - private void afterLoad(User user) { - log.info("[USER AUDIT] user loaded from database: " + user.getId()); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/model/User.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/model/User.java deleted file mode 100644 index a080cb3bf2..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/model/User.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.baeldung.lifecycleevents.model; - -import javax.persistence.Entity; -import javax.persistence.EntityListeners; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.PostLoad; -import javax.persistence.PostPersist; -import javax.persistence.PostRemove; -import javax.persistence.PostUpdate; -import javax.persistence.PrePersist; -import javax.persistence.PreRemove; -import javax.persistence.PreUpdate; -import javax.persistence.Transient; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -@Entity -@EntityListeners(AuditTrailListener.class) -public class User { - private static Log log = LogFactory.getLog(User.class); - - @Id - @GeneratedValue - private int id; - - private String userName; - private String firstName; - private String lastName; - @Transient - private String fullName; - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - 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 getFullName() { - return fullName; - } - - @PrePersist - public void logNewUserAttempt() { - log.info("Attempting to add new user with username: " + userName); - } - - @PostPersist - public void logNewUserAdded() { - log.info("Added user '" + userName + "' with ID: " + id); - } - - @PreRemove - public void logUserRemovalAttempt() { - log.info("Attempting to delete user: " + userName); - } - - @PostRemove - public void logUserRemoval() { - log.info("Deleted user: " + userName); - } - - @PreUpdate - public void logUserUpdateAttempt() { - log.info("Attempting to update user: " + userName); - } - - @PostUpdate - public void logUserUpdate() { - log.info("Updated user: " + userName); - } - - @PostLoad - public void logUserLoad() { - fullName = firstName + " " + lastName; - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/repository/UserRepository.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/repository/UserRepository.java deleted file mode 100644 index af14117ebb..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/repository/UserRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.lifecycleevents.repository; - -import org.springframework.data.jpa.repository.JpaRepository; - -import com.baeldung.lifecycleevents.model.User; - -public interface UserRepository extends JpaRepository { - public User findByUserName(String userName); -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/LikeApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/LikeApplication.java deleted file mode 100644 index 311aea3001..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/LikeApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.like; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class LikeApplication { - - public static void main(String[] args) { - SpringApplication.run(LikeApplication.class, args); - } - -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/model/Movie.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/model/Movie.java deleted file mode 100644 index bba8bd35c4..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/model/Movie.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.like.model; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class Movie { - @Id - @GeneratedValue(strategy = GenerationType.SEQUENCE) - private Long id; - private String title; - private String director; - private String rating; - private int duration; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getDirector() { - return director; - } - - public void setDirector(String director) { - this.director = director; - } - - public String getRating() { - return rating; - } - - public void setRating(String rating) { - this.rating = rating; - } - - public int getDuration() { - return duration; - } - - public void setDuration(int duration) { - this.duration = duration; - } - -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/repository/MovieRepository.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/repository/MovieRepository.java deleted file mode 100644 index 241bdd3306..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/repository/MovieRepository.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.like.repository; - -import java.util.List; - -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.CrudRepository; -import org.springframework.data.repository.query.Param; - -import com.baeldung.like.model.Movie; - -public interface MovieRepository extends CrudRepository { - - List findByTitleContaining(String title); - - List findByTitleLike(String title); - - List findByTitleContains(String title); - - List findByTitleIsContaining(String title); - - List findByRatingStartsWith(String rating); - - List findByDirectorEndsWith(String director); - - List findByTitleContainingIgnoreCase(String title); - - List findByRatingNotContaining(String rating); - - List findByDirectorNotLike(String director); - - @Query("SELECT m FROM Movie m WHERE m.title LIKE %:title%") - List searchByTitleLike(@Param("title") String title); - - @Query("SELECT m FROM Movie m WHERE m.rating LIKE ?1%") - List searchByRatingStartsWith(String rating); - - //Escaping works in SpringBoot >= 2.4.1 - //@Query("SELECT m FROM Movie m WHERE m.director LIKE %?#{escape([0])} escape ?#{escapeCharacter()}") - @Query("SELECT m FROM Movie m WHERE m.director LIKE %:#{[0]}") - List searchByDirectorEndsWith(String director); -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java deleted file mode 100644 index cfb6e67c2c..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.namingstrategy; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; - -@Entity -public class Person { - @Id - private Long id; - - private String firstName; - - private String lastName; - - public Person() {} - - public Person(Long id, String firstName, String lastName) { - this.id = id; - this.firstName = firstName; - this.lastName = lastName; - } - - public Long id() { - return id; - } - - public String firstName() { - return firstName; - } - - public String lastName() { - return lastName; - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/PersonRepository.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/PersonRepository.java deleted file mode 100644 index 3c7c25bbcb..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/PersonRepository.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.springframework.data.jpa.repository.JpaRepository; - -public interface PersonRepository extends JpaRepository { -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java deleted file mode 100644 index 16b01e50e3..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.boot.model.naming.Identifier; -import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; - -public class QuotedLowerCaseNamingStrategy extends SpringPhysicalNamingStrategy { - @Override - protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { - return new Identifier(name.toLowerCase(), true); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java deleted file mode 100644 index 3cb62aa5a2..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.boot.model.naming.Identifier; -import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; - -public class QuotedUpperCaseNamingStrategy extends SpringPhysicalNamingStrategy { - @Override - protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { - return new Identifier(name.toUpperCase(), true); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java deleted file mode 100644 index f223015db8..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class SpringDataJpaNamingConventionApplication { -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java deleted file mode 100644 index 69e96aee27..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.boot.model.naming.Identifier; -import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; - -public class UnquotedLowerCaseNamingStrategy extends SpringPhysicalNamingStrategy { - @Override - protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { - return new Identifier(name.toLowerCase(), false); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java deleted file mode 100644 index cb87af10f4..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.boot.model.naming.Identifier; -import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; - -public class UnquotedUpperCaseNamingStrategy extends SpringPhysicalNamingStrategy { - @Override - protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { - return new Identifier(name.toUpperCase(), false); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/OsivApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/OsivApplication.java deleted file mode 100644 index 4cfcf83e56..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/OsivApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.osiv; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class OsivApplication { - - public static void main(String[] args) { - SpringApplication.run(OsivApplication.class, args); - } - -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/model/BasicUser.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/model/BasicUser.java deleted file mode 100644 index 98f4e379d4..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/model/BasicUser.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.osiv.model; - -import javax.persistence.*; -import java.util.Set; - -@Entity -@Table(name = "users") -public class BasicUser { - - @Id - @GeneratedValue - private Long id; - - private String username; - - @ElementCollection - private Set permissions; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public Set getPermissions() { - return permissions; - } - - public void setPermissions(Set permissions) { - this.permissions = permissions; - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/repository/BasicUserRepository.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/repository/BasicUserRepository.java deleted file mode 100644 index e8d5955d91..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/repository/BasicUserRepository.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.osiv.repository; - -import java.util.Optional; - -import org.springframework.data.jpa.repository.EntityGraph; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.osiv.model.BasicUser; - -@Repository -@Transactional -public interface BasicUserRepository extends JpaRepository { - - @EntityGraph(attributePaths = "permissions") - Optional findDetailedByUsername(String username); - -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/service/SimpleUserService.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/service/SimpleUserService.java deleted file mode 100644 index 1de51678d5..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/service/SimpleUserService.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.osiv.service; - -import java.util.Optional; - -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.osiv.model.BasicUser; -import com.baeldung.osiv.repository.BasicUserRepository; - -@Service -public class SimpleUserService implements UserService { - - private final BasicUserRepository userRepository; - - public SimpleUserService(BasicUserRepository userRepository) { - this.userRepository = userRepository; - } - - @Override - @Transactional(readOnly = true) - public Optional findOne(String username) { - return userRepository.findDetailedByUsername(username); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/service/UserService.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/service/UserService.java deleted file mode 100644 index 3d089fa41b..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/service/UserService.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.osiv.service; - -import com.baeldung.osiv.model.BasicUser; - -import java.util.Optional; - -public interface UserService { - Optional findOne(String username); -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/web/DetailedUserDto.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/web/DetailedUserDto.java deleted file mode 100644 index fd2882c2d5..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/web/DetailedUserDto.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.baeldung.osiv.web; - -import com.baeldung.osiv.model.BasicUser; - -import java.util.Set; - -public class DetailedUserDto { - - private Long id; - private String username; - private Set permissions; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public Set getPermissions() { - return permissions; - } - - public void setPermissions(Set permissions) { - this.permissions = permissions; - } - - public static DetailedUserDto fromEntity(BasicUser user) { - DetailedUserDto detailed = new DetailedUserDto(); - detailed.setId(user.getId()); - detailed.setUsername(user.getUsername()); - detailed.setPermissions(user.getPermissions()); - - return detailed; - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/web/UserController.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/web/UserController.java deleted file mode 100644 index 5466b95166..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/web/UserController.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.osiv.web; - -import com.baeldung.osiv.service.UserService; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@RequestMapping("/users") -public class UserController { - - private final UserService userService; - - public UserController(UserService userService) { - this.userService = userService; - } - - @GetMapping("/{username}") - public ResponseEntity findOne(@PathVariable String username) { - return userService.findOne(username) - .map(DetailedUserDto::fromEntity) - .map(ResponseEntity::ok) - .orElse(ResponseEntity.notFound().build()); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/StoredProcedureApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/StoredProcedureApplication.java deleted file mode 100644 index 5f05764e21..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/StoredProcedureApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.storedprocedure; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class StoredProcedureApplication { - - public static void main(String[] args) { - SpringApplication.run(StoredProcedureApplication.class, args); - } - -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/controller/CarController.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/controller/CarController.java deleted file mode 100644 index 6aef600d01..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/controller/CarController.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.storedprocedure.controller; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import com.baeldung.storedprocedure.entity.Car; -import com.baeldung.storedprocedure.service.CarService; - -@RestController -public class CarController { - @Autowired - private CarService carService; - - @GetMapping(path = "/modelcount") - public long getTotalCarsByModel(@RequestParam("model") String model) { - return carService.getTotalCarsByModel(model); - } - - @GetMapping(path = "/modelcountP") - public long getTotalCarsByModelProcedureName(@RequestParam("model") String model) { - return carService.getTotalCarsByModelProcedureName(model); - } - - @GetMapping(path = "/modelcountV") - public long getTotalCarsByModelVaue(@RequestParam("model") String model) { - return carService.getTotalCarsByModelValue(model); - } - - @GetMapping(path = "/modelcountEx") - public long getTotalCarsByModelExplicit(@RequestParam("model") String model) { - return carService.getTotalCarsByModelExplicit(model); - } - - @GetMapping(path = "/modelcountEn") - public long getTotalCarsByModelEntity(@RequestParam("model") String model) { - return carService.getTotalCarsByModelEntity(model); - } - - @GetMapping(path = "/carsafteryear") - public List findCarsAfterYear(@RequestParam("year") Integer year) { - return carService.findCarsAfterYear(year); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/entity/Car.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/entity/Car.java deleted file mode 100644 index 2817c25ff7..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/entity/Car.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.storedprocedure.entity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.NamedStoredProcedureQuery; -import javax.persistence.StoredProcedureParameter; -import javax.persistence.ParameterMode; - -@Entity -@NamedStoredProcedureQuery(name = "Car.getTotalCardsbyModelEntity", procedureName = "GET_TOTAL_CARS_BY_MODEL", parameters = { - @StoredProcedureParameter(mode = ParameterMode.IN, name = "model_in", type = String.class), - @StoredProcedureParameter(mode = ParameterMode.OUT, name = "count_out", type = Integer.class) }) - -public class Car { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column - private long id; - - @Column - private String model; - - @Column - private Integer year; - - public long getId() { - return id; - } - - public String getModel() { - return model; - } - - public Integer getYear() { - return year; - } - -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/repository/CarRepository.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/repository/CarRepository.java deleted file mode 100644 index 3d9428628e..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/repository/CarRepository.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.storedprocedure.repository; - -import java.util.List; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.jpa.repository.query.Procedure; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -import com.baeldung.storedprocedure.entity.Car; - -@Repository -public interface CarRepository extends JpaRepository { - - @Procedure - int GET_TOTAL_CARS_BY_MODEL(String model); - - @Procedure("GET_TOTAL_CARS_BY_MODEL") - int getTotalCarsByModel(String model); - - @Procedure(procedureName = "GET_TOTAL_CARS_BY_MODEL") - int getTotalCarsByModelProcedureName(String model); - - @Procedure(value = "GET_TOTAL_CARS_BY_MODEL") - int getTotalCarsByModelValue(String model); - - @Procedure(name = "Car.getTotalCardsbyModelEntity") - int getTotalCarsByModelEntiy(@Param("model_in") String model); - - @Query(value = "CALL FIND_CARS_AFTER_YEAR(:year_in);", nativeQuery = true) - List findCarsAfterYear(@Param("year_in") Integer year_in); - -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/service/CarService.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/service/CarService.java deleted file mode 100644 index 104f46e324..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/service/CarService.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.storedprocedure.service; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.baeldung.storedprocedure.entity.Car; -import com.baeldung.storedprocedure.repository.CarRepository; - -@Service -public class CarService { - @Autowired - private CarRepository carRepository; - - public int getTotalCarsByModel(String model) { - return carRepository.getTotalCarsByModel(model); - } - - public int getTotalCarsByModelProcedureName(String model) { - return carRepository.getTotalCarsByModelProcedureName(model); - } - - public int getTotalCarsByModelValue(String model) { - return carRepository.getTotalCarsByModelValue(model); - } - - public int getTotalCarsByModelExplicit(String model) { - return carRepository.GET_TOTAL_CARS_BY_MODEL(model); - } - - public int getTotalCarsByModelEntity(String model) { - return carRepository.getTotalCarsByModelEntiy(model); - } - - public List findCarsAfterYear(Integer year) { - return carRepository.findCarsAfterYear(year); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/tx/TxApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/tx/TxApplication.java deleted file mode 100644 index 4c982c91e9..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/tx/TxApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.tx; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class TxApplication { - - public static void main(String[] args) { - SpringApplication.run(TxApplication.class, args); - } - -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/tx/model/Payment.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/tx/model/Payment.java deleted file mode 100644 index 921a1e9275..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/tx/model/Payment.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.baeldung.tx.model; - -import javax.persistence.*; - -@Entity -public class Payment { - - @Id - @GeneratedValue - private Long id; - - private Long amount; - - @Column(unique = true) - private String referenceNumber; - - @Enumerated(EnumType.STRING) - private State state; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Long getAmount() { - return amount; - } - - public void setAmount(Long amount) { - this.amount = amount; - } - - public String getReferenceNumber() { - return referenceNumber; - } - - public void setReferenceNumber(String referenceNumber) { - this.referenceNumber = referenceNumber; - } - - public State getState() { - return state; - } - - public void setState(State state) { - this.state = state; - } - - public enum State { - STARTED, FAILED, SUCCESSFUL - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-4/src/main/resources/application.properties deleted file mode 100644 index 65d7b0bf29..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/resources/application.properties +++ /dev/null @@ -1,5 +0,0 @@ -spring.jpa.show-sql=true -#MySql -#spring.datasource.url=jdbc:mysql://localhost:3306/baeldung -#spring.datasource.username=baeldung -#spring.datasource.password=baeldung \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/main/resources/car-mysql.sql b/persistence-modules/spring-data-jpa-4/src/main/resources/car-mysql.sql deleted file mode 100644 index bb4ab2a86e..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/resources/car-mysql.sql +++ /dev/null @@ -1,27 +0,0 @@ -DROP TABLE IF EXISTS car; - -CREATE TABLE car (id int(10) NOT NULL AUTO_INCREMENT, - model varchar(50) NOT NULL, - year int(4) NOT NULL, - PRIMARY KEY (id)); - -INSERT INTO car (model, year) VALUES ('BMW', 2000); -INSERT INTO car (model, year) VALUES ('BENZ', 2010); -INSERT INTO car (model, year) VALUES ('PORCHE', 2005); -INSERT INTO car (model, year) VALUES ('PORCHE', 2004); - -DELIMITER $$ - -DROP PROCEDURE IF EXISTS FIND_CARS_AFTER_YEAR$$ -CREATE PROCEDURE FIND_CARS_AFTER_YEAR(IN year_in INT) -BEGIN - SELECT * FROM car WHERE year >= year_in ORDER BY year; -END$$ - -DROP PROCEDURE IF EXISTS GET_TOTAL_CARS_BY_MODEL$$ -CREATE PROCEDURE GET_TOTAL_CARS_BY_MODEL(IN model_in VARCHAR(50), OUT count_out INT) -BEGIN - SELECT COUNT(*) into count_out from car WHERE model = model_in; -END$$ - -DELIMITER ; diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java deleted file mode 100644 index 2a6e166b88..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java +++ /dev/null @@ -1,172 +0,0 @@ -package com.baeldung.derivedquery.repository; - -import com.baeldung.derivedquery.QueryApplication; -import com.baeldung.derivedquery.entity.User; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import java.time.ZonedDateTime; -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = QueryApplication.class) -public class UserRepositoryIntegrationTest { - - private static final String USER_NAME_ADAM = "Adam"; - private static final String USER_NAME_EVE = "Eve"; - private static final ZonedDateTime BIRTHDATE = ZonedDateTime.now(); - - @Autowired - private UserRepository userRepository; - - @Before - public void setUp() { - - User user1 = new User(USER_NAME_ADAM, 25, BIRTHDATE, true); - User user2 = new User(USER_NAME_ADAM, 20, BIRTHDATE, false); - User user3 = new User(USER_NAME_EVE, 20, BIRTHDATE, true); - User user4 = new User(null, 30, BIRTHDATE, false); - - userRepository.saveAll(Arrays.asList(user1, user2, user3, user4)); - } - - @After - public void tearDown() { - - userRepository.deleteAll(); - } - - @Test - public void whenFindByName_thenReturnsCorrectResult() { - - assertEquals(2, userRepository.findByName(USER_NAME_ADAM).size()); - } - - @Test - public void whenFindByNameIsNull_thenReturnsCorrectResult() { - - assertEquals(1, userRepository.findByNameIsNull().size()); - } - - @Test - public void whenFindByNameNot_thenReturnsCorrectResult() { - - assertEquals(USER_NAME_EVE, userRepository.findByNameNot(USER_NAME_ADAM).get(0).getName()); - } - - @Test - public void whenFindByNameStartingWith_thenReturnsCorrectResult() { - - assertEquals(2, userRepository.findByNameStartingWith("A").size()); - } - - @Test - public void whenFindByNameEndingWith_thenReturnsCorrectResult() { - - assertEquals(1, userRepository.findByNameEndingWith("e").size()); - } - - @Test - public void whenByNameContaining_thenReturnsCorrectResult() { - - assertEquals(1, userRepository.findByNameContaining("v").size()); - } - - - @Test - public void whenByNameLike_thenReturnsCorrectResult() { - - assertEquals(2, userRepository.findByNameEndingWith("m").size()); - } - - @Test - public void whenByAgeLessThan_thenReturnsCorrectResult() { - - assertEquals(2, userRepository.findByAgeLessThan(25).size()); - } - - - @Test - public void whenByAgeLessThanEqual_thenReturnsCorrectResult() { - - assertEquals(3, userRepository.findByAgeLessThanEqual(25).size()); - } - - @Test - public void whenByAgeGreaterThan_thenReturnsCorrectResult() { - - assertEquals(1, userRepository.findByAgeGreaterThan(25).size()); - } - - @Test - public void whenByAgeGreaterThanEqual_thenReturnsCorrectResult() { - - assertEquals(2, userRepository.findByAgeGreaterThanEqual(25).size()); - } - - @Test - public void whenByAgeBetween_thenReturnsCorrectResult() { - - assertEquals(4, userRepository.findByAgeBetween(20, 30).size()); - } - - @Test - public void whenByBirthDateAfter_thenReturnsCorrectResult() { - - final ZonedDateTime yesterday = BIRTHDATE.minusDays(1); - assertEquals(4, userRepository.findByBirthDateAfter(yesterday).size()); - } - - @Test - public void whenByBirthDateBefore_thenReturnsCorrectResult() { - - final ZonedDateTime yesterday = BIRTHDATE.minusDays(1); - assertEquals(0, userRepository.findByBirthDateBefore(yesterday).size()); - } - - @Test - public void whenByActiveTrue_thenReturnsCorrectResult() { - - assertEquals(2, userRepository.findByActiveTrue().size()); - } - - @Test - public void whenByActiveFalse_thenReturnsCorrectResult() { - - assertEquals(2, userRepository.findByActiveFalse().size()); - } - - - @Test - public void whenByAgeIn_thenReturnsCorrectResult() { - - final List ages = Arrays.asList(20, 25); - assertEquals(3, userRepository.findByAgeIn(ages).size()); - } - - @Test - public void whenByNameOrBirthDate() { - - assertEquals(4, userRepository.findByNameOrBirthDate(USER_NAME_ADAM, BIRTHDATE).size()); - } - - @Test - public void whenByNameOrBirthDateAndActive() { - - assertEquals(3, userRepository.findByNameOrBirthDateAndActive(USER_NAME_ADAM, BIRTHDATE, false).size()); - } - - @Test - public void whenByNameOrderByName() { - - assertEquals(2, userRepository.findByNameOrderByName(USER_NAME_ADAM).size()); - } -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java deleted file mode 100644 index 306798aa68..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.baeldung.elementcollection; - -import com.baeldung.elementcollection.model.Employee; -import com.baeldung.elementcollection.model.Phone; -import com.baeldung.elementcollection.repository.EmployeeRepository; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; - -import java.util.Arrays; - -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ElementCollectionApplication.class) -public class ElementCollectionIntegrationTest { - - @Autowired - private EmployeeRepository employeeRepository; - - @Before - public void init() { - Employee employee = new Employee(1, "Fred"); - employee.setPhones( - Arrays.asList(new Phone("work", "+55", "99999-9999"), new Phone("home", "+55", "98888-8888"))); - employeeRepository.save(employee); - } - - @After - public void clean() { - employeeRepository.remove(1); - } - - @Test(expected = org.hibernate.LazyInitializationException.class) - public void whenAccessLazyCollection_thenThrowLazyInitializationException() { - Employee employee = employeeRepository.findById(1); - assertThat(employee.getPhones().size(), is(2)); - } - - @Test - public void whenUseJPAQL_thenFetchResult() { - Employee employee = employeeRepository.findByJPQL(1); - assertThat(employee.getPhones().size(), is(2)); - } - - @Test - public void whenUseEntityGraph_thenFetchResult() { - Employee employee = employeeRepository.findByEntityGraph(1); - assertThat(employee.getPhones().size(), is(2)); - } - - @Test - @Transactional - public void whenUseTransaction_thenFetchResult() { - Employee employee = employeeRepository.findById(1); - assertThat(employee.getPhones().size(), is(2)); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java deleted file mode 100644 index cc96b638ab..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.baeldung.like; - -import com.baeldung.like.model.Movie; -import com.baeldung.like.repository.MovieRepository; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.jdbc.Sql; -import org.springframework.test.context.junit4.SpringRunner; - -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; - -@RunWith(SpringRunner.class) -@Sql(scripts = { "/test-movie-data.sql" }) -@SpringBootTest(classes = LikeApplication.class) -@Sql(scripts = "/test-movie-cleanup.sql", executionPhase = AFTER_TEST_METHOD) -public class MovieRepositoryIntegrationTest { - @Autowired - private MovieRepository movieRepository; - - @Test - public void givenPartialTitle_WhenFindByTitleContaining_ThenMoviesShouldReturn() { - List results = movieRepository.findByTitleContaining("in"); - assertEquals(3, results.size()); - - results = movieRepository.findByTitleLike("%in%"); - assertEquals(3, results.size()); - - results = movieRepository.findByTitleIsContaining("in"); - assertEquals(3, results.size()); - - results = movieRepository.findByTitleContains("in"); - assertEquals(3, results.size()); - } - - @Test - public void givenStartOfRating_WhenFindByRatingStartsWith_ThenMoviesShouldReturn() { - List results = movieRepository.findByRatingStartsWith("PG"); - assertEquals(6, results.size()); - } - - @Test - public void givenLastName_WhenFindByDirectorEndsWith_ThenMoviesShouldReturn() { - List results = movieRepository.findByDirectorEndsWith("Burton"); - assertEquals(1, results.size()); - } - - @Test - public void givenPartialTitle_WhenFindByTitleContainingIgnoreCase_ThenMoviesShouldReturn() { - List results = movieRepository.findByTitleContainingIgnoreCase("the"); - assertEquals(2, results.size()); - } - - @Test - public void givenPartialTitle_WhenSearchByTitleLike_ThenMoviesShouldReturn() { - List results = movieRepository.searchByTitleLike("in"); - assertEquals(3, results.size()); - } - - @Test - public void givenStartOfRating_SearchFindByRatingStartsWith_ThenMoviesShouldReturn() { - List results = movieRepository.searchByRatingStartsWith("PG"); - assertEquals(6, results.size()); - } - - @Test - public void givenLastName_WhenSearchByDirectorEndsWith_ThenMoviesShouldReturn() { - List results = movieRepository.searchByDirectorEndsWith("Burton"); - assertEquals(1, results.size()); - } - - @Test - public void givenPartialRating_findByRatingNotContaining_ThenMoviesShouldReturn() { - List results = movieRepository.findByRatingNotContaining("PG"); - assertEquals(1, results.size()); - } - - @Test - public void givenPartialDirector_WhenFindByDirectorNotLike_ThenMoviesShouldReturn() { - List results = movieRepository.findByDirectorNotLike("An%"); - assertEquals(5, results.size()); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java deleted file mode 100644 index 71a4dbda3f..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.exception.SQLGrammarException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.TestPropertySource; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) -@TestPropertySource("quoted-lower-case-naming-strategy.properties") -class QuotedLowerCaseNamingStrategyH2IntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private PersonRepository personRepository; - - @BeforeEach - void insertPeople() { - personRepository.saveAll(Arrays.asList( - new Person(1L, "John", "Doe"), - new Person(2L, "Jane", "Doe"), - new Person(3L, "Ted", "Mosby") - )); - } - - @ParameterizedTest - @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenException(String tableName) { - Query query = entityManager.createNativeQuery("select * from " + tableName); - - // Unexpected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - @Test - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { - Query query = entityManager.createNativeQuery("select * from \"PERSON\""); - - // Expected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - @Test - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { - Query query = entityManager.createNativeQuery("select * from \"person\""); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - public Person fromDatabase(Object databaseRow) { - Object[] typedDatabaseRow = (Object[]) databaseRow; - - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), - (String) typedDatabaseRow[1], - (String) typedDatabaseRow[2] - ); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java deleted file mode 100644 index 6b1c984600..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.exception.SQLGrammarException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.TestPropertySource; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) -@TestPropertySource("quoted-lower-case-naming-strategy-on-postgres.properties") -class QuotedLowerCaseNamingStrategyPostgresLiveTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private PersonRepository personRepository; - - @BeforeEach - void insertPeople() { - personRepository.saveAll(Arrays.asList( - new Person(1L, "John", "Doe"), - new Person(2L, "Jane", "Doe"), - new Person(3L, "Ted", "Mosby") - )); - } - - @ParameterizedTest - @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { - Query query = entityManager.createNativeQuery("select * from " + tableName); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { - Query query = entityManager.createNativeQuery("select * from \"PERSON\""); - - // Expected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - @Test - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { - Query query = entityManager.createNativeQuery("select * from \"person\""); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - public Person fromDatabase(Object databaseRow) { - Object[] typedDatabaseRow = (Object[]) databaseRow; - - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), - (String) typedDatabaseRow[1], - (String) typedDatabaseRow[2] - ); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java deleted file mode 100644 index f819327a5c..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.exception.SQLGrammarException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.TestPropertySource; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) -@TestPropertySource("quoted-upper-case-naming-strategy.properties") -class QuotedUpperCaseNamingStrategyH2IntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private PersonRepository personRepository; - - @BeforeEach - void insertPeople() { - personRepository.saveAll(Arrays.asList( - new Person(1L, "John", "Doe"), - new Person(2L, "Jane", "Doe"), - new Person(3L, "Ted", "Mosby") - )); - } - - @ParameterizedTest - @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenException(String tableName) { - Query query = entityManager.createNativeQuery("select * from " + tableName); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { - Query query = entityManager.createNativeQuery("select * from \"PERSON\""); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { - Query query = entityManager.createNativeQuery("select * from \"person\""); - - // Expected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - public Person fromDatabase(Object databaseRow) { - Object[] typedDatabaseRow = (Object[]) databaseRow; - - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), - (String) typedDatabaseRow[1], - (String) typedDatabaseRow[2] - ); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java deleted file mode 100644 index bd23b81b4b..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.exception.SQLGrammarException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.TestPropertySource; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) -@TestPropertySource("quoted-upper-case-naming-strategy-on-postgres.properties") -class QuotedUpperCaseNamingStrategyPostgresLiveTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private PersonRepository personRepository; - - @BeforeEach - void insertPeople() { - personRepository.saveAll(Arrays.asList( - new Person(1L, "John", "Doe"), - new Person(2L, "Jane", "Doe"), - new Person(3L, "Ted", "Mosby") - )); - } - - @ParameterizedTest - @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { - Query query = entityManager.createNativeQuery("select * from " + tableName); - - // Unexpected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - @Test - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { - Query query = entityManager.createNativeQuery("select * from \"PERSON\""); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { - Query query = entityManager.createNativeQuery("select * from \"person\""); - - // Expected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - public Person fromDatabase(Object databaseRow) { - Object[] typedDatabaseRow = (Object[]) databaseRow; - - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), - (String) typedDatabaseRow[1], - (String) typedDatabaseRow[2] - ); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java deleted file mode 100644 index 1850fea173..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.exception.SQLGrammarException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.TestPropertySource; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) -@TestPropertySource("spring-physical-naming-strategy.properties") -class SpringPhysicalNamingStrategyH2IntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private PersonRepository personRepository; - - @BeforeEach - void insertPeople() { - personRepository.saveAll(Arrays.asList( - new Person(1L, "John", "Doe"), - new Person(2L, "Jane", "Doe"), - new Person(3L, "Ted", "Mosby") - )); - } - - @ParameterizedTest - @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndSpringNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { - Query query = entityManager.createNativeQuery("select * from " + tableName); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { - Query query = entityManager.createNativeQuery("select * from \"PERSON\""); - - // Unexpected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { - Query query = entityManager.createNativeQuery("select * from \"person\""); - - // Unexpected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - public Person fromDatabase(Object databaseRow) { - Object[] typedDatabaseRow = (Object[]) databaseRow; - - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), - (String) typedDatabaseRow[1], - (String) typedDatabaseRow[2] - ); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java deleted file mode 100644 index e26ebb148d..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.exception.SQLGrammarException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.TestPropertySource; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) -@TestPropertySource("spring-physical-naming-strategy-on-postgres.properties") -class SpringPhysicalNamingStrategyPostgresLiveTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private PersonRepository personRepository; - - @BeforeEach - void insertPeople() { - personRepository.saveAll(Arrays.asList( - new Person(1L, "John", "Doe"), - new Person(2L, "Jane", "Doe"), - new Person(3L, "Ted", "Mosby") - )); - } - - @ParameterizedTest - @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndSpringNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { - Query query = entityManager.createNativeQuery("select * from " + tableName); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { - Query query = entityManager.createNativeQuery("select * from \"PERSON\""); - - // Expected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - @Test - void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { - Query query = entityManager.createNativeQuery("select * from \"person\""); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - public Person fromDatabase(Object databaseRow) { - Object[] typedDatabaseRow = (Object[]) databaseRow; - - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), - (String) typedDatabaseRow[1], - (String) typedDatabaseRow[2] - ); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java deleted file mode 100644 index 6311c42e93..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.exception.SQLGrammarException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.TestPropertySource; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.sql.SQLException; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) -@TestPropertySource("unquoted-lower-case-naming-strategy.properties") -class UnquotedLowerCaseNamingStrategyH2IntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private PersonRepository personRepository; - - @BeforeEach - void insertPeople() { - personRepository.saveAll(Arrays.asList( - new Person(1L, "John", "Doe"), - new Person(2L, "Jane", "Doe"), - new Person(3L, "Ted", "Mosby") - )); - } - - @ParameterizedTest - @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { - Query query = entityManager.createNativeQuery("select * from " + tableName); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { - Query query = entityManager.createNativeQuery("select * from \"PERSON\""); - - // Unexpected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { - Query query = entityManager.createNativeQuery("select * from \"person\""); - - // Unexpected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - public Person fromDatabase(Object databaseRow) { - Object[] typedDatabaseRow = (Object[]) databaseRow; - - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), - (String) typedDatabaseRow[1], - (String) typedDatabaseRow[2] - ); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java deleted file mode 100644 index 033a213cf5..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.exception.SQLGrammarException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.TestPropertySource; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) -@TestPropertySource("unquoted-lower-case-naming-strategy-on-postgres.properties") -class UnquotedLowerCaseNamingStrategyPostgresLiveTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private PersonRepository personRepository; - - @BeforeEach - void insertPeople() { - personRepository.saveAll(Arrays.asList( - new Person(1L, "John", "Doe"), - new Person(2L, "Jane", "Doe"), - new Person(3L, "Ted", "Mosby") - )); - } - - @ParameterizedTest - @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { - Query query = entityManager.createNativeQuery("select * from " + tableName); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { - Query query = entityManager.createNativeQuery("select * from \"PERSON\""); - - // Expected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - @Test - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { - Query query = entityManager.createNativeQuery("select * from \"person\""); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - public Person fromDatabase(Object databaseRow) { - Object[] typedDatabaseRow = (Object[]) databaseRow; - - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), - (String) typedDatabaseRow[1], - (String) typedDatabaseRow[2] - ); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java deleted file mode 100644 index 7af8001854..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.exception.SQLGrammarException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.TestPropertySource; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) -@TestPropertySource("unquoted-upper-case-naming-strategy.properties") -class UnquotedUpperCaseNamingStrategyH2IntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private PersonRepository personRepository; - - @BeforeEach - void insertPeople() { - personRepository.saveAll(Arrays.asList( - new Person(1L, "John", "Doe"), - new Person(2L, "Jane", "Doe"), - new Person(3L, "Ted", "Mosby") - )); - } - - @ParameterizedTest - @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { - Query query = entityManager.createNativeQuery("select * from " + tableName); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { - Query query = entityManager.createNativeQuery("select * from \"PERSON\""); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { - Query query = entityManager.createNativeQuery("select * from \"person\""); - - // Expected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - public Person fromDatabase(Object databaseRow) { - Object[] typedDatabaseRow = (Object[]) databaseRow; - - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), - (String) typedDatabaseRow[1], - (String) typedDatabaseRow[2] - ); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java deleted file mode 100644 index 0151e7ece4..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.exception.SQLGrammarException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.TestPropertySource; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) -@TestPropertySource("unquoted-upper-case-naming-strategy-on-postgres.properties") -class UnquotedUpperCaseNamingStrategyPostgresLiveTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private PersonRepository personRepository; - - @BeforeEach - void insertPeople() { - personRepository.saveAll(Arrays.asList( - new Person(1L, "John", "Doe"), - new Person(2L, "Jane", "Doe"), - new Person(3L, "Ted", "Mosby") - )); - } - - @ParameterizedTest - @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { - Query query = entityManager.createNativeQuery("select * from " + tableName); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { - Query query = entityManager.createNativeQuery("select * from \"PERSON\""); - - // Unexpected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - @Test - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { - Query query = entityManager.createNativeQuery("select * from \"person\""); - - // Unexpected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - public Person fromDatabase(Object databaseRow) { - Object[] typedDatabaseRow = (Object[]) databaseRow; - - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), - (String) typedDatabaseRow[1], - (String) typedDatabaseRow[2] - ); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/osiv/UserControllerIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/osiv/UserControllerIntegrationTest.java deleted file mode 100644 index 350b67e1c9..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/osiv/UserControllerIntegrationTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.baeldung.osiv; - -import com.baeldung.osiv.model.BasicUser; -import com.baeldung.osiv.repository.BasicUserRepository; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.web.servlet.MockMvc; - -import java.util.Arrays; -import java.util.HashSet; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@SpringBootTest -@AutoConfigureMockMvc -@ActiveProfiles("test") -@ContextConfiguration(classes = OsivApplication.class) -class UserControllerIntegrationTest { - - @Autowired - private BasicUserRepository userRepository; - - @Autowired - private MockMvc mockMvc; - - @BeforeEach - void setUp() { - BasicUser user = new BasicUser(); - user.setUsername("root"); - user.setPermissions(new HashSet<>(Arrays.asList("PERM_READ", "PERM_WRITE"))); - - userRepository.save(user); - } - - @Test - void givenTheUserExists_WhenOsivIsEnabled_ThenLazyInitWorkEverywhere() throws Exception { - mockMvc.perform(get("/users/root")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.username").value("root")) - .andExpect(jsonPath("$.permissions", containsInAnyOrder("PERM_READ", "PERM_WRITE"))); - } - - @AfterEach - void flushDb() { - userRepository.deleteAll(); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/tx/ManualTransactionIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/tx/ManualTransactionIntegrationTest.java deleted file mode 100644 index 01551348c9..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/tx/ManualTransactionIntegrationTest.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.baeldung.tx; - -import com.baeldung.tx.model.Payment; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.transaction.support.DefaultTransactionDefinition; -import org.springframework.transaction.support.TransactionCallbackWithoutResult; -import org.springframework.transaction.support.TransactionTemplate; - -import javax.persistence.EntityManager; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.transaction.annotation.Propagation.NOT_SUPPORTED; - -@DataJpaTest -@ActiveProfiles("test") -@Transactional(propagation = NOT_SUPPORTED) -class ManualTransactionIntegrationTest { - - @Autowired - private PlatformTransactionManager transactionManager; - - @Autowired - private EntityManager entityManager; - - private TransactionTemplate transactionTemplate; - - @BeforeEach - void setUp() { - transactionTemplate = new TransactionTemplate(transactionManager); - } - - @AfterEach - void flushDb() { - transactionTemplate.execute(status -> entityManager - .createQuery("delete from Payment") - .executeUpdate()); - } - - @Test - void givenAPayment_WhenNotDuplicate_ThenShouldCommit() { - Long id = transactionTemplate.execute(status -> { - Payment payment = new Payment(); - payment.setAmount(1000L); - payment.setReferenceNumber("Ref-1"); - payment.setState(Payment.State.SUCCESSFUL); - - entityManager.persist(payment); - - return payment.getId(); - }); - - Payment payment = entityManager.find(Payment.class, id); - assertThat(payment).isNotNull(); - } - - @Test - void givenAPayment_WhenMarkAsRollback_ThenShouldRollback() { - transactionTemplate.execute(status -> { - Payment payment = new Payment(); - payment.setAmount(1000L); - payment.setReferenceNumber("Ref-1"); - payment.setState(Payment.State.SUCCESSFUL); - - entityManager.persist(payment); - status.setRollbackOnly(); - - return payment.getId(); - }); - - assertThat(entityManager - .createQuery("select p from Payment p", Payment.class) - .getResultList()).isEmpty(); - } - - @Test - void givenTwoPayments_WhenRefIsDuplicate_ThenShouldRollback() { - try { - transactionTemplate.execute(s -> { - Payment first = new Payment(); - first.setAmount(1000L); - first.setReferenceNumber("Ref-1"); - first.setState(Payment.State.SUCCESSFUL); - - Payment second = new Payment(); - second.setAmount(2000L); - second.setReferenceNumber("Ref-1"); - second.setState(Payment.State.SUCCESSFUL); - - entityManager.persist(first); - entityManager.persist(second); - - return "Ref-1"; - }); - } catch (Exception ignored) { - } - - assertThat(entityManager - .createQuery("select p from Payment p", Payment.class) - .getResultList()).isEmpty(); - } - - @Test - void givenAPayment_WhenNotExpectingAnyResult_ThenShouldCommit() { - transactionTemplate.execute(new TransactionCallbackWithoutResult() { - @Override - protected void doInTransactionWithoutResult(TransactionStatus status) { - Payment payment = new Payment(); - payment.setReferenceNumber("Ref-1"); - payment.setState(Payment.State.SUCCESSFUL); - - entityManager.persist(payment); - } - }); - - assertThat(entityManager - .createQuery("select p from Payment p", Payment.class) - .getResultList()).hasSize(1); - } - - @Test - void givenAPayment_WhenUsingTxManager_ThenShouldCommit() { - DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); - definition.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); - definition.setTimeout(3); - - TransactionStatus status = transactionManager.getTransaction(definition); - try { - Payment payment = new Payment(); - payment.setReferenceNumber("Ref-1"); - payment.setState(Payment.State.SUCCESSFUL); - - entityManager.persist(payment); - transactionManager.commit(status); - } catch (Exception ex) { - transactionManager.rollback(status); - } - - assertThat(entityManager - .createQuery("select p from Payment p", Payment.class) - .getResultList()).hasSize(1); - } - -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/lifecycleevents/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/lifecycleevents/UserRepositoryIntegrationTest.java deleted file mode 100644 index 078f437474..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/lifecycleevents/UserRepositoryIntegrationTest.java +++ /dev/null @@ -1,80 +0,0 @@ -package lifecycleevents; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.lifecycleevents.SpringBootLifecycleEventApplication; -import com.baeldung.lifecycleevents.model.User; -import com.baeldung.lifecycleevents.repository.UserRepository; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringBootLifecycleEventApplication.class) -public class UserRepositoryIntegrationTest { - - @Autowired - private UserRepository userRepository; - - @Before - public void setup() { - User user = new User(); - user.setFirstName("Jane"); - user.setLastName("Smith"); - user.setUserName("jsmith123"); - userRepository.save(user); - } - - @After - public void cleanup() { - userRepository.deleteAll(); - } - - @Test - public void whenNewUserProvided_userIsAdded() { - User user = new User(); - user.setFirstName("John"); - user.setLastName("Doe"); - user.setUserName("jdoe123"); - user = userRepository.save(user); - assertTrue(user.getId() > 0); - } - - @Test - public void whenUserNameProvided_userIsLoaded() { - User user = userRepository.findByUserName("jsmith123"); - assertNotNull(user); - assertEquals("jsmith123", user.getUserName()); - } - - @Test - public void whenExistingUserProvided_userIsUpdated() { - User user = userRepository.findByUserName("jsmith123"); - user.setFirstName("Joe"); - user = userRepository.save(user); - assertEquals("Joe", user.getFirstName()); - } - - @Test - public void whenExistingUserDeleted_userIsDeleted() { - User user = userRepository.findByUserName("jsmith123"); - userRepository.delete(user); - user = userRepository.findByUserName("jsmith123"); - assertNull(user); - } - - @Test - public void whenExistingUserLoaded_fullNameIsAvailable() { - String expectedFullName = "Jane Smith"; - User user = userRepository.findByUserName("jsmith123"); - assertEquals(expectedFullName, user.getFullName()); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/application-test.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/application-test.properties deleted file mode 100644 index f9497c8f37..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/application-test.properties +++ /dev/null @@ -1,2 +0,0 @@ -spring.jpa.hibernate.ddl-auto=update -spring.datasource.url=jdbc:h2:mem:jpa3 \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties deleted file mode 100644 index 04b29de41f..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties +++ /dev/null @@ -1,9 +0,0 @@ -spring.datasource.url=jdbc:postgresql://localhost:5432/quoted-lower-case-strategy -spring.datasource.username=postgres -spring.datasource.password=root - -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedLowerCaseNamingStrategy -#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties deleted file mode 100644 index 6643c12c8a..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties +++ /dev/null @@ -1,9 +0,0 @@ -spring.datasource.url=jdbc:h2:mem:quoted-lower-case-strategy -spring.datasource.username=sa -spring.datasource.password= - -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedLowerCaseNamingStrategy -#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties deleted file mode 100644 index 36898d5b4f..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties +++ /dev/null @@ -1,9 +0,0 @@ -spring.datasource.url=jdbc:postgresql://localhost:5432/quoted-upper-case-strategy -spring.datasource.username=postgres -spring.datasource.password=root - -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedUpperCaseNamingStrategy -#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties deleted file mode 100644 index 6d56d58749..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties +++ /dev/null @@ -1,9 +0,0 @@ -spring.datasource.url=jdbc:h2:mem:quoted-upper-case-strategy -spring.datasource.username=sa -spring.datasource.password= - -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedUpperCaseNamingStrategy -#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties deleted file mode 100644 index 706b12b1b6..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties +++ /dev/null @@ -1,9 +0,0 @@ -spring.datasource.url=jdbc:postgresql://localhost:5432/spring-strategy -spring.datasource.username=postgres -spring.datasource.password=root - -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy -#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=default-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties deleted file mode 100644 index c9a0c6f24c..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties +++ /dev/null @@ -1,9 +0,0 @@ -spring.datasource.url=jdbc:h2:mem:spring-strategy -spring.datasource.username=sa -spring.datasource.password= - -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy -#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=default-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties deleted file mode 100644 index b22472bd8f..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties +++ /dev/null @@ -1,9 +0,0 @@ -spring.datasource.url=jdbc:postgresql://localhost:5432/unquoted-lower-case-strategy -spring.datasource.username=postgres -spring.datasource.password=root - -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedLowerCaseNamingStrategy -#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties deleted file mode 100644 index 8083515b4b..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties +++ /dev/null @@ -1,9 +0,0 @@ -spring.datasource.url=jdbc:h2:mem:unquoted-lower-case-strategy -spring.datasource.username=sa -spring.datasource.password= - -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedLowerCaseNamingStrategy -#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties deleted file mode 100644 index da03a0d7b5..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties +++ /dev/null @@ -1,9 +0,0 @@ -spring.datasource.url=jdbc:postgresql://localhost:5432/unquoted-upper-case-strategy -spring.datasource.username=postgres -spring.datasource.password=root - -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedUpperCaseNamingStrategy -#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties deleted file mode 100644 index d1b63e008c..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties +++ /dev/null @@ -1,9 +0,0 @@ -spring.datasource.url=jdbc:h2:mem:unquoted-upper-case-strategy -spring.datasource.username=sa -spring.datasource.password= - -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedUpperCaseNamingStrategy -#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/test-movie-cleanup.sql b/persistence-modules/spring-data-jpa-4/src/test/resources/test-movie-cleanup.sql deleted file mode 100644 index 90aa15307c..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/test-movie-cleanup.sql +++ /dev/null @@ -1 +0,0 @@ -DELETE FROM Movie; \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/test-movie-data.sql b/persistence-modules/spring-data-jpa-4/src/test/resources/test-movie-data.sql deleted file mode 100644 index 37f8e4fe64..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/test-movie-data.sql +++ /dev/null @@ -1,7 +0,0 @@ -INSERT INTO movie(id, title, director, rating, duration) VALUES(1, 'Godzilla: King of the Monsters', ' Michael Dougherty', 'PG-13', 132); -INSERT INTO movie(id, title, director, rating, duration) VALUES(2, 'Avengers: Endgame', 'Anthony Russo', 'PG-13', 181); -INSERT INTO movie(id, title, director, rating, duration) VALUES(3, 'Captain Marvel', 'Anna Boden', 'PG-13', 123); -INSERT INTO movie(id, title, director, rating, duration) VALUES(4, 'Dumbo', 'Tim Burton', 'PG', 112); -INSERT INTO movie(id, title, director, rating, duration) VALUES(5, 'Booksmart', 'Olivia Wilde', 'R', 102); -INSERT INTO movie(id, title, director, rating, duration) VALUES(6, 'Aladdin', 'Guy Ritchie', 'PG', 128); -INSERT INTO movie(id, title, director, rating, duration) VALUES(7, 'The Sun Is Also a Star', 'Ry Russo-Young', 'PG-13', 100); diff --git a/persistence-modules/spring-data-jpa-5/README.md b/persistence-modules/spring-data-jpa-5/README.md deleted file mode 100644 index 0b78ced66c..0000000000 --- a/persistence-modules/spring-data-jpa-5/README.md +++ /dev/null @@ -1,15 +0,0 @@ -### Relevant Articles: - -- [Spring JPA @Embedded and @EmbeddedId](https://www.baeldung.com/spring-jpa-embedded-method-parameters) -- [Generate Database Schema with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-generate-db-schema) -- [Partial Data Update with Spring Data](https://www.baeldung.com/spring-data-partial-update) - -### Eclipse Config -After importing the project into Eclipse, you may see the following error: -"No persistence xml file found in project" - -This can be ignored: -- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" -Or: -- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator - diff --git a/persistence-modules/spring-data-jpa-5/pom.xml b/persistence-modules/spring-data-jpa-5/pom.xml deleted file mode 100644 index db58a16062..0000000000 --- a/persistence-modules/spring-data-jpa-5/pom.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - - 4.0.0 - spring-data-jpa-5 - spring-data-jpa-5 - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - org.springframework.boot - spring-boot-starter-data-jdbc - - - - org.springframework.boot - spring-boot-starter-cache - - - - com.h2database - h2 - - - - org.mapstruct - mapstruct-jdk8 - ${mapstruct.version} - provided - - - - - - src/main/java - - - maven-compiler-plugin - 3.8.1 - - 1.8 - 1.8 - - - org.mapstruct - mapstruct-processor - 1.3.1.Final - - - - - - - - - 2.1.9.RELEASE - com.baeldung.springdatageode.app.ClientCacheApp - 1.1.1.RELEASE - 2.1.9.RELEASE - 1.3.1.Final - - - diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/BookApplication.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/BookApplication.java deleted file mode 100644 index 52f06058aa..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/BookApplication.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.composite; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class BookApplication { - - public static void main(String[] args) { - SpringApplication.run(BookApplication.class); - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/entity/Book.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/entity/Book.java deleted file mode 100644 index e4f1727654..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/entity/Book.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.composite.entity; - -import javax.persistence.EmbeddedId; -import javax.persistence.Entity; - -@Entity -public class Book { - - @EmbeddedId - private BookId id; - private String genre; - private Integer price; - - public Book() { - } - - public Book(String author, String name, String genre, Integer price) { - BookId id = new BookId(author, name); - this.id = id; - this.genre = genre; - this.price = price; - } - - public BookId getId() { - return id; - } - - public void setId(BookId id) { - this.id = id; - } - - public String getGenre() { - return genre; - } - - public void setGenre(String genre) { - this.genre = genre; - } - - public Integer getPrice() { - return price; - } - - public void setPrice(Integer price) { - this.price = price; - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/entity/BookId.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/entity/BookId.java deleted file mode 100644 index 1524452412..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/entity/BookId.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.composite.entity; - -import javax.persistence.Embeddable; -import java.io.Serializable; -import java.util.Objects; - -@Embeddable -public class BookId implements Serializable { - - private String author; - private String name; - - public BookId() { - } - - public BookId(String author, String name) { - this.author = author; - this.name = name; - } - - public String getAuthor() { - return author; - } - - public void setAuthor(String author) { - this.author = author; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - BookId bookId = (BookId) o; - return Objects.equals(author, bookId.author) && Objects.equals(name, bookId.name); - } - - @Override - public int hashCode() { - return Objects.hash(author, name); - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/repository/BookRepository.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/repository/BookRepository.java deleted file mode 100644 index d5993eaf79..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/repository/BookRepository.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.composite.repository; - -import com.baeldung.composite.entity.Book; -import com.baeldung.composite.entity.BookId; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.List; - -@Repository -public interface BookRepository extends JpaRepository { - - List findByIdName(String name); - - List findByIdAuthor(String author); - - List findByGenre(String genre); -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/PartialUpdateApplication.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/PartialUpdateApplication.java deleted file mode 100644 index a750fcadf7..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/PartialUpdateApplication.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.partialupdate; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class PartialUpdateApplication { - - public static void main(String[] args) { - SpringApplication.run(PartialUpdateApplication.class, args); - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/ContactPhone.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/ContactPhone.java deleted file mode 100644 index 352e361bd9..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/ContactPhone.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.partialupdate.model; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class ContactPhone { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - public long id; - @Column(nullable=false) - public long customerId; - public String phone; - - @Override - public String toString() { - return phone; - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/Customer.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/Customer.java deleted file mode 100644 index b19d0b7952..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/Customer.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.partialupdate.model; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class Customer { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - public long id; - public String name; - public String phone; - //... - public String phone99; - - @Override public String toString() { - return String.format("Customer %s, Phone: %s", - this.name, this.phone); - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/CustomerDto.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/CustomerDto.java deleted file mode 100644 index 0ecf206d9a..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/CustomerDto.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.partialupdate.model; - -public class CustomerDto { - private long id; - public String name; - public String phone; - //... - private String phone99; - - public CustomerDto(long id) { - this.id = id; - } - - public CustomerDto(Customer c) { - this.id = c.id; - this.name = c.name; - this.phone = c.phone; - } - - public long getId() { - return this.id; - } - - public Customer convertToEntity() { - Customer c = new Customer(); - c.id = id; - c.name = name; - c.phone = phone; - return c; - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/CustomerStructured.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/CustomerStructured.java deleted file mode 100644 index dd053a963d..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/CustomerStructured.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.partialupdate.model; - -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; - -@Entity -public class CustomerStructured { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - public long id; - public String name; - @OneToMany(fetch = FetchType.EAGER, targetEntity = ContactPhone.class, mappedBy = "customerId") - public List contactPhones; - - @Override public String toString() { - return String.format("Customer %s, Phone: %s", - this.name, this.contactPhones.stream() - .map(e -> e.toString()).reduce("", String::concat)); - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/ContactPhoneRepository.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/ContactPhoneRepository.java deleted file mode 100644 index 4668181e05..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/ContactPhoneRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.partialupdate.repository; - -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; - -import com.baeldung.partialupdate.model.ContactPhone; - -@Repository -public interface ContactPhoneRepository extends CrudRepository { - ContactPhone findById(long id); - ContactPhone findByCustomerId(long id); -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/CustomerRepository.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/CustomerRepository.java deleted file mode 100644 index 43e61df8ab..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/CustomerRepository.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.partialupdate.repository; - -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.CrudRepository; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -import com.baeldung.partialupdate.model.Customer; - -@Repository -public interface CustomerRepository extends CrudRepository { - Customer findById(long id); - - @Modifying - @Query("update Customer u set u.phone = :phone where u.id = :id") - void updatePhone(@Param(value = "id") long id, @Param(value = "phone") String phone); -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/CustomerStructuredRepository.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/CustomerStructuredRepository.java deleted file mode 100644 index 0f9fd1e92e..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/CustomerStructuredRepository.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.partialupdate.repository; - -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; - -import com.baeldung.partialupdate.model.CustomerStructured; - -@Repository -public interface CustomerStructuredRepository extends CrudRepository { - CustomerStructured findById(long id); -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/service/CustomerService.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/service/CustomerService.java deleted file mode 100644 index 9da97a7775..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/service/CustomerService.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.baeldung.partialupdate.service; - -import javax.transaction.Transactional; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.baeldung.partialupdate.model.ContactPhone; -import com.baeldung.partialupdate.model.Customer; -import com.baeldung.partialupdate.model.CustomerDto; -import com.baeldung.partialupdate.model.CustomerStructured; -import com.baeldung.partialupdate.repository.ContactPhoneRepository; -import com.baeldung.partialupdate.repository.CustomerRepository; -import com.baeldung.partialupdate.repository.CustomerStructuredRepository; -import com.baeldung.partialupdate.util.CustomerMapper; - -@Service -@Transactional -public class CustomerService { - - @Autowired - CustomerRepository repo; - @Autowired - CustomerStructuredRepository repo2; - @Autowired - ContactPhoneRepository repo3; - @Autowired - CustomerMapper mapper; - - public Customer getCustomer(long id) { - return repo.findById(id); - } - - public void updateCustomerWithCustomQuery(long id, String phone) { - repo.updatePhone(id, phone); - } - - public Customer addCustomer(String name) { - Customer myCustomer = new Customer(); - myCustomer.name = name; - repo.save(myCustomer); - return myCustomer; - } - - public Customer updateCustomer(long id, String phone) { - Customer myCustomer = repo.findById(id); - myCustomer.phone = phone; - repo.save(myCustomer); - return myCustomer; - } - - public Customer addCustomer(CustomerDto dto) { - Customer myCustomer = new Customer(); - mapper.updateCustomerFromDto(dto, myCustomer); - repo.save(myCustomer); - return myCustomer; - } - - public Customer updateCustomer(CustomerDto dto) { - Customer myCustomer = repo.findById(dto.getId()); - mapper.updateCustomerFromDto(dto, myCustomer); - repo.save(myCustomer); - return myCustomer; - } - - public CustomerStructured addCustomerStructured(String name) { - CustomerStructured myCustomer = new CustomerStructured(); - myCustomer.name = name; - repo2.save(myCustomer); - return myCustomer; - } - - public void addCustomerPhone(long customerId, String phone) { - ContactPhone myPhone = new ContactPhone(); - myPhone.phone = phone; - myPhone.customerId = customerId; - repo3.save(myPhone); - } - - public CustomerStructured updateCustomerStructured(long id, String name) { - CustomerStructured myCustomer = repo2.findById(id); - myCustomer.name = name; - repo2.save(myCustomer); - return myCustomer; - } - -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/util/CustomerMapper.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/util/CustomerMapper.java deleted file mode 100644 index 8a666e3e6c..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/util/CustomerMapper.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.partialupdate.util; - -import org.mapstruct.BeanMapping; -import org.mapstruct.Mapper; -import org.mapstruct.MappingTarget; -import org.mapstruct.NullValuePropertyMappingStrategy; - -import com.baeldung.partialupdate.model.Customer; -import com.baeldung.partialupdate.model.CustomerDto; - -@Mapper(componentModel = "spring") -public interface CustomerMapper { - @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) - void updateCustomerFromDto(CustomerDto dto, @MappingTarget Customer entity); -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/AccountApplication.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/AccountApplication.java deleted file mode 100644 index 547992a6c1..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/AccountApplication.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.schemageneration; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class AccountApplication { - - public static void main(String[] args) { - SpringApplication.run(AccountApplication.class, args); - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/HibernateUtil.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/HibernateUtil.java deleted file mode 100644 index 7d69d65705..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/HibernateUtil.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.schemageneration; - -import com.baeldung.schemageneration.model.Account; -import com.baeldung.schemageneration.model.AccountSetting; -import org.hibernate.boot.Metadata; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.Environment; -import org.hibernate.tool.hbm2ddl.SchemaExport; -import org.hibernate.tool.schema.TargetType; - -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Map; - -public class HibernateUtil { - - /** - * Generates database create commands for the specified entities using Hibernate native API, SchemaExport. - * Creation commands are exported into the create.sql file. - */ - public static void generateSchema() { - Map settings = new HashMap<>(); - settings.put(Environment.URL, "jdbc:h2:mem:schema"); - - StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(settings).build(); - - MetadataSources metadataSources = new MetadataSources(serviceRegistry); - metadataSources.addAnnotatedClass(Account.class); - metadataSources.addAnnotatedClass(AccountSetting.class); - Metadata metadata = metadataSources.buildMetadata(); - - SchemaExport schemaExport = new SchemaExport(); - schemaExport.setFormat(true); - schemaExport.setOutputFile("create.sql"); - schemaExport.createOnly(EnumSet.of(TargetType.SCRIPT), metadata); - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/model/Account.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/model/Account.java deleted file mode 100644 index 785e275e26..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/model/Account.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.baeldung.schemageneration.model; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import javax.persistence.Table; -import java.util.ArrayList; -import java.util.List; - -@Entity -@Table(name = "accounts") -public class Account { - - @Id - @GeneratedValue - private Long id; - - @Column(nullable = false, length = 100) - private String name; - - @Column(name = "email_address") - private String emailAddress; - - @OneToMany(mappedBy = "account", cascade = CascadeType.ALL) - private List accountSettings = new ArrayList<>(); - - public Account() { - } - - public Account(String name, String emailAddress) { - this.name = name; - this.emailAddress = emailAddress; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getEmailAddress() { - return emailAddress; - } - - public void setEmailAddress(String emailAddress) { - this.emailAddress = emailAddress; - } - - public List getAccountSettings() { - return accountSettings; - } - - public void setAccountSettings(List accountSettings) { - this.accountSettings = accountSettings; - } - - public void addAccountSetting(AccountSetting setting) { - this.accountSettings.add(setting); - setting.setAccount(this); - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/model/AccountSetting.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/model/AccountSetting.java deleted file mode 100644 index 61e43894a8..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/model/AccountSetting.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.baeldung.schemageneration.model; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; - -@Entity -@Table(name = "account_settings") -public class AccountSetting { - - @Id - @GeneratedValue - private Long id; - - @Column(name = "name", nullable = false) - private String settingName; - - @Column(name = "value", nullable = false) - private String settingValue; - - @ManyToOne() - @JoinColumn(name ="account_id", nullable = false) - private Account account; - - public AccountSetting() { - } - - public AccountSetting(String settingName, String settingValue) { - this.settingName = settingName; - this.settingValue = settingValue; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getSettingName() { - return settingName; - } - - public void setSettingName(String settingName) { - this.settingName = settingName; - } - - public String getSettingValue() { - return settingValue; - } - - public void setSettingValue(String settingValue) { - this.settingValue = settingValue; - } - - public Account getAccount() { - return account; - } - - public void setAccount(Account account) { - this.account = account; - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/repository/AccountRepository.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/repository/AccountRepository.java deleted file mode 100644 index dc57ffe6d3..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/repository/AccountRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.schemageneration.repository; - -import com.baeldung.schemageneration.model.Account; -import org.springframework.data.repository.CrudRepository; - -public interface AccountRepository extends CrudRepository { - Account findByName(String name); -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/repository/AccountSettingRepository.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/repository/AccountSettingRepository.java deleted file mode 100644 index c2b8ff7398..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/repository/AccountSettingRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.schemageneration.repository; - -import com.baeldung.schemageneration.model.AccountSetting; -import org.springframework.data.repository.CrudRepository; - -public interface AccountSettingRepository extends CrudRepository { - AccountSetting findByAccountId(Long accountId); -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-5/src/main/resources/application.properties deleted file mode 100644 index f55ad438ff..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/resources/application.properties +++ /dev/null @@ -1,13 +0,0 @@ - -spring.datasource.url=jdbc:h2:mem:baeldung - -# JPA-Schema-Generation -# Use below configuration to generate database schema create commands based on the entity models -# and export them into the create.sql file -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=create.sql -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-source=metadata -#spring.jpa.properties.hibernate.format_sql=true - -spring.jpa.show-sql=true - diff --git a/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/composite/repository/BookRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/composite/repository/BookRepositoryIntegrationTest.java deleted file mode 100644 index 9d25acbd96..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/composite/repository/BookRepositoryIntegrationTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.baeldung.composite.repository; - -import com.baeldung.composite.BookApplication; -import com.baeldung.composite.entity.Book; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = BookApplication.class) -public class BookRepositoryIntegrationTest { - - public static final String JAVA_101 = "Java101"; - public static final String JANE = "Jane"; - public static final String TECH = "Tech"; - @Autowired - BookRepository repository; - - @Before - public void setUp() { - Book book1 = new Book("John", JAVA_101, TECH, 20); - Book book2 = new Book(JANE, JAVA_101, "Arch", 25); - Book book3 = new Book(JANE, "Scala101", TECH, 23); - - repository.saveAll(Arrays.asList(book1, book2, book3)); - } - - @After - public void tearDown() { - repository.deleteAll(); - } - - @Test - public void testFindByName() { - List books = repository.findByIdName(JAVA_101); - - assertEquals(2, books.size()); - } - - @Test - public void testFindByAuthor() { - List books = repository.findByIdAuthor(JANE); - - assertEquals(2, books.size()); - } - - @Test - public void testFindByGenre() { - List books = repository.findByGenre(TECH); - - assertEquals(2, books.size()); - } -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/partialupdate/PartialUpdateUnitTest.java b/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/partialupdate/PartialUpdateUnitTest.java deleted file mode 100644 index 874e18c4ad..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/partialupdate/PartialUpdateUnitTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.baeldung.partialupdate; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.partialupdate.model.Customer; -import com.baeldung.partialupdate.model.CustomerDto; -import com.baeldung.partialupdate.model.CustomerStructured; -import com.baeldung.partialupdate.service.CustomerService; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = PartialUpdateApplication.class) -public class PartialUpdateUnitTest { - - @Autowired - CustomerService service; - - @Test - public void givenCustomer_whenUpdate_thenSuccess() { - Customer myCustomer = service.addCustomer("John"); - myCustomer = service.updateCustomer(myCustomer.id, "+00"); - assertEquals("+00", myCustomer.phone); - } - - @Test - public void givenCustomer_whenUpdateWithQuery_thenSuccess() { - Customer myCustomer = service.addCustomer("John"); - service.updateCustomerWithCustomQuery(myCustomer.id, "+88"); - myCustomer = service.getCustomer(myCustomer.id); - assertEquals("+88", myCustomer.phone); - } - - @Test - public void givenCustomerDto_whenUpdateWithMapper_thenSuccess() { - CustomerDto dto = new CustomerDto(new Customer()); - dto.name = "Johnny"; - Customer entity = service.addCustomer(dto); - - CustomerDto dto2 = new CustomerDto(entity.id); - dto2.phone = "+44"; - entity = service.updateCustomer(dto2); - - assertEquals("Johnny", entity.name); - } - - @Test - public void givenCustomerStructured_whenUpdateCustomerPhone_thenSuccess() { - CustomerStructured myCustomer = service.addCustomerStructured("John"); - assertEquals(null, myCustomer.contactPhones); - - service.addCustomerPhone(myCustomer.id, "+44"); - myCustomer = service.updateCustomerStructured(myCustomer.id, "Mr. John"); - - assertNotEquals(null, myCustomer.contactPhones); - assertEquals(1, myCustomer.contactPhones.size()); - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/schemageneration/AccountRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/schemageneration/AccountRepositoryIntegrationTest.java deleted file mode 100644 index 86a7671fe4..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/schemageneration/AccountRepositoryIntegrationTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.baeldung.schemageneration; - -import com.baeldung.schemageneration.model.Account; -import com.baeldung.schemageneration.model.AccountSetting; -import com.baeldung.schemageneration.repository.AccountRepository; -import com.baeldung.schemageneration.repository.AccountSettingRepository; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = AccountApplication.class) -public class AccountRepositoryIntegrationTest { - - private static final String USER_NAME = "Eduard"; - private static final String USER_EMAIL_ADDRESS = "eduard@gmx.com"; - private static final String ACCOUNT_SETTING_NAME = "Timezone"; - private static final String ACCOUNT_SETTING_VALUE = "UTC+02"; - - @Autowired - private AccountRepository accountRepository; - - @Autowired - private AccountSettingRepository accountSettingRepository; - - @After - public void tearDown() { - accountRepository.deleteAll(); - } - - @Test - public void givenNewAccount_whenSave_thenSuccess() { - Account account = new Account(USER_NAME, USER_EMAIL_ADDRESS); - accountRepository.save(account); - - assertEquals(1, accountRepository.count()); - } - - @Test - public void givenSavedAccount_whenFindByName_thenFound() { - Account account = new Account(USER_NAME, USER_EMAIL_ADDRESS); - accountRepository.save(account); - - Account accountFound = accountRepository.findByName(USER_NAME); - - assertNotNull(accountFound); - assertEquals(USER_NAME, accountFound.getName()); - assertEquals(USER_EMAIL_ADDRESS, accountFound.getEmailAddress()); - } - - @Test - public void givenSavedAccount_whenAccountSettingIsAdded_thenPersisted() { - Account account = new Account(USER_NAME, USER_EMAIL_ADDRESS); - account.addAccountSetting(new AccountSetting(ACCOUNT_SETTING_NAME, ACCOUNT_SETTING_VALUE)); - accountRepository.save(account); - - Account accountFound = accountRepository.findByName(USER_NAME); - assertNotNull(accountFound); - AccountSetting accountSetting = accountSettingRepository.findByAccountId(accountFound.getId()); - - assertNotNull(accountSetting); - assertEquals(ACCOUNT_SETTING_NAME, accountSetting.getSettingName()); - assertEquals(ACCOUNT_SETTING_VALUE, accountSetting.getSettingValue()); - } - -} diff --git a/persistence-modules/spring-data-jpa-5/src/test/resources/application-test.properties b/persistence-modules/spring-data-jpa-5/src/test/resources/application-test.properties deleted file mode 100644 index e3d39fe1e2..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/test/resources/application-test.properties +++ /dev/null @@ -1,3 +0,0 @@ -spring.jpa.hibernate.ddl-auto=update -spring.datasource.url=jdbc:h2:mem:baeldung - diff --git a/persistence-modules/spring-data-jpa/README.md b/persistence-modules/spring-data-jpa/README.md deleted file mode 100644 index 1c43edf42b..0000000000 --- a/persistence-modules/spring-data-jpa/README.md +++ /dev/null @@ -1,25 +0,0 @@ -========= - -## Spring Data JPA Example Project - -### Relevant Articles: -- [Spring JPA – Multiple Databases](https://www.baeldung.com/spring-data-jpa-multiple-databases) -- [Spring Data JPA – Adding a Method in All Repositories](https://www.baeldung.com/spring-data-jpa-method-in-all-repositories) -- [An Advanced Tagging Implementation with JPA](https://www.baeldung.com/jpa-tagging-advanced) -- [Spring Data Annotations](https://www.baeldung.com/spring-data-annotations) -- [Spring Data Java 8 Support](https://www.baeldung.com/spring-data-java-8) -- [A Simple Tagging Implementation with JPA](https://www.baeldung.com/jpa-tagging) -- [Spring Data Composable Repositories](https://www.baeldung.com/spring-data-composable-repositories) -- [Query Entities by Dates and Times with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-query-by-date) -- [DDD Aggregates and @DomainEvents](https://www.baeldung.com/spring-data-ddd) -- [Spring Data – CrudRepository save() Method](https://www.baeldung.com/spring-data-crud-repository-save) - -### Eclipse Config -After importing the project into Eclipse, you may see the following error: -"No persistence xml file found in project" - -This can be ignored: -- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" -Or: -- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator - diff --git a/persistence-modules/spring-data-jpa/pom.xml b/persistence-modules/spring-data-jpa/pom.xml deleted file mode 100644 index ddd7e17dcd..0000000000 --- a/persistence-modules/spring-data-jpa/pom.xml +++ /dev/null @@ -1,77 +0,0 @@ - - - 4.0.0 - spring-data-jpa - spring-data-jpa - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.hibernate - hibernate-ehcache - - - org.hibernate - hibernate-envers - - - - com.h2database - h2 - - - - - org.testcontainers - postgresql - ${testcontainers.postgresql.version} - test - - - - org.postgresql - postgresql - - - - - org.springframework.security - spring-security-test - test - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-test - test - - - - com.google.guava - guava - ${guava.version} - - - - - com.baeldung.boot.Application - 1.10.6 - 42.2.5 - 21.0 - - - \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/Application.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/Application.java deleted file mode 100644 index c66921a3ca..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/Application.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.boot; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; - -import com.baeldung.boot.daos.impl.ExtendedRepositoryImpl; - -@SpringBootApplication -@EnableJpaRepositories(repositoryBaseClass = ExtendedRepositoryImpl.class) -public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/config/PersistenceConfiguration.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/config/PersistenceConfiguration.java deleted file mode 100644 index 76d5887030..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/config/PersistenceConfiguration.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.boot.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.data.jpa.repository.config.EnableJpaAuditing; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -import com.baeldung.boot.services.IBarService; -import com.baeldung.boot.services.impl.BarSpringDataJpaService; - -@Configuration -@Profile("!tc") -@EnableTransactionManagement -@EnableJpaAuditing -public class PersistenceConfiguration { - - @Bean - public IBarService barSpringDataJpaService() { - return new BarSpringDataJpaService(); - } - -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ArticleRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ArticleRepository.java deleted file mode 100644 index 73397ad42e..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ArticleRepository.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.boot.daos; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; - -import com.baeldung.boot.domain.Article; - -import java.util.Date; -import java.util.List; - -public interface ArticleRepository extends JpaRepository { - - List
findAllByPublicationDate(Date publicationDate); - - List
findAllByPublicationTimeBetween(Date publicationTimeStart, - Date publicationTimeEnd); - - @Query("select a from Article a where a.creationDateTime <= :creationDateTime") - List
findAllWithCreationDateTimeBefore( - @Param("creationDateTime") Date creationDateTime); - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/CustomItemRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/CustomItemRepository.java deleted file mode 100644 index 0aebe34921..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/CustomItemRepository.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.boot.daos; - -import org.springframework.stereotype.Repository; - -import com.baeldung.boot.domain.Item; - -@Repository -public interface CustomItemRepository { - - void deleteCustom(Item entity); - - Item findItemById(Long id); - - void findThenDelete(Long id); - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/CustomItemTypeRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/CustomItemTypeRepository.java deleted file mode 100644 index 832d61408c..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/CustomItemTypeRepository.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.boot.daos; - -import org.springframework.stereotype.Repository; - -import com.baeldung.boot.domain.ItemType; - -@Repository -public interface CustomItemTypeRepository { - - void deleteCustom(ItemType entity); - - void findThenDelete(Long id); -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ExtendedRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ExtendedRepository.java deleted file mode 100644 index adb2af4320..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ExtendedRepository.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.boot.daos; - -import java.io.Serializable; -import java.util.List; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.repository.NoRepositoryBean; - -@NoRepositoryBean -public interface ExtendedRepository extends JpaRepository { - - List findByAttributeContainsText(String attributeName, String text); - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ExtendedStudentRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ExtendedStudentRepository.java deleted file mode 100644 index c9b0192536..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ExtendedStudentRepository.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.baeldung.boot.daos; - -import com.baeldung.boot.domain.Student; - -public interface ExtendedStudentRepository extends ExtendedRepository { -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/IBarCrudRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/IBarCrudRepository.java deleted file mode 100644 index 921fabe3fb..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/IBarCrudRepository.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.boot.daos; - -import org.springframework.data.repository.CrudRepository; - -import com.baeldung.boot.domain.Bar; - -import java.io.Serializable; - -public interface IBarCrudRepository extends CrudRepository { - // -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/IFooDao.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/IFooDao.java deleted file mode 100644 index d537772076..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/IFooDao.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.boot.daos; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; - -import com.baeldung.boot.domain.Foo; - -public interface IFooDao extends JpaRepository { - - @Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)") - Foo retrieveByName(@Param("name") String name); -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/InventoryRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/InventoryRepository.java deleted file mode 100644 index 606f3993d5..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/InventoryRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.boot.daos; - -import org.springframework.data.repository.CrudRepository; - -import com.baeldung.boot.domain.MerchandiseEntity; - -public interface InventoryRepository extends CrudRepository { -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ItemTypeRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ItemTypeRepository.java deleted file mode 100644 index 413c09e968..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ItemTypeRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.baeldung.boot.daos; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import com.baeldung.boot.domain.ItemType; - -@Repository -public interface ItemTypeRepository extends JpaRepository, CustomItemTypeRepository, CustomItemRepository { -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/LocationRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/LocationRepository.java deleted file mode 100644 index 697ce295d0..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/LocationRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.baeldung.boot.daos; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import com.baeldung.boot.domain.Location; - -@Repository -public interface LocationRepository extends JpaRepository { -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ReadOnlyLocationRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ReadOnlyLocationRepository.java deleted file mode 100644 index 3a2ea3cda5..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ReadOnlyLocationRepository.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.boot.daos; - -import java.util.Optional; - -import org.springframework.data.repository.Repository; - -import com.baeldung.boot.domain.Location; - -@org.springframework.stereotype.Repository -public interface ReadOnlyLocationRepository extends Repository { - - Optional findById(Long id); - - Location save(Location location); -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/StoreRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/StoreRepository.java deleted file mode 100644 index ae13f75f66..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/StoreRepository.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.boot.daos; - -import java.util.List; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import com.baeldung.boot.domain.Store; - -@Repository -public interface StoreRepository extends JpaRepository { - List findStoreByLocationId(Long locationId); -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/CustomItemRepositoryImpl.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/CustomItemRepositoryImpl.java deleted file mode 100644 index 820a2cdd41..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/CustomItemRepositoryImpl.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.boot.daos.impl; - -import javax.persistence.EntityManager; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Repository; - -import com.baeldung.boot.daos.CustomItemRepository; -import com.baeldung.boot.domain.Item; - -@Repository -public class CustomItemRepositoryImpl implements CustomItemRepository { - - @Autowired - private EntityManager entityManager; - - @Override - public void deleteCustom(Item item) { - entityManager.remove(item); - } - - @Override - public Item findItemById(Long id) { - return entityManager.find(Item.class, id); - } - - @Override - public void findThenDelete(Long id) { - final Item item = entityManager.find(Item.class, id); - entityManager.remove(item); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/CustomItemTypeRepositoryImpl.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/CustomItemTypeRepositoryImpl.java deleted file mode 100644 index e057f36b26..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/CustomItemTypeRepositoryImpl.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.boot.daos.impl; - -import javax.persistence.EntityManager; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Repository; - -import com.baeldung.boot.daos.CustomItemTypeRepository; -import com.baeldung.boot.domain.ItemType; - -@Repository -public class CustomItemTypeRepositoryImpl implements CustomItemTypeRepository { - - @Autowired - private EntityManager entityManager; - - @Override - public void deleteCustom(ItemType itemType) { - entityManager.remove(itemType); - } - - @Override - public void findThenDelete(Long id) { - ItemType itemTypeToDelete = entityManager.find(ItemType.class, id); - entityManager.remove(itemTypeToDelete); - } -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/ExtendedRepositoryImpl.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/ExtendedRepositoryImpl.java deleted file mode 100644 index fbe6695844..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/ExtendedRepositoryImpl.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.boot.daos.impl; - -import java.io.Serializable; -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; -import javax.transaction.Transactional; - -import org.springframework.data.jpa.repository.support.JpaEntityInformation; -import org.springframework.data.jpa.repository.support.SimpleJpaRepository; - -import com.baeldung.boot.daos.ExtendedRepository; - -public class ExtendedRepositoryImpl extends SimpleJpaRepository implements ExtendedRepository { - - private EntityManager entityManager; - - public ExtendedRepositoryImpl(JpaEntityInformation entityInformation, EntityManager entityManager) { - super(entityInformation, entityManager); - this.entityManager = entityManager; - } - - @Transactional - public List findByAttributeContainsText(String attributeName, String text) { - CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - CriteriaQuery query = builder.createQuery(getDomainClass()); - Root root = query.from(getDomainClass()); - query.select(root).where(builder.like(root. get(attributeName), "%" + text + "%")); - TypedQuery q = entityManager.createQuery(query); - return q.getResultList(); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/PossessionRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/PossessionRepository.java deleted file mode 100644 index e102754c18..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/PossessionRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.boot.daos.user; - -import org.springframework.data.jpa.repository.JpaRepository; - -import com.baeldung.boot.domain.Possession; - -public interface PossessionRepository extends JpaRepository { - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepository.java deleted file mode 100644 index 53f692ff28..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepository.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.baeldung.boot.daos.user; - -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; - -import com.baeldung.boot.domain.User; - -import java.time.LocalDate; -import java.util.Collection; -import java.util.List; -import java.util.stream.Stream; - -public interface UserRepository extends JpaRepository , UserRepositoryCustom{ - - Stream findAllByName(String name); - - @Query("SELECT u FROM User u WHERE u.status = 1") - Collection findAllActiveUsers(); - - @Query("select u from User u where u.email like '%@gmail.com'") - List findUsersWithGmailAddress(); - - @Query(value = "SELECT * FROM Users u WHERE u.status = 1", nativeQuery = true) - Collection findAllActiveUsersNative(); - - @Query("SELECT u FROM User u WHERE u.status = ?1") - User findUserByStatus(Integer status); - - @Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true) - User findUserByStatusNative(Integer status); - - @Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2") - User findUserByStatusAndName(Integer status, String name); - - @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") - User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name); - - @Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true) - User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name); - - @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") - User findUserByUserStatusAndUserName(@Param("status") Integer userStatus, @Param("name") String userName); - - @Query("SELECT u FROM User u WHERE u.name like ?1%") - User findUserByNameLike(String name); - - @Query("SELECT u FROM User u WHERE u.name like :name%") - User findUserByNameLikeNamedParam(@Param("name") String name); - - @Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true) - User findUserByNameLikeNative(String name); - - @Query(value = "SELECT u FROM User u") - List findAllUsers(Sort sort); - - @Query(value = "SELECT u FROM User u ORDER BY id") - Page findAllUsersWithPagination(Pageable pageable); - - @Query(value = "SELECT * FROM Users ORDER BY id", countQuery = "SELECT count(*) FROM Users", nativeQuery = true) - Page findAllUsersWithPaginationNative(Pageable pageable); - - @Modifying - @Query("update User u set u.status = :status where u.name = :name") - int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name); - - @Modifying - @Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true) - int updateUserSetStatusForNameNative(Integer status, String name); - - @Query(value = "INSERT INTO Users (name, age, email, status, active) VALUES (:name, :age, :email, :status, :active)", nativeQuery = true) - @Modifying - void insertUser(@Param("name") String name, @Param("age") Integer age, @Param("email") String email, @Param("status") Integer status, @Param("active") boolean active); - - @Modifying - @Query(value = "UPDATE Users u SET status = ? WHERE u.name = ?", nativeQuery = true) - int updateUserSetStatusForNameNativePostgres(Integer status, String name); - - @Query(value = "SELECT u FROM User u WHERE u.name IN :names") - List findUserByNameList(@Param("names") Collection names); - - void deleteAllByCreationDateAfter(LocalDate date); - - @Modifying(clearAutomatically = true, flushAutomatically = true) - @Query("update User u set u.active = false where u.lastLoginDate < :date") - void deactivateUsersNotLoggedInSince(@Param("date") LocalDate date); - - @Modifying(clearAutomatically = true, flushAutomatically = true) - @Query("delete User u where u.active = false") - int deleteDeactivatedUsers(); - - @Modifying(clearAutomatically = true, flushAutomatically = true) - @Query(value = "alter table USERS add column deleted int(1) not null default 0", nativeQuery = true) - void addDeletedColumn(); -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustom.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustom.java deleted file mode 100644 index c586b54027..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustom.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.boot.daos.user; - -import java.util.Collection; -import java.util.List; -import java.util.Set; -import java.util.function.Predicate; - -import com.baeldung.boot.domain.User; - -public interface UserRepositoryCustom { - List findUserByEmails(Set emails); - - List findAllUsersByPredicates(Collection> predicates); -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustomImpl.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustomImpl.java deleted file mode 100644 index 63a743b6b5..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustomImpl.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.boot.daos.user; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Path; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; - -import com.baeldung.boot.domain.User; - -public class UserRepositoryCustomImpl implements UserRepositoryCustom { - - @PersistenceContext - private EntityManager entityManager; - - @Override - public List findUserByEmails(Set emails) { - CriteriaBuilder cb = entityManager.getCriteriaBuilder(); - CriteriaQuery query = cb.createQuery(User.class); - Root user = query.from(User.class); - - Path emailPath = user.get("email"); - - List predicates = new ArrayList<>(); - for (String email : emails) { - - predicates.add(cb.like(emailPath, email)); - - } - query.select(user) - .where(cb.or(predicates.toArray(new Predicate[predicates.size()]))); - - return entityManager.createQuery(query) - .getResultList(); - } - - @Override - public List findAllUsersByPredicates(Collection> predicates) { - List allUsers = entityManager.createQuery("select u from User u", User.class).getResultList(); - Stream allUsersStream = allUsers.stream(); - for (java.util.function.Predicate predicate : predicates) { - allUsersStream = allUsersStream.filter(predicate); - } - - return allUsersStream.collect(Collectors.toList()); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate.java deleted file mode 100644 index e435f4c85c..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Transient; - -import org.springframework.context.ApplicationEventPublisher; - -@Entity -class Aggregate { - @Transient - private ApplicationEventPublisher eventPublisher; - @Id - private long id; - - private Aggregate() { - } - - Aggregate(long id, ApplicationEventPublisher eventPublisher) { - this.id = id; - this.eventPublisher = eventPublisher; - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "DomainEntity [id=" + id + "]"; - } - - void domainOperation() { - // some business logic - if (eventPublisher != null) { - eventPublisher.publishEvent(new DomainEvent()); - } - } - - long getId() { - return id; - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate2.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate2.java deleted file mode 100644 index 08f61db812..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate2.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -import java.util.ArrayList; -import java.util.Collection; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Transient; - -import org.springframework.data.domain.AfterDomainEventPublication; -import org.springframework.data.domain.DomainEvents; - -@Entity -public class Aggregate2 { - @Transient - private final Collection domainEvents; - @Id - @GeneratedValue - private long id; - - public Aggregate2() { - domainEvents = new ArrayList<>(); - } - - @AfterDomainEventPublication - public void clearEvents() { - domainEvents.clear(); - } - - public void domainOperation() { - // some domain operation - domainEvents.add(new DomainEvent()); - } - - @DomainEvents - public Collection events() { - return domainEvents; - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate2Repository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate2Repository.java deleted file mode 100644 index 7f09c410fc..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate2Repository.java +++ /dev/null @@ -1,10 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -import org.springframework.data.repository.CrudRepository; - -public interface Aggregate2Repository extends CrudRepository { - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate3.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate3.java deleted file mode 100644 index f664322a59..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate3.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; - -import org.springframework.data.domain.AbstractAggregateRoot; - -@Entity -public class Aggregate3 extends AbstractAggregateRoot { - @Id - @GeneratedValue - private long id; - - public void domainOperation() { - // some domain operation - registerEvent(new DomainEvent()); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate3Repository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate3Repository.java deleted file mode 100644 index 93f50bb5cf..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate3Repository.java +++ /dev/null @@ -1,14 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -import org.springframework.data.repository.CrudRepository; - -/** - * @author goobar - * - */ -public interface Aggregate3Repository extends CrudRepository { - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/AggregateRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/AggregateRepository.java deleted file mode 100644 index 1c2d3884bf..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/AggregateRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -import org.springframework.data.repository.CrudRepository; - -public interface AggregateRepository extends CrudRepository { - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DddConfig.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DddConfig.java deleted file mode 100644 index 34cf21463b..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DddConfig.java +++ /dev/null @@ -1,15 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.PropertySource; - -@SpringBootConfiguration -@EnableAutoConfiguration -@PropertySource("classpath:/ddd.properties") -public class DddConfig { - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DomainEvent.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DomainEvent.java deleted file mode 100644 index e7626e742d..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DomainEvent.java +++ /dev/null @@ -1,8 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -class DomainEvent { - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DomainService.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DomainService.java deleted file mode 100644 index 80aa5ca6cb..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DomainService.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -import javax.transaction.Transactional; - -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.stereotype.Service; - -@Service -public class DomainService { - private final ApplicationEventPublisher eventPublisher; - private final AggregateRepository repository; - - public DomainService(AggregateRepository repository, ApplicationEventPublisher eventPublisher) { - this.repository = repository; - this.eventPublisher = eventPublisher; - } - - @Transactional - public void serviceDomainOperation(long entityId) { - repository.findById(entityId) - .ifPresent(entity -> { - entity.domainOperation(); - repository.save(entity); - eventPublisher.publishEvent(new DomainEvent()); - }); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Article.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Article.java deleted file mode 100644 index de4dbed1a0..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Article.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.boot.domain; - -import javax.persistence.*; -import java.util.Date; - -@Entity -public class Article { - - @Id - @GeneratedValue - private Integer id; - @Temporal(TemporalType.DATE) - private Date publicationDate; - @Temporal(TemporalType.TIME) - private Date publicationTime; - @Temporal(TemporalType.TIMESTAMP) - private Date creationDateTime; - - public Integer getId() { - return id; - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Bar.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Bar.java deleted file mode 100644 index 35d1903801..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Bar.java +++ /dev/null @@ -1,220 +0,0 @@ -package com.baeldung.boot.domain; - -import com.google.common.collect.Sets; -import org.hibernate.annotations.OrderBy; -import org.hibernate.envers.Audited; -import org.jboss.logging.Logger; -import org.springframework.data.annotation.CreatedBy; -import org.springframework.data.annotation.CreatedDate; -import org.springframework.data.annotation.LastModifiedBy; -import org.springframework.data.annotation.LastModifiedDate; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; - -import javax.persistence.*; -import java.io.Serializable; -import java.util.Date; -import java.util.Set; - -@Entity -@NamedQuery(name = "Bar.findAll", query = "SELECT b FROM Bar b") -@Audited -@EntityListeners(AuditingEntityListener.class) -public class Bar implements Serializable { - - private static Logger logger = Logger.getLogger(Bar.class); - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id") - private int id; - - @Column(name = "name") - private String name; - @OneToMany(mappedBy = "bar", cascade = CascadeType.ALL, fetch = FetchType.LAZY) - @OrderBy(clause = "NAME DESC") - // @NotAudited - private Set fooSet = Sets.newHashSet(); - @Column(name = "operation") - private String operation; - @Column(name = "timestamp") - private long timestamp; - @Column(name = "created_date", updatable = false, nullable = false) - @CreatedDate - private long createdDate; - @Column(name = "modified_date") - @LastModifiedDate - private long modifiedDate; - @Column(name = "created_by") - @CreatedBy - private String createdBy; - @Column(name = "modified_by") - @LastModifiedBy - private String modifiedBy; - - public Bar() { - super(); - } - - public Bar(final String name) { - super(); - - this.name = name; - } - - public Set getFooSet() { - return fooSet; - } - - // API - - public void setFooSet(final Set fooSet) { - this.fooSet = fooSet; - } - - public int getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public OPERATION getOperation() { - return OPERATION.parse(operation); - } - - public void setOperation(final String operation) { - this.operation = operation; - } - - public void setOperation(final OPERATION operation) { - this.operation = operation.getValue(); - } - - public long getTimestamp() { - return timestamp; - } - - public void setTimestamp(final long timestamp) { - this.timestamp = timestamp; - } - - public long getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(final long createdDate) { - this.createdDate = createdDate; - } - - public long getModifiedDate() { - return modifiedDate; - } - - public void setModifiedDate(final long modifiedDate) { - this.modifiedDate = modifiedDate; - } - - public String getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(final String createdBy) { - this.createdBy = createdBy; - } - - public String getModifiedBy() { - return modifiedBy; - } - - public void setModifiedBy(final String modifiedBy) { - this.modifiedBy = modifiedBy; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final Bar other = (Bar) obj; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Bar [name=").append(name).append("]"); - return builder.toString(); - } - - @PrePersist - public void onPrePersist() { - logger.info("@PrePersist"); - audit(OPERATION.INSERT); - } - - @PreUpdate - public void onPreUpdate() { - logger.info("@PreUpdate"); - audit(OPERATION.UPDATE); - } - - @PreRemove - public void onPreRemove() { - logger.info("@PreRemove"); - audit(OPERATION.DELETE); - } - - private void audit(final OPERATION operation) { - setOperation(operation); - setTimestamp((new Date()).getTime()); - } - - public enum OPERATION { - INSERT, UPDATE, DELETE; - private String value; - - OPERATION() { - value = toString(); - } - - public static OPERATION parse(final String value) { - OPERATION operation = null; - for (final OPERATION op : OPERATION.values()) { - if (op.getValue().equals(value)) { - operation = op; - break; - } - } - return operation; - } - - public String getValue() { - return value; - } - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Foo.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Foo.java deleted file mode 100644 index 5030e5600b..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Foo.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.baeldung.boot.domain; - -import org.hibernate.envers.Audited; - -import javax.persistence.*; -import java.io.Serializable; - -@NamedNativeQueries({@NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class)}) -@Entity -@Audited -// @Proxy(lazy = false) -public class Foo implements Serializable { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id") - private long id; - - @Column(name = "name", nullable = false) - private String name; - - @ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinColumn(name = "BAR_ID") - private Bar bar = new Bar(); - - public Foo() { - super(); - } - - public Foo(final String name) { - super(); - this.name = name; - } - - // - - public Bar getBar() { - return bar; - } - - public void setBar(final Bar bar) { - this.bar = bar; - } - - public long getId() { - return id; - } - - public void setId(final long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - // - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final Foo other = (Foo) obj; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Foo [name=").append(name).append("]"); - return builder.toString(); - } -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Item.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Item.java deleted file mode 100644 index 8ac06af15a..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Item.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.baeldung.boot.domain; - -import java.math.BigDecimal; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.ManyToOne; - -@Entity -public class Item { - - private String color; - private String grade; - - @Id - private Long id; - - @ManyToOne - private ItemType itemType; - - private String name; - private BigDecimal price; - @ManyToOne - private Store store; - - public String getColor() { - return color; - } - - public String getGrade() { - return grade; - } - - public Long getId() { - return id; - } - - public ItemType getItemType() { - return itemType; - } - - public String getName() { - return name; - } - - public BigDecimal getPrice() { - return price; - } - - public Store getStore() { - return store; - } - - public void setColor(String color) { - this.color = color; - } - - public void setGrade(String grade) { - this.grade = grade; - } - - public void setId(Long id) { - this.id = id; - } - - public void setItemType(ItemType itemType) { - this.itemType = itemType; - } - - public void setName(String name) { - this.name = name; - } - - public void setPrice(BigDecimal price) { - this.price = price; - } - - public void setStore(Store store) { - this.store = store; - } -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/ItemType.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/ItemType.java deleted file mode 100644 index 8a52a9847c..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/ItemType.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.boot.domain; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToMany; - -@Entity -public class ItemType { - - @Id - private Long id; - @OneToMany(cascade = CascadeType.ALL) - @JoinColumn(name = "ITEM_TYPE_ID") - private List items = new ArrayList<>(); - - private String name; - - public Long getId() { - return id; - } - - public List getItems() { - return items; - } - - public String getName() { - return name; - } - - public void setId(Long id) { - this.id = id; - } - - public void setItems(List items) { - this.items = items; - } - - public void setName(String name) { - this.name = name; - } -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/KVTag.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/KVTag.java deleted file mode 100644 index 1901f43c0a..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/KVTag.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.boot.domain; - -import javax.persistence.Embeddable; - -@Embeddable -public class KVTag { - private String key; - private String value; - - public KVTag() { - } - - public KVTag(String key, String value) { - super(); - this.key = key; - this.value = value; - } - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Location.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Location.java deleted file mode 100644 index 9c1b93d551..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Location.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.baeldung.boot.domain; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToMany; - -@Entity -public class Location { - - private String city; - private String country; - @Id - private Long id; - - @OneToMany(cascade = CascadeType.ALL) - @JoinColumn(name = "LOCATION_ID") - private List stores = new ArrayList<>(); - - public String getCity() { - return city; - } - - public String getCountry() { - return country; - } - - public Long getId() { - return id; - } - - public List getStores() { - return stores; - } - - public void setCity(String city) { - this.city = city; - } - - public void setCountry(String country) { - this.country = country; - } - - public void setId(Long id) { - this.id = id; - } - - public void setStores(List stores) { - this.stores = stores; - } -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/MerchandiseEntity.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/MerchandiseEntity.java deleted file mode 100644 index e94c23de86..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/MerchandiseEntity.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.baeldung.boot.domain; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import java.math.BigDecimal; - -@Entity -public class MerchandiseEntity { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - private String title; - - private BigDecimal price; - - private String brand; - - public MerchandiseEntity() { - } - - public MerchandiseEntity(String title, BigDecimal price) { - this.title = title; - this.price = price; - } - - public Long getId() { - return id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public BigDecimal getPrice() { - return price; - } - - public void setPrice(BigDecimal price) { - this.price = price; - } - - public String getBrand() { - return brand; - } - - public void setBrand(String brand) { - this.brand = brand; - } - - @Override - public String toString() { - return "MerchandiseEntity{" + - "id=" + id + - ", title='" + title + '\'' + - ", price=" + price + - ", brand='" + brand + '\'' + - '}'; - } -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Possession.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Possession.java deleted file mode 100644 index f13491ad82..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Possession.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.baeldung.boot.domain; - -import javax.persistence.*; -import com.baeldung.boot.domain.Possession; - -@Entity -@Table -public class Possession { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private long id; - - private String name; - - public Possession() { - super(); - } - - public Possession(final String name) { - super(); - - this.name = name; - } - - public long getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) + (int) (id ^ (id >>> 32)); - result = (prime * result) + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final Possession other = (Possession) obj; - if (id != other.id) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - return true; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]"); - return builder.toString(); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/SkillTag.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/SkillTag.java deleted file mode 100644 index 0933a3e6af..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/SkillTag.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.boot.domain; - -import javax.persistence.Embeddable; - -@Embeddable -public class SkillTag { - private String name; - private int value; - - public SkillTag() { - } - - public SkillTag(String name, int value) { - super(); - this.name = name; - this.value = value; - } - - public int getValue() { - return value; - } - - public void setValue(int value) { - this.value = value; - } - - public String getName() { - return name; - } -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Store.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Store.java deleted file mode 100644 index 5b4b831cc7..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Store.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.baeldung.boot.domain; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; - -@Entity -public class Store { - - private Boolean active; - @Id - private Long id; - @OneToMany(cascade = CascadeType.ALL) - @JoinColumn(name = "STORE_ID") - private List items = new ArrayList<>(); - private Long itemsSold; - - @ManyToOne - private Location location; - - private String name; - - public Boolean getActive() { - return active; - } - - public Long getId() { - return id; - } - - public List getItems() { - return items; - } - - public Long getItemsSold() { - return itemsSold; - } - - public Location getLocation() { - return location; - } - - public String getName() { - return name; - } - - public void setActive(Boolean active) { - this.active = active; - } - - public void setId(Long id) { - this.id = id; - } - - public void setItems(List items) { - this.items = items; - } - - public void setItemsSold(Long itemsSold) { - this.itemsSold = itemsSold; - } - - public void setLocation(Location location) { - this.location = location; - } - - public void setName(String name) { - this.name = name; - } -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Student.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Student.java deleted file mode 100644 index 1003167cc7..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Student.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.baeldung.boot.domain; - -import javax.persistence.ElementCollection; -import javax.persistence.Entity; -import javax.persistence.Id; -import java.util.ArrayList; -import java.util.List; - -@Entity -public class Student { - - @Id - private long id; - private String name; - - @ElementCollection - private List tags = new ArrayList<>(); - - @ElementCollection - private List skillTags = new ArrayList<>(); - - @ElementCollection - private List kvTags = new ArrayList<>(); - - public Student() { - } - - public Student(long id, String name) { - super(); - this.id = id; - this.name = name; - } - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getTags() { - return tags; - } - - public void setTags(List tags) { - this.tags.addAll(tags); - } - - public List getSkillTags() { - return skillTags; - } - - public void setSkillTags(List skillTags) { - this.skillTags.addAll(skillTags); - } - - public List getKVTags() { - return this.kvTags; - } - - public void setKVTags(List kvTags) { - this.kvTags.addAll(kvTags); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/User.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/User.java deleted file mode 100644 index cca00e52a2..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/User.java +++ /dev/null @@ -1,132 +0,0 @@ -package com.baeldung.boot.domain; - -import javax.persistence.*; - -import java.time.LocalDate; -import java.util.List; -import java.util.Objects; - -@Entity -@Table(name = "users") -public class User { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private int id; - private String name; - private LocalDate creationDate; - private LocalDate lastLoginDate; - private boolean active; - private int age; - @Column(unique = true, nullable = false) - private String email; - private Integer status; - @OneToMany - List possessionList; - - public User() { - super(); - } - - public User(String name, LocalDate creationDate,String email, Integer status) { - this.name = name; - this.creationDate = creationDate; - this.email = email; - this.status = status; - this.active = true; - } - - public int getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public String getEmail() { - return email; - } - - public void setEmail(final String email) { - this.email = email; - } - - public Integer getStatus() { - return status; - } - - public void setStatus(Integer status) { - this.status = status; - } - - public int getAge() { - return age; - } - - public void setAge(final int age) { - this.age = age; - } - - public LocalDate getCreationDate() { - return creationDate; - } - - public List getPossessionList() { - return possessionList; - } - - public void setPossessionList(List possessionList) { - this.possessionList = possessionList; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("User [name=").append(name).append(", id=").append(id).append("]"); - return builder.toString(); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - User user = (User) o; - return id == user.id && - age == user.age && - Objects.equals(name, user.name) && - Objects.equals(creationDate, user.creationDate) && - Objects.equals(email, user.email) && - Objects.equals(status, user.status); - } - - @Override - public int hashCode() { - return Objects.hash(id, name, creationDate, age, email, status); - } - - public LocalDate getLastLoginDate() { - return lastLoginDate; - } - - public void setLastLoginDate(LocalDate lastLoginDate) { - this.lastLoginDate = lastLoginDate; - } - - public boolean isActive() { - return active; - } - - public void setActive(boolean active) { - this.active = active; - } - -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IBarService.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IBarService.java deleted file mode 100644 index 8054cbba59..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IBarService.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.boot.services; - -import com.baeldung.boot.domain.Bar; - -public interface IBarService extends IOperations { - // -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IFooService.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IFooService.java deleted file mode 100644 index 871cccdd45..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IFooService.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.boot.services; - -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; - -import com.baeldung.boot.domain.Foo; - -public interface IFooService extends IOperations { - - Foo retrieveByName(String name); - - Page findPaginated(Pageable pageable); - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IOperations.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IOperations.java deleted file mode 100644 index ec2b866b6f..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IOperations.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.boot.services; - -import org.springframework.data.domain.Page; - -import java.io.Serializable; -import java.util.List; - -public interface IOperations { - - T findOne(final long id); - - List findAll(); - - Page findPaginated(int page, int size); - - // write - - T create(final T entity); - - T update(final T entity); - - void delete(final T entity); - - void deleteById(final long entityId); - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/AbstractService.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/AbstractService.java deleted file mode 100644 index f88d018bbb..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/AbstractService.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung.boot.services.impl; - -import com.baeldung.boot.services.IOperations; -import com.google.common.collect.Lists; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.repository.PagingAndSortingRepository; -import org.springframework.transaction.annotation.Transactional; - -import java.io.Serializable; -import java.util.List; - -@Transactional -public abstract class AbstractService implements IOperations { - - // read - one - - @Override - @Transactional(readOnly = true) - public T findOne(final long id) { - return getDao().findById(id).orElse(null); - } - - // read - all - - @Override - @Transactional(readOnly = true) - public List findAll() { - return Lists.newArrayList(getDao().findAll()); - } - - @Override - public Page findPaginated(final int page, final int size) { - return getDao().findAll(PageRequest.of(page, size)); - } - - // write - - @Override - public T create(final T entity) { - return getDao().save(entity); - } - - @Override - public T update(final T entity) { - return getDao().save(entity); - } - - @Override - public void delete(final T entity) { - getDao().delete(entity); - } - - @Override - public void deleteById(final long entityId) { - getDao().deleteById(entityId); - } - - protected abstract PagingAndSortingRepository getDao(); - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/AbstractSpringDataJpaService.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/AbstractSpringDataJpaService.java deleted file mode 100644 index a73a6bd7fc..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/AbstractSpringDataJpaService.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.baeldung.boot.services.impl; - -import com.baeldung.boot.services.IOperations; -import com.google.common.collect.Lists; -import org.springframework.data.repository.CrudRepository; -import org.springframework.transaction.annotation.Transactional; - -import java.io.Serializable; -import java.util.List; - -@Transactional(value = "transactionManager") -public abstract class AbstractSpringDataJpaService implements IOperations { - - @Override - public T findOne(final long id) { - return getDao().findById(id).orElse(null); - } - - @Override - public List findAll() { - return Lists.newArrayList(getDao().findAll()); - } - - @Override - public T create(final T entity) { - return getDao().save(entity); - } - - @Override - public T update(final T entity) { - return getDao().save(entity); - } - - @Override - public void delete(final T entity) { - getDao().delete(entity); - } - - @Override - public void deleteById(final long entityId) { - getDao().deleteById(entityId); - } - - protected abstract CrudRepository getDao(); -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/BarSpringDataJpaService.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/BarSpringDataJpaService.java deleted file mode 100644 index 80568f2fd4..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/BarSpringDataJpaService.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.boot.services.impl; - -import com.baeldung.boot.daos.IBarCrudRepository; -import com.baeldung.boot.domain.Bar; -import com.baeldung.boot.services.IBarService; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.repository.CrudRepository; - -import java.io.Serializable; - -public class BarSpringDataJpaService extends AbstractSpringDataJpaService implements IBarService { - - @Autowired - private IBarCrudRepository dao; - - public BarSpringDataJpaService() { - super(); - } - - @Override - protected CrudRepository getDao() { - return dao; - } - - @Override - public Page findPaginated(int page, int size) { - throw new UnsupportedOperationException("Not implemented yet"); - } -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/FooService.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/FooService.java deleted file mode 100644 index 04eec63854..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/FooService.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.baeldung.boot.services.impl; - -import com.google.common.collect.Lists; -import com.baeldung.boot.daos.IFooDao; -import com.baeldung.boot.domain.Foo; -import com.baeldung.boot.services.IFooService; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.repository.PagingAndSortingRepository; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -@Service -@Transactional -public class FooService extends AbstractService implements IFooService { - - @Autowired - private IFooDao dao; - - public FooService() { - super(); - } - - // API - - @Override - protected PagingAndSortingRepository getDao() { - return dao; - } - - // custom methods - - @Override - public Foo retrieveByName(final String name) { - return dao.retrieveByName(name); - } - - // overridden to be secured - - @Override - @Transactional(readOnly = true) - public List findAll() { - return Lists.newArrayList(getDao().findAll()); - } - - @Override - public Page findPaginated(Pageable pageable) { - return dao.findAll(pageable); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java deleted file mode 100644 index 3b9aa2cc18..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.multipledb; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class MultipleDbApplication { - - public static void main(String[] args) { - SpringApplication.run(MultipleDbApplication.class, args); - } - -} - diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceProductAutoConfiguration.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceProductAutoConfiguration.java deleted file mode 100644 index a6f8f0829f..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceProductAutoConfiguration.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.baeldung.multipledb; - -import java.util.HashMap; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.jdbc.DataSourceBuilder; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.PlatformTransactionManager; - -/** - * By default, the persistence-multiple-db.properties file is read for - * non auto configuration in PersistenceProductConfiguration. - *

- * If we need to use persistence-multiple-db-boot.properties and auto configuration - * then uncomment the below @Configuration class and comment out PersistenceProductConfiguration. - */ -//@Configuration -@PropertySource({"classpath:persistence-multiple-db-boot.properties"}) -@EnableJpaRepositories(basePackages = "com.baeldung.multipledb.dao.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager") -@Profile("!tc") -public class PersistenceProductAutoConfiguration { - @Autowired - private Environment env; - - public PersistenceProductAutoConfiguration() { - super(); - } - - // - - @Bean - public LocalContainerEntityManagerFactoryBean productEntityManager() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(productDataSource()); - em.setPackagesToScan("com.baeldung.multipledb.model.product"); - - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - em.setJpaVendorAdapter(vendorAdapter); - final HashMap properties = new HashMap(); - properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); - em.setJpaPropertyMap(properties); - - return em; - } - - @Bean - @ConfigurationProperties(prefix="spring.second-datasource") - public DataSource productDataSource() { - return DataSourceBuilder.create().build(); - } - - @Bean - public PlatformTransactionManager productTransactionManager() { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(productEntityManager().getObject()); - return transactionManager; - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java deleted file mode 100644 index bcf2cd84eb..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.baeldung.multipledb; - -import com.google.common.base.Preconditions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.PlatformTransactionManager; - -import javax.sql.DataSource; -import java.util.HashMap; - -@Configuration -@PropertySource({"classpath:persistence-multiple-db.properties"}) -@EnableJpaRepositories(basePackages = "com.baeldung.multipledb.dao.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager") -@Profile("!tc") -public class PersistenceProductConfiguration { - @Autowired - private Environment env; - - public PersistenceProductConfiguration() { - super(); - } - - // - - @Bean - public LocalContainerEntityManagerFactoryBean productEntityManager() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(productDataSource()); - em.setPackagesToScan("com.baeldung.multipledb.model.product"); - - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - em.setJpaVendorAdapter(vendorAdapter); - final HashMap properties = new HashMap(); - properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); - em.setJpaPropertyMap(properties); - - return em; - } - - @Bean - public DataSource productDataSource() { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); - dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("product.jdbc.url"))); - dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); - dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); - - return dataSource; - } - - @Bean - public PlatformTransactionManager productTransactionManager() { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(productEntityManager().getObject()); - return transactionManager; - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceUserAutoConfiguration.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceUserAutoConfiguration.java deleted file mode 100644 index e04a1621b2..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceUserAutoConfiguration.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.multipledb; - -import java.util.HashMap; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.jdbc.DataSourceBuilder; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; -import org.springframework.context.annotation.Profile; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.PlatformTransactionManager; - -/** - * By default, the persistence-multiple-db.properties file is read for - * non auto configuration in PersistenceUserConfiguration. - *

- * If we need to use persistence-multiple-db-boot.properties and auto configuration - * then uncomment the below @Configuration class and comment out PersistenceUserConfiguration. - */ -//@Configuration -@PropertySource({"classpath:persistence-multiple-db-boot.properties"}) -@EnableJpaRepositories(basePackages = "com.baeldung.multipledb.dao.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager") -@Profile("!tc") -public class PersistenceUserAutoConfiguration { - @Autowired - private Environment env; - - public PersistenceUserAutoConfiguration() { - super(); - } - - // - - @Primary - @Bean - public LocalContainerEntityManagerFactoryBean userEntityManager() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(userDataSource()); - em.setPackagesToScan("com.baeldung.multipledb.model.user"); - - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - em.setJpaVendorAdapter(vendorAdapter); - final HashMap properties = new HashMap(); - properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); - em.setJpaPropertyMap(properties); - - return em; - } - - @Bean - @Primary - @ConfigurationProperties(prefix="spring.datasource") - public DataSource userDataSource() { - return DataSourceBuilder.create().build(); - } - - @Primary - @Bean - public PlatformTransactionManager userTransactionManager() { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(userEntityManager().getObject()); - return transactionManager; - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceUserConfiguration.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceUserConfiguration.java deleted file mode 100644 index 6b48455c0c..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceUserConfiguration.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.baeldung.multipledb; - -import com.google.common.base.Preconditions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.*; -import org.springframework.core.env.Environment; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.PlatformTransactionManager; - -import javax.sql.DataSource; -import java.util.HashMap; - -@Configuration -@PropertySource({"classpath:persistence-multiple-db.properties"}) -@EnableJpaRepositories(basePackages = "com.baeldung.multipledb.dao.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager") -@Profile("!tc") -public class PersistenceUserConfiguration { - @Autowired - private Environment env; - - public PersistenceUserConfiguration() { - super(); - } - - // - - @Primary - @Bean - public LocalContainerEntityManagerFactoryBean userEntityManager() { - System.out.println("loading config"); - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(userDataSource()); - em.setPackagesToScan("com.baeldung.multipledb.model.user"); - - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - em.setJpaVendorAdapter(vendorAdapter); - final HashMap properties = new HashMap(); - properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); - em.setJpaPropertyMap(properties); - - return em; - } - - @Primary - @Bean - public DataSource userDataSource() { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); - dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("user.jdbc.url"))); - dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); - dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); - - return dataSource; - } - - @Primary - @Bean - public PlatformTransactionManager userTransactionManager() { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(userEntityManager().getObject()); - return transactionManager; - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java deleted file mode 100755 index f1256e2c72..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.multipledb.dao.product; - -import java.util.List; - -import org.springframework.data.domain.Pageable; -import org.springframework.data.repository.PagingAndSortingRepository; - -import com.baeldung.multipledb.model.product.Product; - -public interface ProductRepository extends PagingAndSortingRepository { - - - List findAllByPrice(double price, Pageable pageable); -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/user/PossessionRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/user/PossessionRepository.java deleted file mode 100644 index ae37fde20d..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/user/PossessionRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.multipledb.dao.user; - -import org.springframework.data.jpa.repository.JpaRepository; - -import com.baeldung.multipledb.model.user.PossessionMultipleDB; - -public interface PossessionRepository extends JpaRepository { - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/user/UserRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/user/UserRepository.java deleted file mode 100644 index 267a61a93f..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/user/UserRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.multipledb.dao.user; - -import org.springframework.data.jpa.repository.JpaRepository; - -import com.baeldung.multipledb.model.user.UserMultipleDB; - -public interface UserRepository extends JpaRepository { -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/product/Product.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/product/Product.java deleted file mode 100755 index eaf471043c..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/product/Product.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.baeldung.multipledb.model.product; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(schema = "products") -public class Product { - - @Id - private int id; - - private String name; - - private double price; - - public Product() { - super(); - } - - private Product(int id, String name, double price) { - super(); - this.id = id; - this.name = name; - this.price = price; - } - - public static Product from(int id, String name, double price) { - return new Product(id, name, price); - } - - public int getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public double getPrice() { - return price; - } - - public void setPrice(final double price) { - this.price = price; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Product [name=") - .append(name) - .append(", id=") - .append(id) - .append("]"); - return builder.toString(); - } -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/user/PossessionMultipleDB.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/user/PossessionMultipleDB.java deleted file mode 100644 index a6a3c88bd0..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/user/PossessionMultipleDB.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.baeldung.multipledb.model.user; - -import javax.persistence.*; - -@Entity -@Table -public class PossessionMultipleDB { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private long id; - - private String name; - - public PossessionMultipleDB() { - super(); - } - - public PossessionMultipleDB(final String name) { - super(); - - this.name = name; - } - - public long getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) + (int) (id ^ (id >>> 32)); - result = (prime * result) + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final PossessionMultipleDB other = (PossessionMultipleDB) obj; - if (id != other.id) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - return true; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]"); - return builder.toString(); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/user/UserMultipleDB.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/user/UserMultipleDB.java deleted file mode 100644 index c7cd07f7a1..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/user/UserMultipleDB.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.baeldung.multipledb.model.user; - -import javax.persistence.*; - -import java.util.List; - -@Entity -@Table(name = "users") -public class UserMultipleDB { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private int id; - private String name; - private int age; - @Column(unique = true, nullable = false) - private String email; - private Integer status; - - @OneToMany - List possessionList; - - public UserMultipleDB() { - super(); - } - - public UserMultipleDB(String name, String email, Integer status) { - this.name = name; - this.email = email; - this.status = status; - } - - public int getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public String getEmail() { - return email; - } - - public void setEmail(final String email) { - this.email = email; - } - - public Integer getStatus() { - return status; - } - - public void setStatus(Integer status) { - this.status = status; - } - - public int getAge() { - return age; - } - - public void setAge(final int age) { - this.age = age; - } - - public List getPossessionList() { - return possessionList; - } - - public void setPossessionList(List possessionList) { - this.possessionList = possessionList; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("User [name=").append(name).append(", id=").append(id).append("]"); - return builder.toString(); - } - -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/main/resources/application.properties b/persistence-modules/spring-data-jpa/src/main/resources/application.properties deleted file mode 100644 index f127dd5e50..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/resources/application.properties +++ /dev/null @@ -1,6 +0,0 @@ -spring.main.allow-bean-definition-overriding=true - -spring.jpa.properties.hibernate.jdbc.batch_size=4 -spring.jpa.properties.hibernate.order_inserts=true -spring.jpa.properties.hibernate.order_updates=true -spring.jpa.properties.hibernate.generate_statistics=true diff --git a/persistence-modules/spring-data-jpa/src/main/resources/ddd.properties b/persistence-modules/spring-data-jpa/src/main/resources/ddd.properties deleted file mode 100644 index e5126b694b..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/resources/ddd.properties +++ /dev/null @@ -1 +0,0 @@ -spring.datasource.initialization-mode=never \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/main/resources/import_entities.sql b/persistence-modules/spring-data-jpa/src/main/resources/import_entities.sql deleted file mode 100644 index deb9d07f05..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/resources/import_entities.sql +++ /dev/null @@ -1,21 +0,0 @@ -insert into Article(id, publication_date, publication_time, creation_date_time) values(1, TO_DATE('01/01/2018', 'DD/MM/YYYY'), TO_DATE('15:00', 'HH24:MI'), TO_DATE('31/12/2017 07:30', 'DD/MM/YYYY HH24:MI')); -insert into Article(id, publication_date, publication_time, creation_date_time) values(2, TO_DATE('01/01/2018', 'DD/MM/YYYY'), TO_DATE('15:30', 'HH24:MI'), TO_DATE('15/12/2017 08:00', 'DD/MM/YYYY HH24:MI')); -insert into Article(id, publication_date, publication_time, creation_date_time) values(3, TO_DATE('15/12/2017', 'DD/MM/YYYY'), TO_DATE('16:00', 'HH24:MI'), TO_DATE('01/12/2017 13:45', 'DD/MM/YYYY HH24:MI')); - -insert into location (id, country, city) values (1, 'Country X', 'City One'); -insert into location (id, country, city) values (2, 'Country X', 'City Two'); -insert into location (id, country, city) values (3, 'Country X', 'City Three'); - -insert into store (id, name, location_id, items_sold, active) values (1, 'Store One', 3, 130000, true); -insert into store (id, name, location_id, items_sold, active) values (2, 'Store Two', 1, 170000, false); - -insert into item_type (id, name) values (1, 'Food'); -insert into item_type (id, name) values (2, 'Furniture'); -insert into item_type (id, name) values (3, 'Electronics'); - -insert into item (id, name, store_id, item_type_id, price, grade, color) values (1, 'Food Item One', 1, 1, 100, 'A', 'Color x'); -insert into item (id, name, store_id, item_type_id, price, grade, color) values (2, 'Furniture Item One', 1, 2, 2500, 'B', 'Color y'); -insert into item (id, name, store_id, item_type_id, price, grade, color) values (3, 'Food Item Two', 1, 1, 35, 'A', 'Color z'); -insert into item (id, name, store_id, item_type_id, price, grade, color) values (5, 'Furniture Item Two', 2, 2, 1600, 'A', 'Color w'); -insert into item (id, name, store_id, item_type_id, price, grade, color) values (6, 'Food Item Three', 2, 1, 5, 'B', 'Color a'); -insert into item (id, name, store_id, item_type_id, price, grade, color) values (7, 'Electronics Item One', 2, 3, 999, 'B', 'Color b'); diff --git a/persistence-modules/spring-data-jpa/src/main/resources/logback.xml b/persistence-modules/spring-data-jpa/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/main/resources/persistence-multiple-db-boot.properties b/persistence-modules/spring-data-jpa/src/main/resources/persistence-multiple-db-boot.properties deleted file mode 100644 index ffca79b3f5..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/resources/persistence-multiple-db-boot.properties +++ /dev/null @@ -1,11 +0,0 @@ -hibernate.hbm2ddl.auto=create-drop -hibernate.cache.use_second_level_cache=false -hibernate.cache.use_query_cache=false - -spring.datasource.jdbcUrl=jdbc:h2:mem:spring_jpa_user;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS USERS -spring.datasource.username=sa -spring.datasource.password=sa - -spring.second-datasource.jdbcUrl=jdbc:h2:mem:spring_jpa_product;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS PRODUCTS -spring.second-datasource.username=sa -spring.second-datasource.password=sa diff --git a/persistence-modules/spring-data-jpa/src/main/resources/persistence-multiple-db.properties b/persistence-modules/spring-data-jpa/src/main/resources/persistence-multiple-db.properties deleted file mode 100644 index 75534e8a54..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/resources/persistence-multiple-db.properties +++ /dev/null @@ -1,13 +0,0 @@ -# jdbc.X -jdbc.driverClassName=org.h2.Driver -user.jdbc.url=jdbc:h2:mem:spring_jpa_user;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS USERS -product.jdbc.url=jdbc:h2:mem:spring_jpa_product;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS PRODUCTS -jdbc.user=sa -jdbc.pass=sa - -# hibernate.X -hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=false -hibernate.hbm2ddl.auto=create-drop -hibernate.cache.use_second_level_cache=false -hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/main/resources/persistence.properties b/persistence-modules/spring-data-jpa/src/main/resources/persistence.properties deleted file mode 100644 index 6bc83edf34..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/resources/persistence.properties +++ /dev/null @@ -1,14 +0,0 @@ -# jdbc.X -jdbc.driverClassName=org.h2.Driver -jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS USERS -jdbc.user=sa -jdbc.pass=sa - -# hibernate.X -hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=true -hibernate.hbm2ddl.auto=create-drop -hibernate.cache.use_second_level_cache=true -hibernate.cache.use_query_cache=true -hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory - diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/SpringContextTest.java deleted file mode 100644 index eaccf4acba..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.Application; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java deleted file mode 100644 index f3697bf39f..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.Application; -import com.baeldung.boot.config.PersistenceConfiguration; -import com.baeldung.multipledb.PersistenceProductConfiguration; -import com.baeldung.multipledb.PersistenceUserConfiguration; - -@RunWith(SpringRunner.class) -@DataJpaTest(excludeAutoConfiguration = { - PersistenceConfiguration.class, - PersistenceUserConfiguration.class, - PersistenceProductConfiguration.class }) -@ContextConfiguration(classes = Application.class) -public class SpringJpaContextIntegrationTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/ArticleRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/ArticleRepositoryIntegrationTest.java deleted file mode 100644 index 20fc3cbeaf..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/ArticleRepositoryIntegrationTest.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.baeldung.boot.daos; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.List; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.domain.Article; - -@RunWith(SpringRunner.class) -@DataJpaTest(properties="spring.datasource.data=classpath:import_entities.sql") -public class ArticleRepositoryIntegrationTest { - - @Autowired - private ArticleRepository repository; - - @Test - public void givenImportedArticlesWhenFindAllByPublicationDateThenArticles1And2Returned() - throws Exception { - List

result = repository.findAllByPublicationDate( - new SimpleDateFormat("yyyy-MM-dd").parse("2018-01-01") - ); - - assertEquals(2, result.size()); - assertTrue(result.stream() - .map(Article::getId) - .allMatch(id -> Arrays.asList(1, 2).contains(id)) - ); - } - - @Test - public void givenImportedArticlesWhenFindAllByPublicationTimeBetweenThenArticles2And3Returned() - throws Exception { - List
result = repository.findAllByPublicationTimeBetween( - new SimpleDateFormat("HH:mm").parse("15:15"), - new SimpleDateFormat("HH:mm").parse("16:30") - ); - - assertEquals(2, result.size()); - assertTrue(result.stream() - .map(Article::getId) - .allMatch(id -> Arrays.asList(2, 3).contains(id)) - ); - } - - @Test - public void givenImportedArticlesWhenFindAllWithCreationDateTimeBeforeThenArticles2And3Returned() throws Exception { - List
result = repository.findAllWithCreationDateTimeBefore( - new SimpleDateFormat("yyyy-MM-dd HH:mm").parse("2017-12-15 10:00") - ); - - assertEquals(2, result.size()); - assertTrue(result.stream() - .map(Article::getId) - .allMatch(id -> Arrays.asList(2, 3).contains(id)) - ); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/ExtendedStudentRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/ExtendedStudentRepositoryIntegrationTest.java deleted file mode 100644 index 71f92c94ab..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/ExtendedStudentRepositoryIntegrationTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.boot.daos; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.List; - -import javax.annotation.Resource; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.Application; -import com.baeldung.boot.domain.Student; - -@RunWith(SpringRunner.class) -@ContextConfiguration(classes = {Application.class}) -@DirtiesContext -public class ExtendedStudentRepositoryIntegrationTest { - @Resource - private ExtendedStudentRepository extendedStudentRepository; - - @Before - public void setup() { - Student student = new Student(1, "john"); - extendedStudentRepository.save(student); - Student student2 = new Student(2, "johnson"); - extendedStudentRepository.save(student2); - Student student3 = new Student(3, "tom"); - extendedStudentRepository.save(student3); - } - - @Test - public void givenStudents_whenFindByName_thenGetOk() { - List students = extendedStudentRepository.findByAttributeContainsText("name", "john"); - assertThat(students.size()).isEqualTo(2); - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java deleted file mode 100644 index 5d73e261a4..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung.boot.daos; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; - -import java.math.BigDecimal; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.Application; -import com.baeldung.boot.domain.MerchandiseEntity; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes=Application.class) -public class InventoryRepositoryIntegrationTest { - - private static final String ORIGINAL_TITLE = "Pair of Pants"; - private static final String UPDATED_TITLE = "Branded Luxury Pants"; - private static final String UPDATED_BRAND = "Armani"; - private static final String ORIGINAL_SHORTS_TITLE = "Pair of Shorts"; - - @Autowired - private InventoryRepository repository; - - @Test - public void shouldCreateNewEntryInDB() { - MerchandiseEntity pants = new MerchandiseEntity(ORIGINAL_TITLE, BigDecimal.ONE); - pants = repository.save(pants); - - MerchandiseEntity shorts = new MerchandiseEntity(ORIGINAL_SHORTS_TITLE, new BigDecimal(3)); - shorts = repository.save(shorts); - - assertNotNull(pants.getId()); - assertNotNull(shorts.getId()); - assertNotEquals(pants.getId(), shorts.getId()); - } - - @Test - public void shouldUpdateExistingEntryInDB() { - MerchandiseEntity pants = new MerchandiseEntity(ORIGINAL_TITLE, BigDecimal.ONE); - pants = repository.save(pants); - - Long originalId = pants.getId(); - - pants.setTitle(UPDATED_TITLE); - pants.setPrice(BigDecimal.TEN); - pants.setBrand(UPDATED_BRAND); - - MerchandiseEntity result = repository.save(pants); - - assertEquals(originalId, result.getId()); - assertEquals(UPDATED_TITLE, result.getTitle()); - assertEquals(BigDecimal.TEN, result.getPrice()); - assertEquals(UPDATED_BRAND, result.getBrand()); - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/JpaRepositoriesIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/JpaRepositoriesIntegrationTest.java deleted file mode 100644 index 9e4b78dce3..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/JpaRepositoriesIntegrationTest.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.baeldung.boot.daos; - -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertFalse; -import static junit.framework.TestCase.assertNotNull; -import static junit.framework.TestCase.assertNull; -import static junit.framework.TestCase.assertTrue; - -import java.util.List; -import java.util.Optional; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.domain.Item; -import com.baeldung.boot.domain.ItemType; -import com.baeldung.boot.domain.Location; -import com.baeldung.boot.domain.Store; - -@RunWith(SpringRunner.class) -@DataJpaTest(properties="spring.datasource.data=classpath:import_entities.sql") -public class JpaRepositoriesIntegrationTest { - @Autowired - private LocationRepository locationRepository; - @Autowired - private StoreRepository storeRepository; - @Autowired - private ItemTypeRepository compositeRepository; - @Autowired - private ReadOnlyLocationRepository readOnlyRepository; - - @Test - public void whenSaveLocation_ThenGetSameLocation() { - Location location = new Location(); - location.setId(100L); - location.setCountry("Country H"); - location.setCity("City Hundred"); - location = locationRepository.saveAndFlush(location); - - Location otherLocation = locationRepository.getOne(location.getId()); - assertEquals("Country H", otherLocation.getCountry()); - assertEquals("City Hundred", otherLocation.getCity()); - - locationRepository.delete(otherLocation); - } - - @Test - public void givenLocationId_whenFindStores_thenGetStores() { - List stores = storeRepository.findStoreByLocationId(1L); - assertEquals(1, stores.size()); - } - - @Test - public void givenItemTypeId_whenDeleted_ThenItemTypeDeleted() { - Optional itemType = compositeRepository.findById(1L); - assertTrue(itemType.isPresent()); - compositeRepository.deleteCustom(itemType.get()); - itemType = compositeRepository.findById(1L); - assertFalse(itemType.isPresent()); - } - - @Test - public void givenItemId_whenUsingCustomRepo_ThenDeleteAppropriateEntity() { - Item item = compositeRepository.findItemById(1L); - assertNotNull(item); - compositeRepository.deleteCustom(item); - item = compositeRepository.findItemById(1L); - assertNull(item); - } - - @Test - public void givenItemAndItemType_WhenAmbiguousDeleteCalled_ThenItemTypeDeletedAndNotItem() { - Optional itemType = compositeRepository.findById(1L); - assertTrue(itemType.isPresent()); - Item item = compositeRepository.findItemById(2L); - assertNotNull(item); - - compositeRepository.findThenDelete(1L); - Optional sameItemType = compositeRepository.findById(1L); - assertFalse(sameItemType.isPresent()); - Item sameItem = compositeRepository.findItemById(2L); - assertNotNull(sameItem); - } - - @Test - public void whenCreatingReadOnlyRepo_thenHaveOnlyReadOnlyOperationsAvailable() { - Optional location = readOnlyRepository.findById(1L); - assertNotNull(location); - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java deleted file mode 100644 index b2581b8034..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java +++ /dev/null @@ -1,545 +0,0 @@ -package com.baeldung.boot.daos; - -import org.junit.After; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Sort; -import org.springframework.data.jpa.domain.JpaSort; -import org.springframework.data.mapping.PropertyReferenceException; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.boot.daos.user.UserRepository; -import com.baeldung.boot.domain.User; - -import javax.persistence.EntityManager; -import javax.persistence.Query; -import java.time.LocalDate; -import java.util.*; -import java.util.function.Predicate; -import java.util.stream.Stream; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.*; - -public class UserRepositoryCommon { - - final String USER_EMAIL = "email@example.com"; - final String USER_EMAIL2 = "email2@example.com"; - final String USER_EMAIL3 = "email3@example.com"; - final String USER_EMAIL4 = "email4@example.com"; - final Integer INACTIVE_STATUS = 0; - final Integer ACTIVE_STATUS = 1; - final String USER_EMAIL5 = "email5@example.com"; - final String USER_EMAIL6 = "email6@example.com"; - final String USER_NAME_ADAM = "Adam"; - final String USER_NAME_PETER = "Peter"; - - @Autowired - protected UserRepository userRepository; - @Autowired - private EntityManager entityManager; - - @Test - @Transactional - public void givenUsersWithSameNameInDB_WhenFindAllByName_ThenReturnStreamOfUsers() { - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setEmail(USER_EMAIL); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_ADAM); - user2.setEmail(USER_EMAIL2); - userRepository.save(user2); - - User user3 = new User(); - user3.setName(USER_NAME_ADAM); - user3.setEmail(USER_EMAIL3); - userRepository.save(user3); - - User user4 = new User(); - user4.setName("SAMPLE"); - user4.setEmail(USER_EMAIL4); - userRepository.save(user4); - - try (Stream foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) { - assertThat(foundUsersStream.count()).isEqualTo(3l); - } - } - - @Test - public void givenUsersInDB_WhenFindAllWithQueryAnnotation_ThenReturnCollectionWithActiveUsers() { - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setEmail(USER_EMAIL); - user1.setStatus(ACTIVE_STATUS); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_ADAM); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User user3 = new User(); - user3.setName(USER_NAME_ADAM); - user3.setEmail(USER_EMAIL3); - user3.setStatus(INACTIVE_STATUS); - userRepository.save(user3); - - Collection allActiveUsers = userRepository.findAllActiveUsers(); - - assertThat(allActiveUsers.size()).isEqualTo(2); - } - - @Test - public void givenUsersInDB_WhenFindAllWithQueryAnnotationNative_ThenReturnCollectionWithActiveUsers() { - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setEmail(USER_EMAIL); - user1.setStatus(ACTIVE_STATUS); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_ADAM); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User user3 = new User(); - user3.setName(USER_NAME_ADAM); - user3.setEmail(USER_EMAIL3); - user3.setStatus(INACTIVE_STATUS); - userRepository.save(user3); - - Collection allActiveUsers = userRepository.findAllActiveUsersNative(); - - assertThat(allActiveUsers.size()).isEqualTo(2); - } - - @Test - public void givenUserInDB_WhenFindUserByStatusWithQueryAnnotation_ThenReturnActiveUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByStatus(ACTIVE_STATUS); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUserInDB_WhenFindUserByStatusWithQueryAnnotationNative_ThenReturnActiveUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByStatusNative(ACTIVE_STATUS); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationIndexedParams_ThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByStatusAndName(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNamedParams_ThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByStatusAndNameNamedParams(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParams_ThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByStatusAndNameNamedParamsNative(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNames_ThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByUserStatusAndUserName(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationIndexedParams_ThenReturnUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByNameLike("Ad"); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationNamedParams_ThenReturnUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByNameLikeNamedParam("Ad"); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationNative_ThenReturnUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByNameLikeNative("Ad"); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindAllWithSortByName_ThenReturnUsersSorted() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - - List usersSortByName = userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); - - assertThat(usersSortByName.get(0) - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test(expected = PropertyReferenceException.class) - public void givenUsersInDB_WhenFindAllSortWithFunction_ThenThrowException() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - - userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); - - List usersSortByNameLength = userRepository.findAll(Sort.by("LENGTH(name)")); - - assertThat(usersSortByNameLength.get(0) - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindAllSortWithFunctionQueryAnnotationJPQL_ThenReturnUsersSorted() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - - userRepository.findAllUsers(Sort.by("name")); - - List usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)")); - - assertThat(usersSortByNameLength.get(0) - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindAllWithPageRequestQueryAnnotationJPQL_ThenReturnPageOfUsers() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL4, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS)); - - Page usersPage = userRepository.findAllUsersWithPagination(PageRequest.of(1, 3)); - - assertThat(usersPage.getContent() - .get(0) - .getName()).isEqualTo("SAMPLE1"); - } - - @Test - public void givenUsersInDB_WhenFindAllWithPageRequestQueryAnnotationNative_ThenReturnPageOfUsers() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL4, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS)); - - Page usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(PageRequest.of(1, 3)); - - assertThat(usersSortByNameLength.getContent() - .get(0) - .getName()).isEqualTo(USER_NAME_PETER); - } - - @Test - @Transactional - public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationJPQL_ThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); - - int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE"); - - assertThat(updatedUsersSize).isEqualTo(2); - } - - @Test - public void givenUsersInDB_WhenFindByEmailsWithDynamicQuery_ThenReturnCollection() { - - User user1 = new User(); - user1.setEmail(USER_EMAIL); - userRepository.save(user1); - - User user2 = new User(); - user2.setEmail(USER_EMAIL2); - userRepository.save(user2); - - User user3 = new User(); - user3.setEmail(USER_EMAIL3); - userRepository.save(user3); - - Set emails = new HashSet<>(); - emails.add(USER_EMAIL2); - emails.add(USER_EMAIL3); - - Collection usersWithEmails = userRepository.findUserByEmails(emails); - - assertThat(usersWithEmails.size()).isEqualTo(2); - } - - @Test - public void givenUsersInDBWhenFindByNameListReturnCollection() { - - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setEmail(USER_EMAIL); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - userRepository.save(user2); - - List names = Arrays.asList(USER_NAME_ADAM, USER_NAME_PETER); - - List usersWithNames = userRepository.findUserByNameList(names); - - assertThat(usersWithNames.size()).isEqualTo(2); - } - - - @Test - @Transactional - public void whenInsertedWithQuery_ThenUserIsPersisted() { - userRepository.insertUser(USER_NAME_ADAM, 1, USER_EMAIL, ACTIVE_STATUS, true); - userRepository.insertUser(USER_NAME_PETER, 1, USER_EMAIL2, ACTIVE_STATUS, true); - - User userAdam = userRepository.findUserByNameLike(USER_NAME_ADAM); - User userPeter = userRepository.findUserByNameLike(USER_NAME_PETER); - - assertThat(userAdam).isNotNull(); - assertThat(userAdam.getEmail()).isEqualTo(USER_EMAIL); - assertThat(userPeter).isNotNull(); - assertThat(userPeter.getEmail()).isEqualTo(USER_EMAIL2); - } - - - @Test - @Transactional - public void givenTwoUsers_whenFindByNameUsr01_ThenUserUsr01() { - User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.now(), "usr02@baeldung.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - try (Stream users = userRepository.findAllByName("usr01")) { - assertTrue(users.allMatch(usr -> usr.equals(usr01))); - } - } - - @Test - @Transactional - public void givenTwoUsers_whenFindByNameUsr00_ThenNoUsers() { - User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.now(), "usr02@baeldung.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - try (Stream users = userRepository.findAllByName("usr00")) { - assertEquals(0, users.count()); - } - } - - @Test - public void givenTwoUsers_whenFindUsersWithGmailAddress_ThenUserUsr02() { - User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.now(), "usr02@gmail.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - List users = userRepository.findUsersWithGmailAddress(); - assertEquals(1, users.size()); - assertEquals(usr02, users.get(0)); - } - - @Test - @Transactional - public void givenTwoUsers_whenDeleteAllByCreationDateAfter_ThenOneUserRemains() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - userRepository.deleteAllByCreationDateAfter(LocalDate.of(2018, 5, 1)); - - List users = userRepository.findAll(); - - assertEquals(1, users.size()); - assertEquals(usr01, users.get(0)); - } - - @Test - public void givenTwoUsers_whenFindAllUsersByPredicates_ThenUserUsr01() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - List> predicates = new ArrayList<>(); - predicates.add(usr -> usr.getCreationDate().isAfter(LocalDate.of(2017, 12, 31))); - predicates.add(usr -> usr.getEmail().endsWith(".com")); - - List users = userRepository.findAllUsersByPredicates(predicates); - - assertEquals(1, users.size()); - assertEquals(usr01, users.get(0)); - } - - @Test - @Transactional - public void givenTwoUsers_whenDeactivateUsersNotLoggedInSince_ThenUserUsr02Deactivated() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - usr01.setLastLoginDate(LocalDate.now()); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); - usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); - - userRepository.save(usr01); - userRepository.save(usr02); - - userRepository.deactivateUsersNotLoggedInSince(LocalDate.of(2018, 8, 1)); - - List users = userRepository.findAllUsers(Sort.by(Sort.Order.asc("name"))); - assertTrue(users.get(0).isActive()); - assertFalse(users.get(1).isActive()); - } - - @Test - @Transactional - public void givenTwoUsers_whenDeleteDeactivatedUsers_ThenUserUsr02Deleted() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - usr01.setLastLoginDate(LocalDate.now()); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.com", 0); - usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); - usr02.setActive(false); - - userRepository.save(usr01); - userRepository.save(usr02); - - int deletedUsersCount = userRepository.deleteDeactivatedUsers(); - - List users = userRepository.findAll(); - assertEquals(1, users.size()); - assertEquals(usr01, users.get(0)); - assertEquals(1, deletedUsersCount); - } - - @Test - @Transactional - public void givenTwoUsers_whenAddDeletedColumn_ThenUsersHaveDeletedColumn() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - usr01.setLastLoginDate(LocalDate.now()); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); - usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); - usr02.setActive(false); - - userRepository.save(usr01); - userRepository.save(usr02); - - userRepository.addDeletedColumn(); - - Query nativeQuery = entityManager.createNativeQuery("select deleted from USERS where NAME = 'usr01'"); - assertEquals(0, nativeQuery.getResultList().get(0)); - } - - @After - public void cleanUp() { - userRepository.deleteAll(); - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryIntegrationTest.java deleted file mode 100644 index 1b1d264574..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryIntegrationTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.boot.daos; - -import com.baeldung.boot.Application; -import com.baeldung.boot.domain.User; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; - -import java.time.LocalDate; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Created by adam. - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -@DirtiesContext -public class UserRepositoryIntegrationTest extends UserRepositoryCommon { - - @Test - @Transactional - public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationNativeThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); - userRepository.flush(); - - int updatedUsersSize = userRepository.updateUserSetStatusForNameNative(INACTIVE_STATUS, "SAMPLE"); - - assertThat(updatedUsersSize).isEqualTo(2); - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java deleted file mode 100644 index 99eabc8271..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.boot.daos; - -import com.baeldung.boot.Application; -import com.baeldung.boot.domain.User; -import com.baeldung.util.BaeldungPostgresqlContainer; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; -import org.testcontainers.containers.PostgreSQLContainer; - -import java.time.LocalDate; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Created by adam. - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -@ActiveProfiles({"tc", "tc-auto"}) -public class UserRepositoryTCAutoLiveTest extends UserRepositoryCommon { - - @ClassRule - public static PostgreSQLContainer postgreSQLContainer = BaeldungPostgresqlContainer.getInstance(); - - @Test - @Transactional - public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationNativePostgres_ThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); - userRepository.flush(); - - int updatedUsersSize = userRepository.updateUserSetStatusForNameNativePostgres(INACTIVE_STATUS, "SAMPLE"); - - assertThat(updatedUsersSize).isEqualTo(2); - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java deleted file mode 100644 index be8843c166..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.boot.daos; - -import com.baeldung.boot.Application; -import com.baeldung.boot.domain.User; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.util.TestPropertyValues; -import org.springframework.context.ApplicationContextInitializer; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; -import org.testcontainers.containers.PostgreSQLContainer; - -import java.time.LocalDate; - -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -@ActiveProfiles("tc") -@ContextConfiguration(initializers = {UserRepositoryTCLiveTest.Initializer.class}) -public class UserRepositoryTCLiveTest extends UserRepositoryCommon { - - @ClassRule - public static PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer("postgres:11.1") - .withDatabaseName("integration-tests-db") - .withUsername("sa") - .withPassword("sa"); - - @Test - @Transactional - public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationNative_ThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); - userRepository.flush(); - - int updatedUsersSize = userRepository.updateUserSetStatusForNameNativePostgres(INACTIVE_STATUS, "SAMPLE"); - - assertThat(updatedUsersSize).isEqualTo(2); - } - - static class Initializer - implements ApplicationContextInitializer { - public void initialize(ConfigurableApplicationContext configurableApplicationContext) { - TestPropertyValues.of( - "spring.datasource.url=" + postgreSQLContainer.getJdbcUrl(), - "spring.datasource.username=" + postgreSQLContainer.getUsername(), - "spring.datasource.password=" + postgreSQLContainer.getPassword() - ).applyTo(configurableApplicationContext.getEnvironment()); - } - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/Aggregate2EventsIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/Aggregate2EventsIntegrationTest.java deleted file mode 100644 index e76b932cb9..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/Aggregate2EventsIntegrationTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; - -import com.baeldung.boot.ddd.event.Aggregate2; -import com.baeldung.boot.ddd.event.Aggregate2Repository; -import com.baeldung.boot.ddd.event.DomainEvent; - -@SpringJUnitConfig -@SpringBootTest -class Aggregate2EventsIntegrationTest { - @MockBean - private TestEventHandler eventHandler; - @Autowired - private Aggregate2Repository repository; - - // @formatter:off - @DisplayName("given aggregate with @AfterDomainEventPublication," - + " when do domain operation and save twice," - + " then an event is published only for the first time") - // @formatter:on - @Test - void afterDomainEvents() { - // given - Aggregate2 aggregate = new Aggregate2(); - - // when - aggregate.domainOperation(); - repository.save(aggregate); - repository.save(aggregate); - - // then - verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); - } - - @BeforeEach - void beforeEach() { - repository.deleteAll(); - } - - // @formatter:off - @DisplayName("given aggregate with @DomainEvents," - + " when do domain operation and save," - + " then an event is published") - // @formatter:on - @Test - void domainEvents() { - // given - Aggregate2 aggregate = new Aggregate2(); - - // when - aggregate.domainOperation(); - repository.save(aggregate); - - // then - verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/Aggregate3EventsIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/Aggregate3EventsIntegrationTest.java deleted file mode 100644 index 4193e932ee..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/Aggregate3EventsIntegrationTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; - -import com.baeldung.boot.ddd.event.Aggregate3; -import com.baeldung.boot.ddd.event.Aggregate3Repository; -import com.baeldung.boot.ddd.event.DomainEvent; - -@SpringJUnitConfig -@SpringBootTest -class Aggregate3EventsIntegrationTest { - - @MockBean - private TestEventHandler eventHandler; - @Autowired - private Aggregate3Repository repository; - - // @formatter:off - @DisplayName("given aggregate extending AbstractAggregateRoot," - + " when do domain operation and save twice," - + " then an event is published only for the first time") - // @formatter:on - @Test - void afterDomainEvents() { - // given - Aggregate3 aggregate = new Aggregate3(); - - // when - aggregate.domainOperation(); - repository.save(aggregate); - repository.save(aggregate); - - // then - verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); - } - - // @formatter:off - @DisplayName("given aggregate extending AbstractAggregateRoot," - + " when do domain operation and save," - + " then an event is published") - // @formatter:on - @Test - void domainEvents() { - // given - Aggregate3 aggregate = new Aggregate3(); - - // when - aggregate.domainOperation(); - repository.save(aggregate); - - // then - verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/AggregateEventsIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/AggregateEventsIntegrationTest.java deleted file mode 100644 index ac607063b2..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/AggregateEventsIntegrationTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.baeldung.boot.ddd.event; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.TestConfiguration; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.context.annotation.Bean; -import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; - -import com.baeldung.boot.ddd.event.Aggregate; -import com.baeldung.boot.ddd.event.AggregateRepository; -import com.baeldung.boot.ddd.event.DomainEvent; -import com.baeldung.boot.ddd.event.DomainService; - -@SpringJUnitConfig -@SpringBootTest -class AggregateEventsIntegrationTest { - - @Autowired - private DomainService domainService; - - @MockBean - private TestEventHandler eventHandler; - @Autowired - private ApplicationEventPublisher eventPublisher; - @Autowired - private AggregateRepository repository; - - // @formatter:off - @DisplayName("given existing aggregate," - + " when do domain operation directly on aggregate," - + " then domain event is NOT published") - // @formatter:on - @Test - void aggregateEventsTest() { - Aggregate existingDomainEntity = new Aggregate(0, eventPublisher); - repository.save(existingDomainEntity); - - // when - repository.findById(existingDomainEntity.getId()) - .get() - .domainOperation(); - - // then - verifyZeroInteractions(eventHandler); - } - - @BeforeEach - void beforeEach() { - repository.deleteAll(); - } - - // @formatter:off - @DisplayName("given existing aggregate," - + " when do domain operation on service," - + " then domain event is published") - // @formatter:on - @Test - void serviceEventsTest() { - Aggregate existingDomainEntity = new Aggregate(1, eventPublisher); - repository.save(existingDomainEntity); - - // when - domainService.serviceDomainOperation(existingDomainEntity.getId()); - - // then - verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); - } - - @TestConfiguration - public static class TestConfig { - @Bean - public DomainService domainService(AggregateRepository repository, ApplicationEventPublisher eventPublisher) { - return new DomainService(repository, eventPublisher); - } - } - -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/TestEventHandler.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/TestEventHandler.java deleted file mode 100644 index 0f499834eb..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/TestEventHandler.java +++ /dev/null @@ -1,14 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -import org.springframework.transaction.event.TransactionalEventListener; - -import com.baeldung.boot.ddd.event.DomainEvent; - -interface TestEventHandler { - @TransactionalEventListener - void handleEvent(DomainEvent event); - -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/AbstractServicePersistenceIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/AbstractServicePersistenceIntegrationTest.java deleted file mode 100644 index bf0c85fca6..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/AbstractServicePersistenceIntegrationTest.java +++ /dev/null @@ -1,252 +0,0 @@ -package com.baeldung.boot.services; - -import com.baeldung.boot.domain.Foo; -import com.baeldung.boot.services.IOperations; -import com.baeldung.util.IDUtil; -import org.hamcrest.Matchers; -import org.junit.Ignore; -import org.junit.Test; -import org.springframework.dao.DataAccessException; - -import java.io.Serializable; -import java.util.List; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.*; - -public abstract class AbstractServicePersistenceIntegrationTest { - - // tests - - // find - one - - @Test - /**/public final void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoResourceIsReceived() { - // When - final Foo createdResource = getApi().findOne(IDUtil.randomPositiveLong()); - - // Then - assertNull(createdResource); - } - - @Test - public void givenResourceExists_whenResourceIsRetrieved_thenNoExceptions() { - final Foo existingResource = persistNewEntity(); - getApi().findOne(existingResource.getId()); - } - - @Test - public void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoExceptions() { - getApi().findOne(IDUtil.randomPositiveLong()); - } - - @Test - public void givenResourceExists_whenResourceIsRetrieved_thenTheResultIsNotNull() { - final Foo existingResource = persistNewEntity(); - final Foo retrievedResource = getApi().findOne(existingResource.getId()); - assertNotNull(retrievedResource); - } - - @Test - public void givenResourceExists_whenResourceIsRetrieved_thenResourceIsRetrievedCorrectly() { - final Foo existingResource = persistNewEntity(); - final Foo retrievedResource = getApi().findOne(existingResource.getId()); - assertEquals(existingResource, retrievedResource); - } - - // find - one - by name - - // find - all - - @Test - /**/public void whenAllResourcesAreRetrieved_thenNoExceptions() { - getApi().findAll(); - } - - @Test - /**/public void whenAllResourcesAreRetrieved_thenTheResultIsNotNull() { - final List resources = getApi().findAll(); - - assertNotNull(resources); - } - - @Test - /**/public void givenAtLeastOneResourceExists_whenAllResourcesAreRetrieved_thenRetrievedResourcesAreNotEmpty() { - persistNewEntity(); - - // When - final List allResources = getApi().findAll(); - - // Then - assertThat(allResources, not(Matchers. empty())); - } - - @Test - /**/public void givenAnResourceExists_whenAllResourcesAreRetrieved_thenTheExistingResourceIsIndeedAmongThem() { - final Foo existingResource = persistNewEntity(); - - final List resources = getApi().findAll(); - - assertThat(resources, hasItem(existingResource)); - } - - @Test - /**/public void whenAllResourcesAreRetrieved_thenResourcesHaveIds() { - persistNewEntity(); - - // When - final List allResources = getApi().findAll(); - - // Then - for (final Foo resource : allResources) { - assertNotNull(resource.getId()); - } - } - - // create - - @Test(expected = RuntimeException.class) - /**/public void whenNullResourceIsCreated_thenException() { - getApi().create(null); - } - - @Test - /**/public void whenResourceIsCreated_thenNoExceptions() { - persistNewEntity(); - } - - @Test - /**/public void whenResourceIsCreated_thenResourceIsRetrievable() { - final Foo existingResource = persistNewEntity(); - - assertNotNull(getApi().findOne(existingResource.getId())); - } - - @Test - /**/public void whenResourceIsCreated_thenSavedResourceIsEqualToOriginalResource() { - final Foo originalResource = createNewEntity(); - final Foo savedResource = getApi().create(originalResource); - - assertEquals(originalResource, savedResource); - } - - @Test(expected = RuntimeException.class) - public void whenResourceWithFailedConstraintsIsCreated_thenException() { - final Foo invalidResource = createNewEntity(); - invalidate(invalidResource); - - getApi().create(invalidResource); - } - - /** - * -- specific to the persistence engine - */ - @Test(expected = DataAccessException.class) - @Ignore("Hibernate simply ignores the id silently and still saved (tracking this)") - public void whenResourceWithIdIsCreated_thenDataAccessException() { - final Foo resourceWithId = createNewEntity(); - resourceWithId.setId(IDUtil.randomPositiveLong()); - - getApi().create(resourceWithId); - } - - // update - - @Test(expected = RuntimeException.class) - /**/public void whenNullResourceIsUpdated_thenException() { - getApi().update(null); - } - - @Test - /**/public void givenResourceExists_whenResourceIsUpdated_thenNoExceptions() { - // Given - final Foo existingResource = persistNewEntity(); - - // When - getApi().update(existingResource); - } - - /** - * - can also be the ConstraintViolationException which now occurs on the update operation will not be translated; as a consequence, it will be a TransactionSystemException - */ - @Test(expected = RuntimeException.class) - public void whenResourceIsUpdatedWithFailedConstraints_thenException() { - final Foo existingResource = persistNewEntity(); - invalidate(existingResource); - - getApi().update(existingResource); - } - - @Test - /**/public void givenResourceExists_whenResourceIsUpdated_thenUpdatesArePersisted() { - // Given - final Foo existingResource = persistNewEntity(); - - // When - change(existingResource); - getApi().update(existingResource); - - final Foo updatedResource = getApi().findOne(existingResource.getId()); - - // Then - assertEquals(existingResource, updatedResource); - } - - // delete - - // @Test(expected = RuntimeException.class) - // public void givenResourceDoesNotExists_whenResourceIsDeleted_thenException() { - // // When - // getApi().delete(IDUtil.randomPositiveLong()); - // } - // - // @Test(expected = RuntimeException.class) - // public void whenResourceIsDeletedByNegativeId_thenException() { - // // When - // getApi().delete(IDUtil.randomNegativeLong()); - // } - // - // @Test - // public void givenResourceExists_whenResourceIsDeleted_thenNoExceptions() { - // // Given - // final Foo existingResource = persistNewEntity(); - // - // // When - // getApi().delete(existingResource.getId()); - // } - // - // @Test - // /**/public final void givenResourceExists_whenResourceIsDeleted_thenResourceNoLongerExists() { - // // Given - // final Foo existingResource = persistNewEntity(); - // - // // When - // getApi().delete(existingResource.getId()); - // - // // Then - // assertNull(getApi().findOne(existingResource.getId())); - // } - - // template method - - protected Foo createNewEntity() { - return new Foo(randomAlphabetic(6)); - } - - protected abstract IOperations getApi(); - - private final void invalidate(final Foo entity) { - entity.setName(null); - } - - private final void change(final Foo entity) { - entity.setName(randomAlphabetic(6)); - } - - protected Foo persistNewEntity() { - return getApi().create(createNewEntity()); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/FooServicePersistenceIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/FooServicePersistenceIntegrationTest.java deleted file mode 100644 index 72de4918a2..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/FooServicePersistenceIntegrationTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.boot.services; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.junit.Assert.assertNotNull; - -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.dao.InvalidDataAccessApiUsageException; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.Application; -import com.baeldung.boot.domain.Foo; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes=Application.class) -public class FooServicePersistenceIntegrationTest extends AbstractServicePersistenceIntegrationTest { - - @Autowired - private IFooService service; - - // tests - - @Test - public final void whenContextIsBootstrapped_thenNoExceptions() { - // - } - - @Test - public final void whenEntityIsCreated_thenNoExceptions() { - service.create(new Foo(randomAlphabetic(6))); - } - - @Test(expected = DataIntegrityViolationException.class) - public final void whenInvalidEntityIsCreated_thenDataException() { - service.create(new Foo()); - } - - @Test(expected = DataIntegrityViolationException.class) - public final void whenEntityWithLongNameIsCreated_thenDataException() { - service.create(new Foo(randomAlphabetic(2048))); - } - - // custom Query method - - @Test - public final void givenUsingCustomQuery_whenRetrievingEntity_thenFound() { - final String name = randomAlphabetic(6); - service.create(new Foo(name)); - - final Foo retrievedByName = service.retrieveByName(name); - assertNotNull(retrievedByName); - } - - // work in progress - - @Test(expected = InvalidDataAccessApiUsageException.class) - @Ignore("Right now, persist has saveOrUpdate semantics, so this will no longer fail") - public final void whenSameEntityIsCreatedTwice_thenDataException() { - final Foo entity = new Foo(randomAlphabetic(8)); - service.create(entity); - service.create(entity); - } - - // API - - @Override - protected final IOperations getApi() { - return service; - } - -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/SpringDataJPABarAuditIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/SpringDataJPABarAuditIntegrationTest.java deleted file mode 100644 index 644d1ec805..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/SpringDataJPABarAuditIntegrationTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.boot.services; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.Application; -import com.baeldung.boot.domain.Bar; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes=Application.class) -public class SpringDataJPABarAuditIntegrationTest { - - private static Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class); - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - logger.info("setUpBeforeClass()"); - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - logger.info("tearDownAfterClass()"); - } - - @Autowired - @Qualifier("barSpringDataJpaService") - private IBarService barService; - - @Autowired - private EntityManagerFactory entityManagerFactory; - - private EntityManager em; - - @Before - public void setUp() throws Exception { - logger.info("setUp()"); - em = entityManagerFactory.createEntityManager(); - } - - @After - public void tearDown() throws Exception { - logger.info("tearDown()"); - em.close(); - } - - @Test - @WithMockUser(username = "tutorialuser") - public final void whenBarsModified_thenBarsAudited() { - Bar bar = new Bar("BAR1"); - barService.create(bar); - assertEquals(bar.getCreatedDate(), bar.getModifiedDate()); - assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy()); - bar.setName("BAR2"); - bar = barService.update(bar); - assertTrue(bar.getCreatedDate() < bar.getModifiedDate()); - assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy()); - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/multipledb/JpaMultipleDBIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/multipledb/JpaMultipleDBIntegrationTest.java deleted file mode 100644 index a1f4a3fa2c..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/multipledb/JpaMultipleDBIntegrationTest.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.baeldung.multipledb; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.Collections; -import java.util.Optional; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.EnableTransactionManagement; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.multipledb.dao.product.ProductRepository; -import com.baeldung.multipledb.dao.user.PossessionRepository; -import com.baeldung.multipledb.dao.user.UserRepository; -import com.baeldung.multipledb.model.product.Product; -import com.baeldung.multipledb.model.user.PossessionMultipleDB; -import com.baeldung.multipledb.model.user.UserMultipleDB; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes=MultipleDbApplication.class) -@EnableTransactionManagement -public class JpaMultipleDBIntegrationTest { - - @Autowired - private UserRepository userRepository; - - @Autowired - private PossessionRepository possessionRepository; - - @Autowired - private ProductRepository productRepository; - - // tests - - @Test - @Transactional("userTransactionManager") - public void whenCreatingUser_thenCreated() { - UserMultipleDB user = new UserMultipleDB(); - user.setName("John"); - user.setEmail("john@test.com"); - user.setAge(20); - PossessionMultipleDB p = new PossessionMultipleDB("sample"); - p = possessionRepository.save(p); - user.setPossessionList(Collections.singletonList(p)); - user = userRepository.save(user); - final Optional result = userRepository.findById(user.getId()); - assertTrue(result.isPresent()); - System.out.println(result.get().getPossessionList()); - assertEquals(1, result.get().getPossessionList().size()); - } - - @Test - @Transactional("userTransactionManager") - public void whenCreatingUsersWithSameEmail_thenRollback() { - UserMultipleDB user1 = new UserMultipleDB(); - user1.setName("John"); - user1.setEmail("john@test.com"); - user1.setAge(20); - user1 = userRepository.save(user1); - assertTrue(userRepository.findById(user1.getId()).isPresent()); - - UserMultipleDB user2 = new UserMultipleDB(); - user2.setName("Tom"); - user2.setEmail("john@test.com"); - user2.setAge(10); - try { - user2 = userRepository.save(user2); - userRepository.flush(); - fail("DataIntegrityViolationException should be thrown!"); - } catch (final DataIntegrityViolationException e) { - // Expected - } catch (final Exception e) { - fail("DataIntegrityViolationException should be thrown, instead got: " + e); - } - } - - @Test - @Transactional("productTransactionManager") - public void whenCreatingProduct_thenCreated() { - Product product = new Product(); - product.setName("Book"); - product.setId(2); - product.setPrice(20); - product = productRepository.save(product); - - assertTrue(productRepository.findById(product.getId()).isPresent()); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java deleted file mode 100644 index 9bfba61a3b..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java +++ /dev/null @@ -1,144 +0,0 @@ -package com.baeldung.multipledb; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.EnableTransactionManagement; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.multipledb.PersistenceProductConfiguration; -import com.baeldung.multipledb.dao.product.ProductRepository; -import com.baeldung.multipledb.model.product.Product; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes=MultipleDbApplication.class) -@EnableTransactionManagement -public class ProductRepositoryIntegrationTest { - - @Autowired - private ProductRepository productRepository; - - @Before - @Transactional("productTransactionManager") - public void setUp() { - productRepository.save(Product.from(1001, "Book", 21)); - productRepository.save(Product.from(1002, "Coffee", 10)); - productRepository.save(Product.from(1003, "Jeans", 30)); - productRepository.save(Product.from(1004, "Shirt", 32)); - productRepository.save(Product.from(1005, "Bacon", 10)); - } - - @Test - public void whenRequestingFirstPageOfSizeTwo_ThenReturnFirstPage() { - Pageable pageRequest = PageRequest.of(0, 2); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(2)); - assertTrue(result.stream() - .map(Product::getId) - .allMatch(id -> Arrays.asList(1001, 1002) - .contains(id))); - } - - @Test - public void whenRequestingSecondPageOfSizeTwo_ThenReturnSecondPage() { - Pageable pageRequest = PageRequest.of(1, 2); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(2)); - assertTrue(result.stream() - .map(Product::getId) - .allMatch(id -> Arrays.asList(1003, 1004) - .contains(id))); - } - - @Test - public void whenRequestingLastPage_ThenReturnLastPageWithRemData() { - Pageable pageRequest = PageRequest.of(2, 2); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(1)); - assertTrue(result.stream() - .map(Product::getId) - .allMatch(id -> Arrays.asList(1005) - .contains(id))); - } - - @Test - public void whenSortingByNameAscAndPaging_ThenReturnSortedPagedResult() { - Pageable pageRequest = PageRequest.of(0, 3, Sort.by("name")); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(3)); - assertThat(result.getContent() - .stream() - .map(Product::getId) - .collect(Collectors.toList()), equalTo(Arrays.asList(1005, 1001, 1002))); - - } - - @Test - public void whenSortingByPriceDescAndPaging_ThenReturnSortedPagedResult() { - Pageable pageRequest = PageRequest.of(0, 3, Sort.by("price") - .descending()); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(3)); - assertThat(result.getContent() - .stream() - .map(Product::getId) - .collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001))); - - } - - @Test - public void whenSortingByPriceDescAndNameAscAndPaging_ThenReturnSortedPagedResult() { - Pageable pageRequest = PageRequest.of(0, 5, Sort.by("price") - .descending() - .and(Sort.by("name"))); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(5)); - assertThat(result.getContent() - .stream() - .map(Product::getId) - .collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001, 1005, 1002))); - - } - - @Test - public void whenRequestingFirstPageOfSizeTwoUsingCustomMethod_ThenReturnFirstPage() { - Pageable pageRequest = PageRequest.of(0, 2); - - List result = productRepository.findAllByPrice(10, pageRequest); - - assertThat(result, hasSize(2)); - assertTrue(result.stream() - .map(Product::getId) - .allMatch(id -> Arrays.asList(1002, 1005) - .contains(id))); - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java deleted file mode 100644 index e5ad2dd448..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.util; - -import org.testcontainers.containers.PostgreSQLContainer; - -public class BaeldungPostgresqlContainer extends PostgreSQLContainer { - - private static final String IMAGE_VERSION = "postgres:11.1"; - - private static BaeldungPostgresqlContainer container; - - - private BaeldungPostgresqlContainer() { - super(IMAGE_VERSION); - } - - public static BaeldungPostgresqlContainer getInstance() { - if (container == null) { - container = new BaeldungPostgresqlContainer(); - } - return container; - } - - @Override - public void start() { - super.start(); - System.setProperty("DB_URL", container.getJdbcUrl()); - System.setProperty("DB_USERNAME", container.getUsername()); - System.setProperty("DB_PASSWORD", container.getPassword()); - } - - @Override - public void stop() { - //do nothing, JVM handles shut down - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/util/IDUtil.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/util/IDUtil.java deleted file mode 100644 index 45e72e046d..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/util/IDUtil.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.util; - -import java.util.Random; - -public final class IDUtil { - - private IDUtil() { - throw new AssertionError(); - } - - // API - - public static String randomPositiveLongAsString() { - return Long.toString(randomPositiveLong()); - } - - public static String randomNegativeLongAsString() { - return Long.toString(randomNegativeLong()); - } - - public static long randomPositiveLong() { - long id = new Random().nextLong() * 10000; - id = (id < 0) ? (-1 * id) : id; - return id; - } - - private static long randomNegativeLong() { - long id = new Random().nextLong() * 10000; - id = (id > 0) ? (-1 * id) : id; - return id; - } - -} diff --git a/persistence-modules/spring-data-jpa/src/test/resources/application-tc-auto.properties b/persistence-modules/spring-data-jpa/src/test/resources/application-tc-auto.properties deleted file mode 100644 index c3005d861f..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/resources/application-tc-auto.properties +++ /dev/null @@ -1,4 +0,0 @@ -# configuration for test containers testing -spring.datasource.url=${DB_URL} -spring.datasource.username=${DB_USERNAME} -spring.datasource.password=${DB_PASSWORD} diff --git a/persistence-modules/spring-data-jpa/src/test/resources/application-tc.properties b/persistence-modules/spring-data-jpa/src/test/resources/application-tc.properties deleted file mode 100644 index 3bf8693d53..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/resources/application-tc.properties +++ /dev/null @@ -1,4 +0,0 @@ -# configuration for Test Containers testing -spring.datasource.driver-class-name=org.postgresql.Driver -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false