Java Persistence API (일명 JPA)는 객체와 관계 데이터베이스 간의 데이터를 관리, 유지 및 액세스하기위한 Java 사양입니다. 최대 절전 모드는 JPA 사양을 구현하는 ORM (Object Relational Mapping) 도구입니다.
이 예에서는 Hibernate를 퍼시스턴스 제공자로 사용하여 Spring을 JPA와 통합하는 방법을 학습합니다.
이 응용 프로그램에 사용되는 도구 및 기술은 다음과 같습니다.
- Spring 4.3.7.RELEASE
- Hibernate 5.2.9.Final
- JPA 2.1
- MySQL Connector 6.0.5
- MySQL Server 5.7.12
- Eclipse Neon.3
- Maven 3.3.9
- JavaSE 1.8
Spring, Hibernate 및 JPA를 사용하여 간단한 독립형 애플리케이션을 작성해 봅시다.
프로젝트 구조
다음 maven 프로젝트 구조를 검토하십시오.
배우기- 이클립스에서 maven 프로젝트를 만드는 방법 .
Jar dependencies
pom.xml파일을 편집 하고 다음과 같이 Spring, Hibernate 및 MySQL 종속성을 추가 하십시오 .
pom.xml
1
2
3
4
5
6
7
8
9
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
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.boraji.tutorial.hibernate</groupId>
<artifactId>spring-hibernate-jpa-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-hibernate-jpa-tutorial</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- Spring Context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- Spring ORM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- Mysql Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
<!-- Hibernate 5.2.9 Final -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.9.Final</version>
</dependency>
<!-- Apache Commons DBCP -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
|
cs |
JPA Entity class
다음과 같이 패키지 @Entity아래 에 클래스를 작성하십시오 com.boraji.tutorial.spring.entity.
Person.java
1
2
3
4
5
6
7
8
9
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
|
package com.boraji.tutorial.spring.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "PERSONS")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "FIRST_NAME")
private String firstName;
@Column(name = "LAST_NAME")
private String lastName;
@Column(name = "EMAIL")
private String email;
public Person() {}
public Person(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
// Getter and Setter methods
}
|
cs |
Data Access Object (DAO) class
다음과 같이 패키지 @Repository 아래에 클래스를 작성하십시오 com.boraji.tutorial.spring.dao.
PersonDao.java
1
2
3
4
5
6
7
8
9
10
|
package com.boraji.tutorial.spring.dao;
import java.util.List;
import com.boraji.tutorial.spring.entity.Person;
public interface PersonDao {
void add(Person person);
List<Person> listPersons();
}
|
cs |
PersonDaoImp.java
1
2
3
4
5
6
7
8
9
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
|
package com.boraji.tutorial.spring.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.springframework.stereotype.Repository;
import com.boraji.tutorial.spring.entity.Person;
/**
* @author imssbora
*
*/
@Repository
public class PersonDaoImp implements PersonDao {
@PersistenceContext
private EntityManager em;
@Override
public void add(Person person) {
em.persist(person);
}
@Override
public List<Person> listPersons() {
CriteriaQuery<Person> criteriaQuery = em.getCriteriaBuilder().createQuery(Person.class);
@SuppressWarnings("unused")
Root<Person> root = criteriaQuery.from(Person.class);
return em.createQuery(criteriaQuery).getResultList();
}
}
|
cs |
@PersistenceContext주석은 주입하는 데 사용됩니다 EntityManagerDOA 클래스로 객체를.
Service class
다음과 같이 패키지 @Service 아래에 클래스를 작성하십시오 com.boraji.tutorial.spring.service.
PersonService.java
1
2
3
4
5
6
7
8
9
10
|
package com.boraji.tutorial.spring.service;
import java.util.List;
import com.boraji.tutorial.spring.entity.Person;
public interface PersonService {
void add(Person person);
List<Person> listPersons();
}
|
cs |
PersonServiceImp.java
1
2
3
4
5
6
7
8
9
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
|
package com.boraji.tutorial.spring.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.boraji.tutorial.spring.dao.PersonDao;
import com.boraji.tutorial.spring.entity.Person;
/**
* @author imssbora
*
*/
@Service
public class PersonServiceImp implements PersonService {
@Autowired
private PersonDao userDao;
@Transactional
@Override
public void add(Person person) {
userDao.add(person);
}
@Transactional(readOnly = true)
@Override
public List<Person> listPersons() {
return userDao.listPersons();
}
}
|
cs |
persistence.xml 파일
폴더 persistence.xml아래 에 파일을 src/main/java/META-INF작성하고 다음 코드를 작성하십시오.
persistence.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="LOCAL_PERSISTENCE">
<description> Spring Hibernate JPA Configuration Example</description>
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/BORAJI" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="admin" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
|
cs |
이것은 persistence.xml를 구성하는 데 사용되는 EntityManager응용 프로그램 서버 또는 독립 실행 형 응용 프로그램 내에서. 데이터베이스 (연결 URL, 사용자 이름, 비밀번호 등) 및 ORM 관련 정보가 들어 있습니다.
Spring configuration
패키지 @Configuration 아래에 클래스를 만듭니다 com.boraji.tutorial.spring.config.
@EnableTransactionManagement 트랜잭션 관리 기능을 사용하려면 주석으로이 구성 클래스에 주석을 답니다 .
AppConfig.java
1
2
3
4
5
6
7
8
9
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
|
package com.boraji.tutorial.spring.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalEntityManagerFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @author imssbora
*
*/
@Configuration
@EnableTransactionManagement
@ComponentScans(value = { @ComponentScan("com.boraji.tutorial.spring.dao"),
@ComponentScan("com.boraji.tutorial.spring.service") })
public class AppConfig {
@Bean
public LocalEntityManagerFactoryBean geEntityManagerFactoryBean() {
LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean();
factoryBean.setPersistenceUnitName("LOCAL_PERSISTENCE");
return factoryBean;
}
@Bean
public JpaTransactionManager geJpaTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(geEntityManagerFactoryBean().getObject());
return transactionManager;
}
}
|
cs |
Run application
위의 spring-hibernate-jpa 구성을 테스트 할 기본 클래스를 작성하십시오.
MainApp.java
1
2
3
4
5
6
7
8
9
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
|
package com.boraji.tutorial.spring;
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.boraji.tutorial.spring.config.AppConfig;
import com.boraji.tutorial.spring.entity.Person;
import com.boraji.tutorial.spring.service.PersonService;
/**
* @author imssbora
*
*/
public class MainApp {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
PersonService personService = context.getBean(PersonService.class);
// Add Persons
personService.add(new Person("Sunil", "Bora", "suni.bora@example.com"));
personService.add(new Person("David", "Miller", "david.miller@example.com"));
personService.add(new Person("Sameer", "Singh", "sameer.singh@example.com"));
personService.add(new Person("Paul", "Smith", "paul.smith@example.com"));
// Get Persons
List<Person> persons = personService.listPersons();
for (Person person : persons) {
System.out.println("Id = "+person.getId());
System.out.println("First Name = "+person.getFirstName());
System.out.println("Last Name = "+person.getLastName());
System.out.println("Email = "+person.getEmail());
System.out.println();
}
context.close();
}
}
|
cs |
Output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
Hibernate: create table PERSONS (id bigint not null auto_increment, EMAIL varchar(255), FIRST_NAME varchar(255), LAST_NAME varchar(255), primary key (id)) engine=MyISAM
Hibernate: insert into PERSONS (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)
Hibernate: insert into PERSONS (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)
Hibernate: insert into PERSONS (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)
Hibernate: insert into PERSONS (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)
Hibernate: select person0_.id as id1_0_, person0_.EMAIL as EMAIL2_0_, person0_.FIRST_NAME as FIRST_NA3_0_, person0_.LAST_NAME as LAST_NAM4_0_ from PERSONS person0_
Id = 1
First Name = Sunil
Last Name = Bora
Email = suni.bora@example.com
Id = 2
First Name = David
Last Name = Miller
Email = david.miller@example.com
Id = 3
First Name = Sameer
Last Name = Singh
Email = sameer.singh@example.com
Id = 4
First Name = Paul
Last Name = Smith
Email = paul.smith@example.com
|
cs |
Download Sources
spring-hibernate-jpa-example.zip18.19 KB
'JAVA/SPRING > SPRING' 카테고리의 다른 글
Spring Framework: annotation 정리 (0) | 2017.12.04 |
---|---|
Spring Web MVC, @Controller 어노테이션 정리 (0) | 2017.12.04 |