JAVA-32815 Split or move spring-data-jpa-simple (#16322)
Co-authored-by: timis1 <[email protected]>
This commit is contained in:
@@ -8,13 +8,10 @@ This module contains articles about Spring Data JPA that are also part of an Ebo
|
||||
Since this is a module tied to an e-book, it should **not** be moved or used to store the code for any further article.
|
||||
|
||||
### Relevant Articles
|
||||
- [Introduction to Spring Data JPA](https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa)
|
||||
- [Customizing the Result of JPA Queries with Aggregation Functions](https://www.baeldung.com/jpa-queries-custom-result-with-aggregation-functions)
|
||||
- [CrudRepository, JpaRepository, and PagingAndSortingRepository in Spring Data](https://www.baeldung.com/spring-data-repositories)
|
||||
- [New CRUD Repository Interfaces in Spring Data 3](https://www.baeldung.com/spring-data-3-crud-repository-interfaces)
|
||||
- [Derived Query Methods in Spring Data JPA Repositories](https://www.baeldung.com/spring-data-derived-queries)
|
||||
- [Spring Data JPA @Query](https://www.baeldung.com/spring-data-jpa-query)
|
||||
- [Spring Data JPA Projections](https://www.baeldung.com/spring-data-jpa-projections)
|
||||
- [Spring Data JPA @Modifying Annotation](https://www.baeldung.com/spring-data-jpa-modifying-annotation)
|
||||
- [Generate Database Schema with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-generate-db-schema)
|
||||
- [Pagination and Sorting using Spring Data JPA](https://www.baeldung.com/spring-data-jpa-pagination-sorting)
|
||||
- [Spring Data JPA @Modifying Annotation](https://www.baeldung.com/spring-data-jpa-modifying-annotation)
|
||||
@@ -43,21 +43,11 @@
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-oxm</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>jakarta.xml.bind</groupId>
|
||||
<artifactId>jakarta.xml.bind-api</artifactId>
|
||||
<version>${jakarta.xml.bind.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate.orm</groupId>
|
||||
<artifactId>hibernate-ant</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
package com.baeldung.jpa.paginationsorting;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication(scanBasePackages = "com.baeldung.jpa.paginationsorting")
|
||||
public class PaginationSortingApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(PaginationSortingApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
package com.baeldung.jpa.paginationsorting.config;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
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 com.google.common.base.Preconditions;
|
||||
|
||||
@Configuration
|
||||
@PropertySource({ "classpath:pagination-sorting-db.properties" })
|
||||
@EnableJpaRepositories(basePackages = "com.baeldung.jpa.paginationsorting", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager")
|
||||
public class PersistenceProductConfiguration {
|
||||
private final Environment env;
|
||||
|
||||
public PersistenceProductConfiguration(Environment env) {
|
||||
this.env = env;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocalContainerEntityManagerFactoryBean productEntityManager() {
|
||||
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
|
||||
em.setDataSource(productDataSource());
|
||||
em.setPackagesToScan("com.baeldung.jpa.paginationsorting");
|
||||
|
||||
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
||||
em.setJpaVendorAdapter(vendorAdapter);
|
||||
final HashMap<String, Object> properties = new HashMap<String, Object>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
-67
@@ -1,67 +0,0 @@
|
||||
package com.baeldung.jpa.paginationsorting.model;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.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();
|
||||
}
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.jpa.paginationsorting.repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
|
||||
import com.baeldung.jpa.paginationsorting.model.Product;
|
||||
|
||||
public interface ProductRepository extends PagingAndSortingRepository<Product, Integer>, CrudRepository<Product, Integer> {
|
||||
|
||||
List<Product> findAllByPrice(double price, Pageable pageable);
|
||||
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
package com.baeldung.jpa.schemageneration;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
|
||||
@SpringBootApplication
|
||||
@PropertySource("classpath:schema-generation.properties")
|
||||
public class AccountApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(AccountApplication.class, args);
|
||||
}
|
||||
}
|
||||
-40
@@ -1,40 +0,0 @@
|
||||
package com.baeldung.jpa.schemageneration;
|
||||
|
||||
import java.util.EnumSet;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
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 com.baeldung.jpa.schemageneration.model.Account;
|
||||
import com.baeldung.jpa.schemageneration.model.AccountSetting;
|
||||
|
||||
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<String, Object> 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);
|
||||
}
|
||||
}
|
||||
-75
@@ -1,75 +0,0 @@
|
||||
package com.baeldung.jpa.schemageneration.model;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@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<AccountSetting> 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<AccountSetting> getAccountSettings() {
|
||||
return accountSettings;
|
||||
}
|
||||
|
||||
public void setAccountSettings(List<AccountSetting> accountSettings) {
|
||||
this.accountSettings = accountSettings;
|
||||
}
|
||||
|
||||
public void addAccountSetting(AccountSetting setting) {
|
||||
this.accountSettings.add(setting);
|
||||
setting.setAccount(this);
|
||||
}
|
||||
}
|
||||
-68
@@ -1,68 +0,0 @@
|
||||
package com.baeldung.jpa.schemageneration.model;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.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;
|
||||
}
|
||||
}
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
package com.baeldung.jpa.schemageneration.repository;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
import com.baeldung.jpa.schemageneration.model.Account;
|
||||
|
||||
public interface AccountRepository extends CrudRepository<Account, Long> {
|
||||
Account findByName(String name);
|
||||
}
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
package com.baeldung.jpa.schemageneration.repository;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
import com.baeldung.jpa.schemageneration.model.AccountSetting;
|
||||
|
||||
public interface AccountSettingRepository extends CrudRepository<AccountSetting, Long> {
|
||||
|
||||
AccountSetting findByAccountId(Long accountId);
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.jpa.simple;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableJpaRepositories("com.baeldung.jpa.simple.repository")
|
||||
public class JpaApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(JpaApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
-75
@@ -1,75 +0,0 @@
|
||||
package com.baeldung.jpa.simple.config;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
|
||||
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 org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
|
||||
@Configuration
|
||||
@PropertySource("classpath:persistence.properties")
|
||||
@EnableTransactionManagement
|
||||
//@ImportResource("classpath*:*springDataConfig.xml")
|
||||
public class PersistenceConfig {
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
@Bean
|
||||
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
|
||||
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
|
||||
em.setDataSource(dataSource());
|
||||
em.setPackagesToScan("com.baeldung.jpa.simple.model");
|
||||
|
||||
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
||||
em.setJpaVendorAdapter(vendorAdapter);
|
||||
em.setJpaProperties(additionalProperties());
|
||||
|
||||
return em;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DataSource dataSource() {
|
||||
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
|
||||
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
|
||||
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
|
||||
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
|
||||
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
|
||||
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PlatformTransactionManager transactionManager() {
|
||||
final JpaTransactionManager transactionManager = new JpaTransactionManager();
|
||||
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
|
||||
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
|
||||
return new PersistenceExceptionTranslationPostProcessor();
|
||||
}
|
||||
|
||||
final Properties additionalProperties() {
|
||||
final Properties hibernateProperties = new Properties();
|
||||
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
|
||||
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
|
||||
|
||||
return hibernateProperties;
|
||||
}
|
||||
}
|
||||
-57
@@ -1,57 +0,0 @@
|
||||
package com.baeldung.jpa.simple.model;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Book {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
private String title;
|
||||
private String author;
|
||||
private String isbn;
|
||||
|
||||
public Book() {
|
||||
}
|
||||
|
||||
public Book(String title, String author, String isbn) {
|
||||
this.title = title;
|
||||
this.author = author;
|
||||
this.isbn = isbn;
|
||||
}
|
||||
|
||||
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 getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public void setAuthor(String author) {
|
||||
this.author = author;
|
||||
}
|
||||
|
||||
public String getIsbn() {
|
||||
return isbn;
|
||||
}
|
||||
|
||||
public void setIsbn(String isbn) {
|
||||
this.isbn = isbn;
|
||||
}
|
||||
}
|
||||
-77
@@ -1,77 +0,0 @@
|
||||
package com.baeldung.jpa.simple.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Foo implements Serializable {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private long id;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
|
||||
public Foo() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Foo(final String name) {
|
||||
super();
|
||||
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
-71
@@ -1,71 +0,0 @@
|
||||
package com.baeldung.jpa.simple.model;
|
||||
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@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;
|
||||
}
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
package com.baeldung.jpa.simple.repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.repository.ListCrudRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.baeldung.jpa.simple.model.Book;
|
||||
|
||||
@Repository
|
||||
public interface BookListRepository extends ListCrudRepository<Book, Long> {
|
||||
|
||||
List<Book> findBooksByAuthor(String author);
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
package com.baeldung.jpa.simple.repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.repository.ListCrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.baeldung.jpa.simple.model.Book;
|
||||
|
||||
@Repository
|
||||
public interface BookPagingAndSortingRepository extends PagingAndSortingRepository<Book, Long>, ListCrudRepository<Book, Long> {
|
||||
|
||||
List<Book> findBooksByAuthor(String author, Pageable pageable);
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.jpa.simple.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import com.baeldung.jpa.simple.model.Foo;
|
||||
|
||||
public interface IFooDAO extends JpaRepository<Foo, Long> {
|
||||
|
||||
Foo findByName(String name);
|
||||
|
||||
@Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)")
|
||||
Foo retrieveByName(@Param("name") String name);
|
||||
}
|
||||
-65
@@ -1,65 +0,0 @@
|
||||
package com.baeldung.jpa.simple.repository;
|
||||
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import com.baeldung.jpa.simple.model.User;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, Integer>, UserRepositoryCustom {
|
||||
|
||||
List<User> findByName(String name);
|
||||
|
||||
List<User> findByNameIs(String name);
|
||||
|
||||
List<User> findByNameEquals(String name);
|
||||
|
||||
List<User> findByNameIsNull();
|
||||
|
||||
List<User> findByNameNot(String name);
|
||||
|
||||
List<User> findByNameIsNot(String name);
|
||||
|
||||
List<User> findByNameStartingWith(String name);
|
||||
|
||||
List<User> findByNameEndingWith(String name);
|
||||
|
||||
List<User> findByNameContaining(String name);
|
||||
|
||||
List<User> findByNameLike(String name);
|
||||
|
||||
List<User> findByAgeLessThan(Integer age);
|
||||
|
||||
List<User> findByAgeLessThanEqual(Integer age);
|
||||
|
||||
List<User> findByAgeGreaterThan(Integer age);
|
||||
|
||||
List<User> findByAgeGreaterThanEqual(Integer age);
|
||||
|
||||
List<User> findByAgeBetween(Integer startAge, Integer endAge);
|
||||
|
||||
List<User> findByBirthDateAfter(ZonedDateTime birthDate);
|
||||
|
||||
List<User> findByBirthDateBefore(ZonedDateTime birthDate);
|
||||
|
||||
List<User> findByActiveTrue();
|
||||
|
||||
List<User> findByActiveFalse();
|
||||
|
||||
List<User> findByAgeIn(Collection<Integer> ages);
|
||||
|
||||
List<User> findByNameOrAge(String name, Integer age);
|
||||
|
||||
List<User> findByNameOrAgeAndActive(String name, Integer age, Boolean active);
|
||||
|
||||
List<User> findByNameOrderByName(String name);
|
||||
|
||||
List<User> findByNameOrderByNameDesc(String name);
|
||||
|
||||
List<User> findByNameIsNotNull();
|
||||
|
||||
List<User> findByNameOrderByNameAsc(String name);
|
||||
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
package com.baeldung.jpa.simple.repository;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import com.baeldung.jpa.simple.model.User;
|
||||
|
||||
public interface UserRepositoryCustom {
|
||||
|
||||
List<User> findUserByEmails(Set<String> emails);
|
||||
|
||||
List<User> findAllUsersByPredicates(Collection<Predicate<User>> predicates);
|
||||
|
||||
}
|
||||
-57
@@ -1,57 +0,0 @@
|
||||
package com.baeldung.jpa.simple.repository;
|
||||
|
||||
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 com.baeldung.jpa.simple.model.User;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.PersistenceContext;
|
||||
import jakarta.persistence.criteria.CriteriaBuilder;
|
||||
import jakarta.persistence.criteria.CriteriaQuery;
|
||||
import jakarta.persistence.criteria.Path;
|
||||
import jakarta.persistence.criteria.Predicate;
|
||||
import jakarta.persistence.criteria.Root;
|
||||
|
||||
public class UserRepositoryCustomImpl implements UserRepositoryCustom {
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Override
|
||||
public List<User> findUserByEmails(Set<String> emails) {
|
||||
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
|
||||
CriteriaQuery<User> query = cb.createQuery(User.class);
|
||||
Root<User> user = query.from(User.class);
|
||||
|
||||
Path<String> emailPath = user.get("email");
|
||||
|
||||
List<Predicate> 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<User> findAllUsersByPredicates(Collection<java.util.function.Predicate<User>> predicates) {
|
||||
List<User> allUsers = entityManager.createQuery("select u from User u", User.class)
|
||||
.getResultList();
|
||||
Stream<User> allUsersStream = allUsers.stream();
|
||||
for (java.util.function.Predicate<User> predicate : predicates) {
|
||||
allUsersStream = allUsersStream.filter(predicate);
|
||||
}
|
||||
|
||||
return allUsersStream.collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.jpa.simple.service;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.baeldung.jpa.simple.model.Foo;
|
||||
import com.baeldung.jpa.simple.repository.IFooDAO;
|
||||
|
||||
@Service
|
||||
public class FooService implements IFooService {
|
||||
|
||||
@Autowired
|
||||
private IFooDAO dao;
|
||||
|
||||
@Override
|
||||
public Foo create(Foo foo) {
|
||||
return dao.save(foo);
|
||||
}
|
||||
}
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
package com.baeldung.jpa.simple.service;
|
||||
|
||||
import com.baeldung.jpa.simple.model.Foo;
|
||||
|
||||
public interface IFooService {
|
||||
Foo create(Foo foo);
|
||||
}
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
# jdbc.X
|
||||
jdbc.driverClassName=org.h2.Driver
|
||||
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.hbm2ddl.auto=create-drop
|
||||
-1
@@ -1 +0,0 @@
|
||||
spring.jpa.properties.hibernate.globally_quoted_identifiers=true
|
||||
-139
@@ -1,139 +0,0 @@
|
||||
package com.baeldung.jpa.paginationsorting;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
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.transaction.annotation.EnableTransactionManagement;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.baeldung.jpa.paginationsorting.model.Product;
|
||||
import com.baeldung.jpa.paginationsorting.repository.ProductRepository;
|
||||
|
||||
@SpringBootTest(classes = PaginationSortingApplication.class)
|
||||
@EnableTransactionManagement
|
||||
class ProductRepositoryIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private ProductRepository productRepository;
|
||||
|
||||
@BeforeEach
|
||||
@Transactional("productTransactionManager")
|
||||
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
|
||||
void whenRequestingFirstPageOfSizeTwo_ThenReturnFirstPage() {
|
||||
Pageable pageRequest = PageRequest.of(0, 2);
|
||||
|
||||
Page<Product> result = productRepository.findAll(pageRequest);
|
||||
|
||||
assertThat(result.getContent(), hasSize(2));
|
||||
assertTrue(result.stream()
|
||||
.map(Product::getId)
|
||||
.allMatch(id -> Arrays.asList(1001, 1002)
|
||||
.contains(id)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenRequestingSecondPageOfSizeTwo_ThenReturnSecondPage() {
|
||||
Pageable pageRequest = PageRequest.of(1, 2);
|
||||
|
||||
Page<Product> result = productRepository.findAll(pageRequest);
|
||||
|
||||
assertThat(result.getContent(), hasSize(2));
|
||||
assertTrue(result.stream()
|
||||
.map(Product::getId)
|
||||
.allMatch(id -> Arrays.asList(1003, 1004)
|
||||
.contains(id)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenRequestingLastPage_ThenReturnLastPageWithRemData() {
|
||||
Pageable pageRequest = PageRequest.of(2, 2);
|
||||
|
||||
Page<Product> result = productRepository.findAll(pageRequest);
|
||||
|
||||
assertThat(result.getContent(), hasSize(1));
|
||||
assertTrue(result.stream()
|
||||
.map(Product::getId)
|
||||
.allMatch(id -> Arrays.asList(1005)
|
||||
.contains(id)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenSortingByNameAscAndPaging_ThenReturnSortedPagedResult() {
|
||||
Pageable pageRequest = PageRequest.of(0, 3, Sort.by("name"));
|
||||
|
||||
Page<Product> 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
|
||||
void whenSortingByPriceDescAndPaging_ThenReturnSortedPagedResult() {
|
||||
Pageable pageRequest = PageRequest.of(0, 3, Sort.by("price")
|
||||
.descending());
|
||||
|
||||
Page<Product> 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
|
||||
void whenSortingByPriceDescAndNameAscAndPaging_ThenReturnSortedPagedResult() {
|
||||
Pageable pageRequest = PageRequest.of(0, 5, Sort.by("price")
|
||||
.descending()
|
||||
.and(Sort.by("name")));
|
||||
|
||||
Page<Product> 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
|
||||
void whenRequestingFirstPageOfSizeTwoUsingCustomMethod_ThenReturnFirstPage() {
|
||||
Pageable pageRequest = PageRequest.of(0, 2);
|
||||
|
||||
List<Product> result = productRepository.findAllByPrice(10, pageRequest);
|
||||
|
||||
assertThat(result, hasSize(2));
|
||||
assertTrue(result.stream()
|
||||
.map(Product::getId)
|
||||
.allMatch(id -> Arrays.asList(1002, 1005)
|
||||
.contains(id)));
|
||||
}
|
||||
}
|
||||
-31
@@ -1,31 +0,0 @@
|
||||
package com.baeldung.jpa.simple;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import com.baeldung.jpa.simple.model.Book;
|
||||
import com.baeldung.jpa.simple.repository.BookListRepository;
|
||||
|
||||
@SpringBootTest(classes = JpaApplication.class)
|
||||
class BookListRepositoryIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private BookListRepository bookListRepository;
|
||||
|
||||
@Test
|
||||
void givenDbContainsBooks_whenFindBooksByAuthor_thenReturnBooksByAuthor() {
|
||||
Book book1 = new Book("Spring Data", "John Doe", "1234567890");
|
||||
Book book2 = new Book("Spring Data 2", "John Doe", "1234567891");
|
||||
Book book3 = new Book("Spring Data 3", "John Doe", "1234567892");
|
||||
bookListRepository.saveAll(Arrays.asList(book1, book2, book3));
|
||||
|
||||
List<Book> books = bookListRepository.findBooksByAuthor("John Doe");
|
||||
assertEquals(3, books.size());
|
||||
}
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package com.baeldung.jpa.simple;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
|
||||
import com.baeldung.jpa.simple.model.Book;
|
||||
import com.baeldung.jpa.simple.repository.BookPagingAndSortingRepository;
|
||||
|
||||
@SpringBootTest
|
||||
class BookPagingAndSortingRepositoryIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private BookPagingAndSortingRepository bookPagingAndSortingRepository;
|
||||
|
||||
@Test
|
||||
void givenDbContainsBooks_whenfindBooksByAuthor_thenReturnBooksByAuthor() {
|
||||
Book book1 = new Book("Spring Data", "John Miller", "1234567890");
|
||||
Book book2 = new Book("Spring Data 2", "John Miller", "1234567891");
|
||||
Book book3 = new Book("Spring Data 3", "John Miller", "1234567892");
|
||||
bookPagingAndSortingRepository.saveAll(Arrays.asList(book1, book2, book3));
|
||||
|
||||
Pageable pageable = PageRequest.of(0, 2, Sort.by("title").descending());
|
||||
List<Book> books = bookPagingAndSortingRepository.findBooksByAuthor("John Miller", pageable);
|
||||
assertEquals(2, books.size());
|
||||
assertEquals(book3.getId(), books.get(0).getId());
|
||||
assertEquals(book2.getId(), books.get(1).getId());
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user