springboot+hibernate如何简单配置多个数据源

前言:

        1,业务需求:使用原生的hibernate连接数据库,数据来源是两个数据库,并且为了后期维护,需要将数据库账号密码重hibernate.cfg.xml中抽离出来,放到properties文件中读取

        2,网上有很多教程,说是hibernate进行配置,实质上是jpa

        3,本文章适合对hibernate基本使用有了解的人

        4,由于笔记本上只有一个数据库,所以模拟过程中有些不严谨,两个数据库连接,连的是同一个数据库,但过程是这么个过程

        5,这里没有将与数据库相关的对象注入到spring容器中。

1,引入hibernate的pom.xml文件

2,编写hibernate.cfg.xml文件

3,编写hibernate.properties文件

4,编写实体类

5,编写测试案例

 

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>demo2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo2</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.7.RELEASE</spring-boot.version>
    </properties>
    <dependencies>
        <!--spring的web服务-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--便于生成set方法的lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--test模块-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--前端模板-->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>3.0.12.RELEASE</version>
        </dependency>
        <!--springboot整合前端模板-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--springboot整合jdbc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!--mysql连接驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.37</version>
            <scope>runtime</scope>
        </dependency>
        <!-- springboot整合mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
        <!-- 操作Excel文件-->
        <dependency>
            <groupId>net.sourceforge.jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6</version>
        </dependency>
        <!-- hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>com.example.demo2.Demo2Application</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

hibernate1.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <!-- 配置数据库连接 connection -->
    <session-factory>
        <!-- 数据库驱动 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- 数据库方言 MySQL -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <mapping class="com.example.demo2.pojo.Student" />
    </session-factory>
</hibernate-configuration>

hibernate2.cfg.xml  内容与上面的一样,我电脑上只有一个数据库只有这样模拟了,没办法

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <!-- 配置数据库连接 connection -->
    <session-factory>
        <!-- 数据库驱动 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- 数据库方言 MySQL -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <mapping class="com.example.demo2.pojo.Student" />
    </session-factory>
</hibernate-configuration>

hibernate1.properties


hibernate.connection.url=jdbc:mysql://localhost:3306/test?severTimezone=UTC&useUnicode=true&characterEncoding=utf-8
hibernate.connection.password=123
hibernate.connection.username=root

 

 hibernate2.properties  内容与上面的一样,我电脑上只有一个数据库只有这样模拟了,没办法


hibernate.connection.url=jdbc:mysql://localhost:3306/test?severTimezone=UTC&useUnicode=true&characterEncoding=utf-8
hibernate.connection.password=123
hibernate.connection.username=root

实体类 student.class

package com.example.demo2.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;

@AllArgsConstructor
@NoArgsConstructor
@Data

@Entity
@Table()
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;
    private String password;
}

测试代码 test1.class

package com.example.demo2;

import com.example.demo2.pojo.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.query.NativeQuery;
import org.junit.jupiter.api.Test;
import java.util.List;

public class Test1 {
    public static StandardServiceRegistry registry1;
    public static Session session1;
    public static SessionFactory factory1;

    public static StandardServiceRegistry registry2;
    public static Session session2;
    public static SessionFactory factory2;

    static {
        registry1=new StandardServiceRegistryBuilder().configure("hibernate1.cfg.xml")
                .loadProperties("hibernate1.properties").build();
        factory1=new MetadataSources(registry1).buildMetadata().buildSessionFactory();
        session1=factory1.openSession();

        registry2=new StandardServiceRegistryBuilder().configure("hibernate2.cfg.xml")
                .loadProperties("hibernate2.properties").build();
        factory2=new MetadataSources(registry2).buildMetadata().buildSessionFactory();
        session2=factory1.openSession();
    }

    @Test
    public void getStudent1()
    {
        //两个session是不同的,他们是有不同的工厂创建出来的
        System.out.println(session1==session2);
        NativeQuery nativeQuery1 = session1.createSQLQuery("select * from student").addEntity(Student.class);
        List<Student> list1 = nativeQuery1.list();
        if (!list1.isEmpty())
            for (Student student:list1)
                System.out.println(student);
        session1.close();
    }

    @Test
    public void getStudent2()
    {
        NativeQuery nativeQuery2 = session2.createSQLQuery("select * from student").addEntity(Student.class);
        List<Student> list2 = nativeQuery2.list();
        if (!list2.isEmpty())
            for (Student student:list2)
                System.out.println(student);
        session2.close();
    }




}

测试结果:

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值