spring cloud 搭建(JPA数据访问)

Posted 正怒月神

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring cloud 搭建(JPA数据访问)相关的知识,希望对你有一定的参考价值。

一,创建三层架构

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

都是如下方式:

技术图片技术图片?

 

技术图片技术图片?

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

则通过如下“+”号处理

技术图片技术图片?

 

二,mysql新增表

user表

技术图片技术图片?

新增记录:

技术图片技术图片?

 

对应的model层

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

@Data
@Entity
@Table(name="user",catalog="testdb")
@DynamicUpdate
public class User {
    @Id
    @GeneratedValue(generator = "generator")
    @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

技术图片技术图片?

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:

<?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">
    <parent>
        <artifactId>test.parent</artifactId>
        <groupId>com.test</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>test.dao</artifactId>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <version>2.1.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.test</groupId>
            <artifactId>test.model</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.4.RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.35</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
    </dependencies>


</project>

 

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<User,Integer>{
}

 

 

五,JPA的Service

UserService

public interface UserService {
    List<User> Test();
}

技术图片

UserServiceImpl

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

    @Autowired
    UserDao dao;

    public List<User> Test()
    {
        List<User> 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数据访问)的主要内容,如果未能解决你的问题,请参考以下文章

Spring-data-Jpa项目搭建

Spring-Cloud、Hystrix 和 JPA - LazyInitializationException

使用Spring Data JPA访问关系型数据库

使用Spring Data JPA访问关系型数据库

Spring Data JPA

Spring Cloud 如何搭建Config