spring cloud 搭建(JPA数据访问)

一,创建三层架构

首先,创建 model(实体层),dao(数据访问层),service(业务层)

都是如下方式:

spring cloud 搭建(JPA数据访问)_第1张图片

 

spring cloud 搭建(JPA数据访问)_第2张图片

如果创建的Moudel右键没有 Maven选项,

则通过如下“+”号处理

spring cloud 搭建(JPA数据访问)_第3张图片

 

二,mysql新增表

user表

spring cloud 搭建(JPA数据访问)_第4张图片

新增记录:

spring cloud 搭建(JPA数据访问)_第5张图片

 

对应的model层

使用了Lombok的@Data注解,省去get;set;

@Data
@Entity
@Table(name="user",catalog="testdb")
@DynamicUpdate
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id")
    private Integer id;
    @Column(name="name")
    private String name;
    @Column(name="pwd")
    private String pwd;
    @Column(name="age")
    private Integer age;
    @Column(name="createTime")
    private Date createTime;

}

 

三,配置 JPA 

首先,我们打开cloud-config

spring cloud 搭建(JPA数据访问)_第6张图片

config-dev.yml中我们新增:

1  数据库链接(datasource)

2  jpa

3  druid(连接池)

registry:
  url: http://${host:localhost}:9010/eureka/


# 测试属性
isDebug: true

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/testdb?serverTimezone=UTC
    username: root
    password: root
  jpa:
    generate-ddl: false
    hibernate:
      ddl-auto: none
    database: mysql
    show-sql: false
  resources:
    chain:
      strategy:
        content:
          enabled: true
          paths: /**

#druid connect pool
db:
  druid:
    url: ${spring.datasource.url}
    username: ${spring.datasource.username}
    password: ${spring.datasource.password}
    filters: stat,wall
    max-active: 60
    initial-size: 10
    max-wait: 60000
    min-idle: 10
    time-between-eviction-runs-millis: 600000
    min-evictable-idle-time-millis: 300000
    test-while-idle: true
    test-on-borrow: false
    test-on-return: false
    pool-prepared-statements: false
    max-open-prepared-statements: 20

 

四,JPA的Dao

打开dao层,新增config文件夹,

接着新增:

1 DruidProperties:这是读取刚才cloud-config新增的配置信息

2 JpaConfiguration:这个是我们Jpa配置类

 

DruidProperties:

package com.test.dao.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * @author Tyler
 * @date 2020/4/1
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "db.druid")
public class DruidProperties {

    private String url;
    private String username;
    private String password;
    private String filters;
    private String validationQuery;

    private int maxActive;
    private int initialSize;
    private int maxWait;
    private int minIdle;

    private long timeBetweenEvictionRunsMillis;
    private long minEvictableIdleTimeMillis;

    private boolean testWhileIdle;
    private boolean testOnBorrow;
    private boolean testOnReturn;

    private boolean poolPreparedStatements;
    private int maxOpenPreparedStatements;

}

 

JpaConfiguration:

大家修改对应的:

1  basePackages = "com.test.dao"

2  PACKAGES_TO_SCAN = "com.test.model";

3  UNIT_NAME = "test";

package com.test.dao.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.context.annotation.*;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.repository.query.QueryLookupStrategy;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.persistence.SharedCacheMode;
import javax.persistence.ValidationMode;
import javax.sql.DataSource;

/**
 * @author Tyler
 * @date 2020/4/1
 */
@Configuration
@EnableTransactionManagement(mode = AdviceMode.ASPECTJ)
@EnableJpaRepositories(basePackages = "com.test.dao", entityManagerFactoryRef = "entityManagerFactory",
        transactionManagerRef = "transactionManager", repositoryImplementationPostfix = "Impl",
        queryLookupStrategy = QueryLookupStrategy.Key.CREATE_IF_NOT_FOUND,
        includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = Repository.class) }
)
@EnableJpaAuditing
public class JpaConfiguration {
    private static final Logger logger = LoggerFactory.getLogger(JpaConfiguration.class);
    static final String PACKAGES_TO_SCAN = "com.test.model";
    static final String UNIT_NAME = "test";

    @Autowired
    private DruidProperties druid;
    @Autowired
    private JpaProperties jpa;


    //通过连接池管理数据源
    @Bean(name = "druidDataSource")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        try {
            dataSource.setUrl(druid.getUrl());
            dataSource.setUsername(druid.getUsername());
            dataSource.setPassword(druid.getPassword());
            dataSource.setMaxActive(druid.getMaxActive());
            dataSource.setInitialSize(druid.getInitialSize());
            dataSource.setMaxWait(druid.getMaxWait());
            dataSource.setMinIdle(druid.getMinIdle());
            dataSource.setValidationQuery(druid.getValidationQuery());
            dataSource.setTimeBetweenEvictionRunsMillis(druid.getTimeBetweenEvictionRunsMillis());
            dataSource.setMinEvictableIdleTimeMillis(druid.getMinEvictableIdleTimeMillis());
            dataSource.setTestWhileIdle(druid.isTestWhileIdle());
            dataSource.setTestOnBorrow(druid.isTestOnBorrow());
            dataSource.setTestOnReturn(druid.isTestOnReturn());
            dataSource.setPoolPreparedStatements(druid.isPoolPreparedStatements());
            dataSource.setMaxOpenPreparedStatements(druid.getMaxOpenPreparedStatements());
            dataSource.setFilters(druid.getFilters());
        } catch (Exception e) {

            e.printStackTrace();
        }
        return dataSource;
    }

    //类似hibernate sessionFactory
    @Bean(name = "entityManagerFactory")
    public EntityManagerFactory entityManagerFactory() {
        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        jpaVendorAdapter.setGenerateDdl(jpa.isGenerateDdl());
        jpaVendorAdapter.setShowSql(jpa.isShowSql());
        jpaVendorAdapter.setDatabase(jpa.getDatabase());
        jpaVendorAdapter.setDatabasePlatform(jpa.getDatabasePlatform());

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setDataSource(dataSource());
        factory.setPackagesToScan(PACKAGES_TO_SCAN);
        factory.setJpaVendorAdapter(jpaVendorAdapter);
        factory.setPersistenceUnitName(UNIT_NAME);
        factory.setSharedCacheMode(SharedCacheMode.ALL);
        factory.setValidationMode(ValidationMode.NONE);
        factory.afterPropertiesSet();
        return factory.getObject();
    }

    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager() {
        return new JpaTransactionManager(entityManagerFactory());
    }

}

 

pom:



    
        test.parent
        com.test
        1.0-SNAPSHOT
    
    4.0.0

    test.dao
    
        
            org.springframework.boot
            spring-boot-starter-data-jpa
            2.1.6.RELEASE
        
        
            com.test
            test.model
            1.0-SNAPSHOT
            compile
        
        
            org.springframework
            spring-context
            5.2.4.RELEASE
            compile
        
        
            mysql
            mysql-connector-java
            5.1.35
        
        
            com.alibaba
            druid
            1.1.10
        
    


 

UserDao:

package com.test.dao;

import com.test.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;


@Repository
public interface UserDao extends JpaRepository{
}

 

五,JPA的Service

UserService

public interface UserService {
    List Test();
}

UserServiceImpl

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao dao;

    public List Test()
    {
        List list=dao.findAll();
        return list;
    }
}

 

六,服务调用

在我们的服务(service1)中

1  Service1Application添加 scanBasePackages={"com.test"}扫描

@SpringBootApplication(scanBasePackages = {"com.test"})
@EnableEurekaClient
public class Service1Application {

    public static void main(String[] args) {
        SpringApplication.run(Service1Application.class, args);
    }

}

2  TestController调用

@RestController
@RequestMapping("test")
public class TestController {
    @Value("${isDebug}")
    private String isDebug;

    @Autowired
    private UserService service;

    @GetMapping(value = "/hello")
    public String hello(){
        return isDebug;
    }

    @GetMapping(value = "/test")
    public Integer test(){
        return service.Test().size();
    }
}

 

七,启动后,查看服务

spring cloud 搭建(JPA数据访问)_第7张图片

你可能感兴趣的:(spring,cloud,ORM,spring)