• SpringCloud使用jpa之传统方式


    不说废话,直接上代码:

    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>
    
        <groupId>com.shinho</groupId>
        <artifactId>dbmeta</artifactId>
        <version>0.0.1</version>
        <packaging>jar</packaging>
    
        <name>dbmeta</name>
        <description>Demo project for Spring Boot</description>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.0.1.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
            <spring-cloud.version>Finchley.M9</spring-cloud.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
            </dependency>
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-expression</artifactId>
                <version>4.3.14.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-rest</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>0.2.9</version>
            </dependency>
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-ehcache</artifactId>
                <version>5.2.16.Final</version>
            </dependency>
            <dependency>
                <groupId>net.sf.ehcache</groupId>
                <artifactId>ehcache</artifactId>
                <version>2.9.0</version>
            </dependency>
            <dependency>  
                <groupId>log4j</groupId>  
                <artifactId>log4j</artifactId>  
                <version>1.2.17</version>  
            </dependency> 
        </dependencies>
    
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-dependencies</artifactId>
                    <version>${spring-cloud.version}</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
            </dependencies>
        </dependencyManagement>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
        
        <repositories>
            <repository>
                <id>ali</id>
                <name>ali Repository</name>
                <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
                <snapshots>
                    <enabled>false</enabled>
                </snapshots>
            </repository>
            <repository>
                <id>spring-milestones</id>
                <name>Spring Milestones</name>
                <url>https://repo.spring.io/milestone</url>
                <snapshots>
                    <enabled>false</enabled>
                </snapshots>
            </repository>
            <repository>
                <id>clojars</id>
                <name>Clojars repository</name>
                <url>https://clojars.org/repo</url>
            </repository>
        </repositories>
    
    </project>

    application.yml

    eureka:
      client:
        serviceUrl:
          defaultZone: http://192.168.40.132:7087/eureka
    server:
      port: 7088
      
    spring:
      application:
        name: service-dbmeta
      datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        url: jdbc:mysql://127.0.0.1:3306/shbi?characterEncoding=utf8
        username: root
        password: root
        driverClassName: com.mysql.jdbc.Driver
        initialSize: 5
        minIdle: 5
        maxActive: 20
        maxWait: 60000
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT 1 FROM DUAL
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxPoolPreparedStatementPerConnectionSize: 20
        filters: stat,wall,log4j
        connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
        useGlobalDataSourceStat: true
      jpa:
        database: MYSQL
        show-sql: false
        generate-ddl: true
        hibernate:
          ddl-auto: create
          naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
        properties:
          hibernate:
            dialect: org.hibernate.dialect.MySQL5Dialect
            cache: 
              region.factory_class: org.hibernate.cache.ehcache.EhCacheRegionFactory
              provider_configuration_file_resource_path: ehcache.xml

    实体类Tables.java

    package com.shinho.entity;
    
    import java.io.Serializable;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    import org.hibernate.annotations.Cache;
    import org.hibernate.annotations.CacheConcurrencyStrategy;
    
    @Entity
    @Table(name="tables",catalog = "shbi")
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
    public class Tables implements Serializable{
        private static final long serialVersionUID = 1L;
        
        private int tableid;
        private String tablename;
        private int dbid;
        private String tabletext;
        
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "tableid", unique = true, nullable = false)
        public int getTableid() {
            return tableid;
        }
        
        public void setTableid(int tableid) {
            this.tableid = tableid;
        }
        
        @Column(name = "tablename", nullable = false)
        public String getTablename() {
            return tablename;
        }
        
        public void setTablename(String tablename) {
            this.tablename = tablename;
        }
        
        @Column(name = "dbid")
        public int getDbid() {
            return dbid;
        }
        
        public void setDbid(int dbid) {
            this.dbid = dbid;
        }
        
        @Column(name = "tabletext")
        public String getTabletext() {
            return tabletext;
        }
        
        public void setTabletext(String tabletext) {
            this.tabletext = tabletext;
        }
    }

    数据库访问层TablesDao.java

    package com.shinho.dao;
    
    import org.springframework.data.jpa.repository.Query;
    import org.springframework.data.repository.CrudRepository;
    
    import com.shinho.entity.Tables;
    
    
    public interface TablesDao extends CrudRepository<Tables, Integer> {
        
        @Query(value="select count(*) from props",nativeQuery=true)
        int getcount();
    }

    最后,执行类 DbmetaApplication.java

    package com.shinho;
    
    import org.apache.log4j.Logger;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    
    import com.shinho.dao.TablesDao;
    
    @Configuration
    @EnableAutoConfiguration
    @ComponentScan(basePackages={"com.shinho"})
    @EnableWebMvc
    @EnableEurekaClient
    @RestController
    public class DbmetaApplication {
        
        private static final Logger logger = Logger.getLogger(DbmetaApplication.class);
        
        public static void main(String[] args) {
            SpringApplication.run(DbmetaApplication.class, args);
        }
        
        @Value("${server.port}")
        String port;
        
        @RequestMapping("/hi")
        @Bean
        public String home(TablesDao dao) {
            logger.info("测试");
            int ishas = dao.getcount();
            return ishas+"";
        }
    }

    补充说明:

    1. 执行类上一定要加@EnableWebMvc,否则不好使。
    2. hibernate-ehcache的版本一定要和jpa里面的hibernate里面的一致,可以看pom文件的Dependency Hierarchy里面的。
    3. MySql里面Tables是个系统表,不要用这个名字。
  • 相关阅读:
    推荐一个网站设计方面的好网站
    验证错误时,让控件自动得到焦点
    VS中改变WebForm或WinFrom的默认视图
    页面回发时,如何保持ScrollBar的位置
    GridView中模板列的排序问题
    php中'mysqli not found'错误的解决方法
    使用ASP.NET 2.0 输出缓存替换的功能实现Donut Caching
    VS2005中自定义“在文件中查找”返回结果的样式
    document.getElementById("").style和$("").css(name,value)方法的区别?
    利用DebuggerDisplay特性得到更好的Debug体验
  • 原文地址:https://www.cnblogs.com/wpcnblog/p/8945218.html
Copyright © 2020-2023  润新知