반응형

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
반응형

개발하다가 재기동과 새로고침을 아무리해도 적용이 되지 않는 경우가 있다.

2가지방법을 제안한다.

 

 

1. F12를 눌러보면 개발자 도구가 뜬다. 그 상태에서 새로고침 버튼을 우클릭하면 아래와 같이 된다.

캐시 비우기 및 강력 새로고침 하면 된다~

 

 

2. F12를 누른 후 빨간 네모인 Disable cache 에 체크를 한다.

 

끝.

반응형
반응형

https://penthegom.tistory.com/48

 

[Spring Boot]Spring MVC JSP 웹 튜토리얼(인텔리제이용 intelliJ) - 1

이 글에서는 스프링 부트 프레임 워크를 사용하여 스프링 MVC 웹 애플리케이션을 만들고 부트 스트랩하는 방법을 설명하겠다. JSP를 웹 애플리케이션의보기로 사용합니다. 이 응용 프로그램에 사용되는 도구 및 기..

penthegom.tistory.com

앞서 기본 Spring Boot MVC 를 만들어봤다. 이어서 이제 Mybatis와 PostgreSQL을 연결하는 방법을 설명하겠다.

이 응용 프로그램에 사용되는 도구 및 기술은 다음과 같다.

 

  • Spring Boot 2.1.x
  • Tomcat Embedded (Spring Boot 내장)
  • JavaSE 1.8
  • Maven
  • Mybatis
  • PostgreSQL 9.6.15
  • IntelliJ IDEA Ultimate 

 

프로젝트 구조(TREE)

1. DB설치 및 테이블 생성

Oracle, PostgreSQL, MySQL 등등 DB툴을 설치 해야한다. 여기서는 PostgreSQL을 사용하기로 한다.

이번 튜토리얼을 하기 위해 test라는 DB스키마를 생성한다.

 

1
2
3
4
5
6
7
8
CREATE TABLE test (
    id integer NOT NULL,
    name varchar NULL,
    CONSTRAINT test_pkey PRIMARY KEY (id)
);
 
INSERT INTO test (id, "name")
VALUES(1'펜다곰'),(2'홍길동');
cs

 

2. 각종 소스

 

- 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
65
66
67
68
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.penthegom.example</groupId>
    <artifactId>penthegomdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>penthegomdemo</name>
    <description>Demo project for Spring Boot</description>
 
    <properties>
        <java.version>1.8</java.version>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
 
        <!-- JSP -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
</project>
 
cs

 

- application.yml(application.properties 를 application.yml로 변경후 적읍시다! 한글주석과 트리형태로 관리가 됩니다.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
spring:
  mvc:
    view:
      prefix: /WEB-INF/views/
      suffix: .jsp
    static-path-pattern: /resources/**
  #DB 설정
  datasource:
    url: jdbc:postgresql://127.0.0.1:5432/tutorial
    driver-class-name: org.postgresql.Driver
   username: penthegom
   password: penthegom
  #JSP 바로적용 설정
  devtools:
    livereload:
      enabled: true
#로그 레벨
logging:
  level:
    # 쿼리 보기
    com.penthegom.example.penthegomdemo: DEBUG
 
cs

 

 

- DatabaseConfig.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
package com.penthegom.example.penthegomdemo.config;
 
import javax.sql.DataSource;
 
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;
 
@Configuration
@MapperScan(basePackages="com.penthegom.example.penthegomdemo.mapper")
@EnableTransactionManagement
public class DatabaseConfig {
 
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sessionFactory.setMapperLocations(resolver.getResources("classpath:mapper/postgresql/*.xml"));
        return sessionFactory.getObject();
    }
    
    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) throws Exception {
      final SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
      return sqlSessionTemplate;
    }
}
cs

 

- HelloController.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
package com.penthegom.example.penthegomdemo.controller;
 
import com.penthegom.example.penthegomdemo.dto.Test;
import com.penthegom.example.penthegomdemo.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
import java.util.List;
 
@Controller
public class HelloController {
 
    @Autowired
    TestService testService;
 
    @RequestMapping("/")
    public String index() {
 
        return "index";
    }
 
    @RequestMapping("/query")
    public @ResponseBody
    List<Test> query() throws Exception{
        return testService.getAll();
    }
}
 
cs

 

- Test.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.penthegom.example.penthegomdemo.dto;
 
public class Test {
    private String id;
    private String name;
 
    public String getId() {
        return id;
    }
 
    public void setId(String id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
}
cs

 

- TestMapper.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.penthegom.example.penthegomdemo.mapper;
 
import java.util.List;
 
import com.penthegom.example.penthegomdemo.dto.Test;
import org.springframework.stereotype.Repository;
 
@Repository
public interface TestMapper {
 
    public List<Test> getAll() throws Exception;
    
}
 
cs

 

- TestService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.penthegom.example.penthegomdemo.service;
 
import java.util.List;
 
import com.penthegom.example.penthegomdemo.dto.Test;
import com.penthegom.example.penthegomdemo.mapper.TestMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
 
@Service
public class TestService {
 
    @Autowired
    TestMapper testMapper;
    
    public List<Test> getAll() throws Exception{
        return testMapper.getAll();
    }
}
 
cs

 

- test.xml

1
2
3
4
5
6
7
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.penthegom.example.penthegomdemo.mapper.TestMapper">
    <select id="getAll" resultType="com.penthegom.example.penthegomdemo.dto.Test">
        SELECT * FROM test
    </select>
</mapper>
cs

 

3. 실행 결과

 

반응형

+ Recent posts