• Spring boot hibernate Configuration Example


    1. pom.xml

    <?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
        http://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.5.RELEASE</version>
            <relativePath /> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.howtodoinjava.demo</groupId>
        <artifactId>SpringBoot2Demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>SpringBoot2Demo</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-web</artifactId>
            </dependency>
     
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
     
            <dependency>
                <groupId>com.h2database</groupId>
                <artifactId>h2</artifactId>
                <scope>runtime</scope>
            </dependency>
     
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
     
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
     
    </project>

    spring-boot-starter-data-jpa 包含了 spring data, hibernate, HikariCP, JPA API, JPA Implementation (默认为hibernate), JDBC和其他库.

     h2数据库应用

    2. Create JPA entity classes

    EmployeeEntity.java

    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Table;
     
    @Entity
    @Table(name="TBL_EMPLOYEES")
    public class EmployeeEntity {
     
        @Id
        @GeneratedValue
        private Long id;
         
        @Column(name="first_name")
        private String firstName;
         
        @Column(name="last_name")
        private String lastName;
         
        @Column(name="email", nullable=false, length=200)
        private String email;
         
        //Setters and getters left out for brevity.
     
        @Override
        public String toString() {
            return "EmployeeEntity [id=" + id + ", firstName=" + firstName +
                    ", lastName=" + lastName + ", email=" + email   + "]";
        }
    }

     @Entity  会让springboot自动扫描这个class

    @Table(name="TBL_EMPLOYEES") 初始化表名为 TBL_EMPLOYEES

    @id 标注table的id

    @GeneratedValue id值自动产生

    @Column 初始化表格列名

    3. Create JPA Repository

    继承JpaRepository接口

    EmployeeRepository.java

    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.stereotype.Repository;
     
    import com.howtodoinjava.demo.entity.EmployeeEntity;
     
    @Repository
    public interface EmployeeRepository extends JpaRepository<EmployeeEntity, Long> {
     
    }
    EmployeeEntity和id类型被指定作为 JpaRepository 参数。通过继承,EmployeeRepository就拥有存储、删除、查找Employee实体的功能了。

    4. Properties Configuration

    4.1. Data source

    数据库连接

    application.properties

    spring.datasource.url=jdbc:h2:file:~/test
    spring.datasource.driverClassName=org.h2.Driver
    spring.datasource.username=sa
    spring.datasource.password=
    spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
     
    # Enabling H2 Console
    spring.h2.console.enabled=true
     
    # Custom H2 Console URL
    spring.h2.console.path=/h2-console
    

     4.2. Hibernate print SQL and Logging

    application.properties

    #Turn Statistics on and log SQL stmts
     
    spring.jpa.show-sql=true
    spring.jpa.properties.hibernate.format_sql=true
     
    #If want to see very extensive logging
    spring.jpa.properties.hibernate.generate_statistics=true
    logging.level.org.hibernate.type=trace
    logging.level.org.hibernate.stat=debug
    

     4.3. Database Initialization

    除了@Table那种初始化数据库的表形式外,还有一种是使用schema.sql创建数据库表。

     --1

    application.properties

    spring.jpa.hibernate.ddl-auto=none // 使用schema.sql创建数据库表
    

    如:schema.sql

    DROP TABLE IF EXISTS TBL_EMPLOYEES;
      
    CREATE TABLE TBL_EMPLOYEES (
        id INT AUTO_INCREMENT  PRIMARY KEY,
        first_name VARCHAR(250) NOT NULL,
        last_name VARCHAR(250) NOT NULL,
        email VARCHAR(250) DEFAULT NULL
    );

     5. Spring boot hibernate demo

    SpringBoot2DemoApplication.java

    package com.howtodoinjava.demo;
     
    import java.util.Optional;
     
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
     
    import com.howtodoinjava.demo.entity.EmployeeEntity;
    import com.howtodoinjava.demo.repository.EmployeeRepository;
     
    @SpringBootApplication
    public class SpringBoot2DemoApplication implements CommandLineRunner {
     
        private Logger logger = LoggerFactory.getLogger(this.getClass());
         
        @Autowired
        EmployeeRepository repository;
         
        public static void main(String[] args) {
            SpringApplication.run(SpringBoot2DemoApplication.class, args);
        }
     
        @Override
        public void run(String... args) throws Exception
        {      
            Optional<EmployeeEntity> emp = repository.findById(2L);
     
            logger.info("Employee id 2 -> {}", emp.get());
        }
    }

     原文链接

    
    
    
  • 相关阅读:
    常用模块
    递归函数
    内置函数与匿名函数
    Mac控制台相关操作
    Maven相关知识记录
    @Import底层实现原理
    spring循环依赖
    springcloud注册中心对比
    分布式事务
    Drools使用注意事项
  • 原文地址:https://www.cnblogs.com/chenqr/p/11135993.html
Copyright © 2020-2023  润新知