1. 程式人生 > >springboot整合spring data jpa例項

springboot整合spring data jpa例項

這裡不多介紹jpa和springboot只做使用的實際配置 打好springboot專案之後配置資料來源

首先加入pom依賴

jpa,mysql,lombok(實體上加上@Data註解可以省去get,set,toString,等方法)

   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
   </dependency>
   <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
            <scope>runtime</scope>
    </dependency>

    <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
    </dependency>

第一步:資料來源連結配置和jpa相關配置

配置application.yml檔案的資料來源和jpa

spring:
  datasource:
    url: jdbc:mysql://172.20.94.39:3306/marketing?characterEncoding=utf-8&verifyServerCertificate=false&useSSL=false&requireSSL=false
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: marketing
    password: marketing
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    database: mysql

第二步:配置資料來源配置檔案

package com.renrenche.marketing.ads_scheduler.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
//此處是你dao檔案所在的包名
@EnableJpaRepositories("com.renrenche.marketing.ads_scheduler.dao")
@EnableTransactionManagement
public class DataSourceConfig {

    @Autowired
    private DataSource dataSource;
    @Value("${spring.jpa.hibernate.ddl-auto}")
    private String ddlAuto;
    @Value("${spring.jpa.show-sql}")
    private String showSql;
    @Primary
    @Bean
    public EntityManagerFactory entityManagerFactory() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        //此處com.example.*.model是你的java bean所在的包名
        factory.setPackagesToScan("com.renrenche.marketing.ads_scheduler.domain");
        factory.setDataSource(dataSource);

        Map<String, Object> jpaProperties = new HashMap<String, Object>();
        jpaProperties.put("hibernate.ejb.naming_strategy","org.hibernate.cfg.ImprovedNamingStrategy");
        jpaProperties.put("hibernate.jdbc.batch_size",50);
        //以下是配置自動建立表結構
        jpaProperties.put("hibernate.hbm2ddl.auto", ddlAuto);
        jpaProperties.put("hibernate.format_sql", "true");
        jpaProperties.put("hibernate.show_sql", showSql);
        jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
       

        factory.setJpaPropertyMap(jpaProperties);
        factory.afterPropertiesSet();
        return factory.getObject();
    }
    @Primary
    @Bean
    public PlatformTransactionManager transactionManager() {

        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory());
        return txManager;
    }
}

接下來就可以建立實體。利用實體配置直接在資料庫生成表結構

package com.renrenche.marketing.ads_scheduler.domain.sem;

import lombok.Data;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;

@Entity
@Table(name = "sem_channel")
@Data
public class SemChannelEntity implements Serializable {

    private static final long serialVersionUID = -5654459077990963779L;

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "channel_en")
    private String channelEn;

    @Column(name = "channel_cn")
    private String channelCn;

    @Column(name = "discription")
    private String discription;

    @Column(name = "status")
    private Integer status;

    @Column(name = "create_time")
    @CreationTimestamp
    private Date createTime;

    @UpdateTimestamp
    @Column(name = "update_time")
    private Date updateTime;
}

執行springboot專案即可在資料庫生成表

console控制檯列印日誌

建立成功,可以在庫裡看到建好的表