有没有用SpringBoot+SpringDataJPA(底层用Hibernate)+Sharding-JDBC来进行数据库操作和分库分表的,有冲突吗,可行吗?70


大力踢外套
大力踢外套 2024-04-10 11:44:04 47190
分类专栏:问题 问题分类: 其它未定义问题
系统自动结题
2 个回答
  • 1843880570 进阶 2024-04-12 08:59:14
    在配置文件中加入数据库配置
     
    JPA的基本配置介绍
     
    validate:在加载hibernate时,验证创建数据库表结构。
    create:每次加载hibernate,重新创建数据库表结构,设置时要注意,如果设置错误的话,就会造成数据的丢失。
    create-drop:在加载的时候创建表,在关闭项目时删除表结构。
    update:加载时更新表结构。
    none:加载时不做任何操作。
    spring.jpa.show-sql配置 设置为true时,可以在控制台打印SQL。
    application.properties
     
    #DB Configuration:
    #数据库配置
     
    #数据库驱动
    spring.datasource.driverClassName=com.mysql.jdbc.Driver
    #数据库地址
    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
    #数据库用户名
    spring.datasource.username=root
    #数据库密码
    spring.datasource.password=123456
     
    #JPA Configuration:
    #JPA 配置
     
     
    spring.jpa.database=MySQL
    #控制台打印SQL
    spring.jpa.show-sql=true
    spring.jpa.generate-ddl=true
    spring.jpa.hibernate.ddl-auto=update
    spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
     
     
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    问题:
     
    Loading class com.mysql.jdbc.Driver'. This is deprecated. The new driver class iscom.mysql.cj.jdbc.Driver’. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
     
    application.properties要改
     
    #DB Configuration:
    #数据库配置
     
    #数据库驱动
    spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
    #数据库地址
    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
    #数据库用户名
    spring.datasource.username=root
    #数据库密码
    spring.datasource.password=123456
     
    #JPA Configuration:
    #JPA 配置
     
     
    spring.jpa.database=MySQL
    #控制台打印SQL
    spring.jpa.show-sql=true
    spring.jpa.generate-ddl=true
    spring.jpa.hibernate.ddl-auto=update
    spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
     
     
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    com.mysql.jdbc.Driver 高版本使用 com.mysql.cj.jdbc.Driver
     
    创建实体配置实体
    创建一个实体对象,在类上加入注解@Entity来表明这是一个实体类,
     
    在属性上使用@Id表明这是数据库中的主键ID,使用@GeneratedValue(strategy = GenerationType.IDENTITY)表明此字段自增长,在属性上加入@Column(nullable = false,unique = true)可以设置字段的一些属性,比如nullable为非空、unique唯一约束,还提供了其他属性等等。
     
    User.java
     
    package cn.liuawen.domain;
     
    import lombok.Data;
     
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
     
    @Entity
    @Data
    public class User {
        // 主键
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        // 用户名
        private String username;
        // 密码
        private String password;
    }
     
     
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    编写UserRepository
    创建数据操作层
     
    新建一个repository接口,使其继承JpaRepository,这个接口默认提供一组与JPA规范相关的方法
     
    UserRepository.java
     
    package cn.liuawen.repository;
     
    import cn.liuawen.domain.User;
    import org.springframework.data.jpa.repository.JpaRepository;
     
    import java.util.List;
     
     
    //实体、类型
    public interface UserRepository  extends JpaRepository<User,Long> {
        public List<User> findAll();
    }
     
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    来分析一波
     
    UserRepository 继承 JpaRepository<User,Long> 那JpaRepository<T, ID>是什么
     
    //
    // Source code recreated from a .class file by IntelliJ IDEA
    // (powered by Fernflower decompiler)
    //
     
    package org.springframework.data.jpa.repository;
     
    import java.util.List;
    import org.springframework.data.domain.Example;
    import org.springframework.data.domain.Sort;
    import org.springframework.data.repository.NoRepositoryBean;
    import org.springframework.data.repository.PagingAndSortingRepository;
    import org.springframework.data.repository.query.QueryByExampleExecutor;
     
    @NoRepositoryBean
    public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {
        List<T> findAll();
     
        List<T> findAll(Sort var1);
     
        List<T> findAllById(Iterable<ID> var1);
     
        <S extends T> List<S> saveAll(Iterable<S> var1);
     
        void flush();
     
        <S extends T> S saveAndFlush(S var1);
     
        void deleteInBatch(Iterable<T> var1);
     
        void deleteAllInBatch();
     
        T getOne(ID var1);
     
        <S extends T> List<S> findAll(Example<S> var1);
     
        <S extends T> List<S> findAll(Example<S> var1, Sort var2);
    }
     
     
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    从源代码中可以看到,默认为我们提供了很多简单的方法,如findAll()、getOne()等,而JpaRepository则继承了PagingAndSortingRepository接口。PagingAndSortingRepository接口代码其代码如下所示。
     
    //
    // Source code recreated from a .class file by IntelliJ IDEA
    // (powered by Fernflower decompiler)
    //
     
    package org.springframework.data.repository;
     
    import org.springframework.data.domain.Page;
    import org.springframework.data.domain.Pageable;
    import org.springframework.data.domain.Sort;
     
    @NoRepositoryBean
    public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> {
        Iterable<T> findAll(Sort var1);
     
        Page<T> findAll(Pageable var1);
    }
     
     
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    PagingAndSortingRepository接口继承了CrudRepository接口,实现了有关分页排序等相关的方法,其代码如下所示。
     
    //
    // Source code recreated from a .class file by IntelliJ IDEA
    // (powered by Fernflower decompiler)
    //
     
    package org.springframework.data.repository;
     
    import java.util.Optional;
     
    @NoRepositoryBean
    public interface CrudRepository<T, ID> extends Repository<T, ID> {
        <S extends T> S save(S var1);
     
        <S extends T> Iterable<S> saveAll(Iterable<S> var1);
     
        Optional<T> findById(ID var1);
     
        boolean existsById(ID var1);
     
        Iterable<T> findAll();
     
        Iterable<T> findAllById(Iterable<ID> var1);
     
        long count();
     
        void deleteById(ID var1);
     
        void delete(T var1);
     
        void deleteAll(Iterable<? extends T> var1);
     
        void deleteAll();
    }
     
     
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    CrudRepository接口继承了Spring Data JPA的核心接口Repository,实现了有关CRUD相关的方法(增、删、改、查)。在Repository接口中没有提供任何方法,仅仅作为一个标识来让其他类实现它作为仓库接口类,其代码如代码所示。
     
    //
    // Source code recreated from a .class file by IntelliJ IDEA
    // (powered by Fernflower decompiler)
    //
     
    package org.springframework.data.repository;
     
    import org.springframework.stereotype.Indexed;
     
    @Indexed
    public interface Repository<T, ID> {
    }
     
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    除了Repository接口以外,其余接口都含有一个@NoRepositoryBean注解,加入这个注解的类,Spring就不会实例化,用作父类的Repository。
     
    编写测试类
    简单测试运行
     
    package cn.liuawen;
     
    import cn.liuawen.domain.User;
    import cn.liuawen.repository.UserRepository;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
     
    import java.util.List;
     
     
    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = SpringbootJpaApplication.class)
    public class JpaTest {
        @Autowired
        private UserRepository userRepository;
     
        @Test
        public void test1(){
            List<User> users = userRepository.findAll();
            System.out.println(users);
        }
    }
     
     
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    在使用JPA操作数据库时,操作特别简单,基本上使用Repository提供的几个方法已经可以满足我们的需求。
     
    满足不了自己写SQL咯
     
    Error:
     
    Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
    2020-06-16 01:19:02.111 ERROR 18708 --- [           main] o.s.boot.SpringApplication               : Application run failed
     
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: 
     
    Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: 
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: 
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: com.mysql.jdbc.Driver
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
    a
     
     
     
    Caused by: java.lang.IllegalStateException: Cannot load driver class: com.mysql.jdbc.Driver
    at org.springframework.util.Assert.state(Assert.java:94) ~[spring-core-5.2.7.RELEASE.jar:5.2.7.RELEASE]
     
     
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    我没加MySQL的驱动
     
    <!-- MySQL连接驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    1
    2
    3
    4
    5
    Loading class com.mysql.jdbc.Driver'. This is deprecated. The new driver class iscom.mysql.cj.jdbc.Driver’. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
     
    高版本是 com.mysql.cj.jdbc.Driver
     
    控制台打印信息
     
     
    Hibernate: select user0_.id as id1_0_, user0_.password as password2_0_, user0_.username as username3_0_ from user user0_
    [User(id=1, username=菜鸡文, password=123), User(id=2, username=柳小子, password=123)]
     
    赞同 0 反对 0

  • prtyaa 新手 2024-04-17 10:41:08

    是的,使用Spring Boot、Spring Data JPA(底层使用Hibernate)和Sharding-JDBC来进行数据库操作是完全可行的。

    这种组合提供了强大的功能来构建高效、可扩展的微服务和数据库解决方案。下面是这种组合的一些主要特点和步骤:

    1.  

      Spring Boot:

       

       

       

       

        • Spring Boot是一个快速开发框架,它简化了Spring应用的初始搭建以及开发过程。

           

           

       

       

        • 通过Spring Boot,你可以快速创建一个基于Spring的应用程序,而无需编写大量的配置代码。

           

           

       

       

       

       

    2.  

      Spring Data JPA:

       

       

       

       

        • Spring Data JPA是基于JPA(Java Persistence API)的一个框架,它简化了数据库访问层的开发。

           

           

       

       

        • 通过定义接口和注解,你可以轻松地执行CRUD操作以及复杂的查询。

           

           

       

       

        • Spring Data JPA与Hibernate集成,Hibernate是JPA的一个实现,提供了对象关系映射(ORM)功能。

           

           

       

       

       

       

    3.  

      Sharding-JDBC:

       

       

       

       

        • Sharding-JDBC是一个轻量级的Java数据库分库分表中间件。

           

           

       

       

        • 它可以在Java的JDBC层进行数据库分片,支持水平分片和垂直分片,帮助你轻松构建分布式数据库系统。

           

           

       

       

        • 通过Sharding-JDBC,你可以将一个大的数据库拆分成多个小的数据库或表,以提高性能和可扩展性。

           

           

       

       

       

       

    使用这种组合的步骤大致如下:

    1.  

      创建Spring Boot项目: 使用Spring Initializr或你喜欢的IDE创建一个新的Spring Boot项目。

       

       

    2.  

      添加依赖: 在项目的pom.xml文件中添加Spring Boot、Spring Data JPA和Sharding-JDBC的相关依赖。

       

       

    3.  

      配置数据源和Sharding规则: 在application.propertiesapplication.yml文件中配置数据源信息以及Sharding规则。

       

       

    4.  

      定义实体和仓库接口: 使用JPA注解定义数据库表对应的实体类,并创建继承JpaRepositoryCrudRepository的接口来定义数据访问操作。

       

       

    5.  

      集成Sharding-JDBC: 配置Sharding-JDBC的相关规则,如分片策略、读写分离等。

       

       

    6.  

      编写业务逻辑: 在服务类中编写业务逻辑,使用仓库接口执行数据库操作。

       

       

    7.  

      运行和测试: 运行Spring Boot应用,并进行测试以确保一切正常工作。

       

       

    这种组合提供了高度的灵活性和可扩展性,可以帮助你构建高效、可靠的数据库访问层。当然,具体实现时还需要根据项目的实际需求进行详细的配置和开发。

    赞同 0 反对 0

    丫哈哈哈哈哈哈哈各个环节
大力踢外套进阶
粉丝 0 发表 12 + 关注 私信
上周热门
统信系统能生成某一指定文件夹下的所有文件列表吗  2772
统信系统有自己的字幕屏幕保护程序吗  2532
统信软件能支持pandas吗  2454
统信系统如何在保证自己数据安全的基础上,进行数据分析,比如使用pandas进行大数据分析  2443
安全与发展,统信系统是如何在两者之间权衡,满足用户高效办公的要求  2103
统信系统的数据安全机制是什么  1770
统信软件支持python为什么不支持安装pandas  1113
您好,我想问一下,就是这银河麒麟系统,背景黑屏怎么办啊,其他的都正常,就是没有背景,设置里面的背景一点击系统就不响应了怎么解决?  174
我想连接共享打印机可是,搜索驱动时候没有,怎么办  160
uos有支持活体检测的软件吗  149
本周热议
麒麟系统登录输入密码后又需要重新输入密码,确定密码正确。如何处理? 12
求麒麟系统下的Broadcom 802.11n 无线网卡驱动 10
银河麒麟桌面操作系统V10 SP1安装应用时会反复提示安全授权认证,如何才能取消呢? 10
统信UOS系统下安装HP打印机驱动问题 10
银河麒麟系统登录时用户名是中文,如何将输入法切换成中文进行登录? 9
如何在统信系统使用VFP? 9
使用正版软件承诺书每年一签有相关的政策文件吗? 8
银河麒麟系统安装软件需要密码授权,单用户模式修改密码不行,如何解决 8
uos系统怎么装了向日葵,向日葵打不开啊? 7
有偿使用中国长城信创运维工程师(初级)证书 7

加入交流群

请使用微信扫一扫!