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


大力踢外套
大力踢外套 2024-04-10 11:44:04 47188
分类专栏: 问题

网站声明:如果转载,请联系本站管理员。否则一切后果自行承担。

本文链接:https://www.xckfsq.com/news/show.html?id=53198
赞同 0
评论 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
    回复

    丫哈哈哈哈哈哈哈各个环节
大力踢外套L1
粉丝 0 发表 12 + 关注 私信
上周热门
如何使用 StarRocks 管理和优化数据湖中的数据?  2959
【软件正版化】软件正版化工作要点  2878
统信UOS试玩黑神话:悟空  2843
信刻光盘安全隔离与信息交换系统  2737
镜舟科技与中启乘数科技达成战略合作,共筑数据服务新生态  1270
grub引导程序无法找到指定设备和分区  1235
华为全联接大会2024丨软通动力分论坛精彩议程抢先看!  165
点击报名 | 京东2025校招进校行程预告  164
2024海洋能源产业融合发展论坛暨博览会同期活动-海洋能源与数字化智能化论坛成功举办  163
华为纯血鸿蒙正式版9月底见!但Mate 70的内情还得接着挖...  159
本周热议
我的信创开放社区兼职赚钱历程 40
今天你签到了吗? 27
信创开放社区邀请他人注册的具体步骤如下 15
如何玩转信创开放社区—从小白进阶到专家 15
方德桌面操作系统 14
我有15积分有什么用? 13
用抖音玩法闯信创开放社区——用平台宣传企业产品服务 13
如何让你先人一步获得悬赏问题信息?(创作者必看) 12
2024中国信创产业发展大会暨中国信息科技创新与应用博览会 9
中央国家机关政府采购中心:应当将CPU、操作系统符合安全可靠测评要求纳入采购需求 8

加入交流群

请使用微信扫一扫!