В настоящее время интеграция Spring и JPA стала простой задачей благодаря Spring Boot и spring Data.
Я собираюсь настроить сервер postgresql
1
2
3
4
5
6
7
|
docker pull postgres #run the container docker run --name postgreslocal -e POSTGRES_PASSWORD=postgres -d postgres #get the ip docker inspect -- format '{{ .NetworkSettings.IPAddress }}' postgreslocal #get the port docker inspect -- format '{{ .NetworkSettings.Ports }}' postgreslocal |
Создать таблицу сотрудников
01
02
03
04
05
06
07
08
09
10
11
12
13
14
|
create schema spring_data_jpa_example; create table spring_data_jpa_example.employee( id SERIAL PRIMARY KEY, firstname TEXT NOT NULL, lastname TEXT NOT NULL, email TEXT not null , age INT NOT NULL, salary real, unique(email) ); insert into spring_data_jpa_example.employee (firstname,lastname,email,age,salary) |
Давайте начнем с нашего файла Gradle
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
group 'com.gkatzioura' version '1.0-SNAPSHOT' apply plugin: 'java' sourceCompatibility = 1.8 buildscript { repositories { mavenCentral() } dependencies { classpath( "org.springframework.boot:spring-boot-gradle-plugin:1.3.3.RELEASE" ) } } apply plugin: 'idea' apply plugin: 'spring-boot' repositories { mavenCentral() } dependencies { compile( "org.springframework.boot:spring-boot-starter-web" ) { exclude module: "spring-boot-starter-tomcat" } compile( "org.postgresql:postgresql:9.4-1206-jdbc42" ) compile( "org.springframework.boot:spring-boot-starter-jetty" ) compile( "org.springframework.boot:spring-boot-starter-data-jpa:1.3.3.RELEASE" ) compile( "com.mchange:c3p0:0.9.5.2" ) testCompile( "junit:junit:4.11" ); } |
Как вы видите, мы добавили пул соединений c3p0, spring-boot-starter-data-jpa для hibernate и драйвер postgres. Это все, что нам нужно.
Класс приложения
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
|
package com.gkatzioura.springdata.jpa; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; /** * Created by gkatzioura on 6/2/16. */ @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication springApplication = new SpringApplication(); ApplicationContext ctx = springApplication.run(Application. class , args); } } |
Конфигурация источника данных
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
package com.gkatzioura.springdata.jpa.config; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; /** * Created by gkatzioura on 6/2/16. */ @Configuration public class DataSourceConfig { @Bean public DataSource createDataSource() throws Exception { ComboPooledDataSource ds = new ComboPooledDataSource(); ds.setJdbcUrl( "jdbc:postgresql://172.17.0.3:5432/postgres?user=postgres&password=postgres" ); ds.setDriverClass( "org.postgresql.Driver" ); return ds; } } |
Конфигурация Jpa
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
package com.gkatzioura.springdata.jpa.config; import org.hibernate.jpa.HibernatePersistenceProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource; import java.util.Properties; /** * Created by gkatzioura on 6/2/16. */ @Configuration @EnableJpaRepositories (entityManagerFactoryRef = "entityManagerFactory" , transactionManagerRef = "transactionManager" , basePackages = { "com.gkatzioura.springdata.jpa.persistence" }) @EnableTransactionManagement public class JPAConfig { @Autowired private DataSource dataSource; @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); entityManagerFactoryBean.setDataSource(dataSource); entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider. class ); entityManagerFactoryBean.setJpaProperties(hibernateProperties()); entityManagerFactoryBean.setPackagesToScan( new String[] { "com.gkatzioura.springdata.jpa.persistence" }); return entityManagerFactoryBean; } @Bean public JpaTransactionManager transactionManager() { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); return transactionManager; } private Properties hibernateProperties() { Properties properties = new Properties(); properties.put( "hibernate.dialect" , "org.hibernate.dialect.PostgreSQL9Dialect" ); properties.put( "hibernate.globally_quoted_identifiers" , "true" ); return properties; } } |
Наша сущность за столом сотрудника
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
package com.gkatzioura.springdata.jpa.persistence.entity; import javax.persistence.*; /** * Created by gkatzioura on 6/2/16. */ @Entity @Table (name = "employee" , schema= "spring_data_jpa_example" ) public class Employee { @Id @Column (name = "id" ) @GeneratedValue (strategy = GenerationType.SEQUENCE) private Long id; @Column (name = "firstname" ) private String firstName; @Column (name = "lastname" ) private String lastname; @Column (name = "email" ) private String email; @Column (name = "age" ) private Integer age; @Column (name = "salary" ) private Integer salary; 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 String getEmail() { return email; } public void setEmail(String email) { this .email = email; } public Integer getAge() { return age; } public void setAge(Integer age) { this .age = age; } public Integer getSalary() { return salary; } public void setSalary(Integer salary) { this .salary = salary; } } |
Репозиторий, который поможет нам получить доступ ко всем пользователям
01
02
03
04
05
06
07
08
09
10
11
12
|
package com.gkatzioura.springdata.jpa.persistence.repository; import com.gkatzioura.springdata.jpa.persistence.entity.Employee; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * Created by gkatzioura on 6/2/16. */ @Repository public interface EmployeeRepository extends JpaRepository<Employee,Long>{ } |
И контроллер, который будет получать все данные
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
package com.gkatzioura.springdata.jpa.controller; import com.gkatzioura.springdata.jpa.persistence.entity.Employee; import com.gkatzioura.springdata.jpa.persistence.repository.EmployeeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * Created by gkatzioura on 6/2/16. */ @RestController public class TestController { @Autowired private EmployeeRepository employeeRepository; @RequestMapping ( "/employee" ) public List<Employee> getTest() { return employeeRepository.findAll(); } } |
Довольно удобно, учитывая зависимости и накладные расходы на конфигурацию XML в прошлом.
Вы можете найти исходный код на github .
Ссылка: | Интеграция Spring boot и Spring data JPA от нашего партнера JCG Эммануила Гкатзиураса в блоге gkatzioura . |