수색…


소개

이 스레드는 hibernate 및 thymyleaf 템플릿 엔진을 사용하여 스프링 부팅 응용 프로그램을 만드는 방법에 중점을 둡니다.

비고

또한 Thymeleaf 설명서를 확인하십시오.

Maven 종속성

이 예제는 스프링 부트 1.5.1.RELEASE를 기반으로합니다. 다음 종속성이 있습니다.

<!-- Spring -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<!-- H2 -->
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
</dependency>
<!-- Test -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

이 예제에서 우리는 Spring Boot JPA, Thymeleaf 및 웹 스타터를 사용할 것입니다. 나는 getter와 setter를 쉽게 생성하기 위해 Lombok을 사용하고 있지만 필수는 아닙니다. H2는 메모리를 구성하기 쉬운 데이터베이스로 사용됩니다.

최대 절전 모드 구성

첫째, Hibernate를 올바르게 설정하기 위해 우리가 필요로하는 것을 개괄적으로 살펴 보자.

  1. @EnableTransactionManagement@EnableJpaRepositories - 트랜잭션 관리와 스프링 데이터 저장소 사용을 원합니다.
  2. DataSource - 응용 프로그램의 기본 데이터 소스입니다. 이 예제에서는 메모리 내 h2를 사용합니다.
  3. LocalContainerEntityManagerFactoryBean - HibernateJpaVendorAdapter 사용하는 스프링 엔티티 관리자 팩토리.
  4. PlatformTransactionManager - 주석 처리 된 @Transactional 구성 요소의 주 트랜잭션 관리자입니다.

구성 파일 :

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.example.repositories")
public class PersistanceJpaConfig {
    
    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("org.h2.Driver");
        dataSource.setUrl("jdbc:h2:mem:testdb;mode=MySQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
        dataSource.setUsername("sa");
        dataSource.setPassword("");
        return dataSource;
    }
    
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource);
        em.setPackagesToScan(new String[] { "com.example.models" });
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalProperties());
        return em;
    }

    @Bean
    public PlatformTransactionManager transactionManager(LocalContainerEntityManagerFactoryBean entityManagerFactory, DataSource dataSource) {
        JpaTransactionManager tm = new JpaTransactionManager();
        tm.setEntityManagerFactory(entityManagerFactory.getObject());
        tm.setDataSource(dataSource);
        return tm;
    }

    Properties additionalProperties() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.hbm2ddl.auto", "update");
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
        return properties;
    }

}

엔티티 및 저장소

간단한 엔티티 : Lombok @Getter@Setter 주석을 사용하여 getter 및 setter 생성

@Entity
@Getter @Setter
public class Message {
    
    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    private String id;
    private String message;

}

나는 getters와 setters를 생성하기 위해 UUID 기반의 id와 lombok을 사용하고있다.

위 엔티티에 대한 간단한 저장소 :

@Transactional
public interface MessageRepository extends CrudRepository<Message, String> {
}

저장소에 대한 추가 정보 : spring data docs

엔터티가 em.setPackagesToScan ( LocalContainerEntityManagerFactoryBean 빈에 정의 됨)에 매핑 된 패키지와 basePackages ( @EnableJpaRepositories 주석에 정의 됨)에 매핑 된 패키지에있는 리포지토리에 있는지 확인합니다.

Thymeleaf 리소스 및 스프링 컨트롤러

Thymeleaf 템플릿을 노출하려면 컨트롤러를 정의해야합니다.

예:

@Controller
@RequestMapping("/")
public class MessageController {
    
    @Autowired
    private MessageRepository messageRepository;
    
    @GetMapping
    public ModelAndView index() {
        Iterable<Message> messages = messageRepository.findAll();
        return new ModelAndView("index", "index", messages);
    }
    
}

이 간단한 컨트롤러는 MessageRepository 삽입하고 모든 메시지를 src/main/resources/templates 있는 index.html 이라는 템플릿 파일에 전달하고 마지막으로 /index 에 노출합니다.

같은 방법으로 다른 템플릿을 templates 폴더 (기본적으로 spring src/main/resources/templates )에 배치하고 모델을 전달하여 클라이언트에 제공 할 수 있습니다.

다른 정적 리소스는 다음 폴더 중 하나에 있어야하며 기본적으로 스프링 부팅시 노출됩니다.

/META-INF/resources/
/resources/
/static/
/public/

Thymeleaf index.html 예 :

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head th:fragment="head (title)">
        <title th:text="${title}">Index</title>
        <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}" href="../../css/bootstrap.min.css" />
    </head>
    <body>
        <nav class="navbar navbar-default navbar-fixed-top">
          <div class="container-fluid">
            <div class="navbar-header">
              <a class="navbar-brand" href="#">Thymeleaf</a>
            </div>
          </div>
        </nav>
        <div class="container">
            <ul class="nav">
                <li><a th:href="@{/}" href="messages.html"> Messages </a></li>
            </ul>
        </div>
    </body>
</html>
  • bootstrap.min.csssrc/main/resources/static/css 폴더에 있습니다. @{} 구문을 사용하여 상대 경로를 사용하여 다른 정적 리소스를 얻을 수 있습니다.


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow