gpt4 book ai didi

Java Hibernate - 无法连接到 H2

转载 作者:行者123 更新时间:2023-11-30 01:54:20 25 4
gpt4 key购买 nike

我需要帮助。我不知道这个项目出了什么问题。我无法连接到 h2 数据库。即使我没有保留任何对象,只是关闭连接,我也会收到错误。

抱歉,我知道,这个问题已经被问过好几次了,但没有一个答案适合我的情况。

我得到的错误:

Mar 04, 2019 11:00:24 PM org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {5.2.12.Final} Mar 04, 2019 11:00:24 PM org.hibernate.cfg.Environment INFO: HHH000206: hibernate.properties not found Mar 04, 2019 11:00:24 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead. Support for obsolete DTD/XSD namespaces may be removed at any time. Mar 04, 2019 11:00:24 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final} Mar 04, 2019 11:00:25 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!) org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:271) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51) at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352) at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111) at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83) at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418) at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726) at orm.hibernate.employees.HibernateUtils.(HibernateUtils.java:13) at orm.hibernate.employees.EmployeeRepository.addNewEmployee(EmployeeRepository.java:16) at orm.hibernate.employees.EmployeesApp.main(EmployeesApp.java:21) Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [org.h2.Driver] at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:348) at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.loadDriverIfPossible(DriverManagerConnectionProviderImpl.java:160) at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildCreator(DriverManagerConnectionProviderImpl.java:116) at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:100) at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:72) at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145) at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66) at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88) at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259) ... 16 more Caused by: java.lang.ClassNotFoundException: Could not load requested class : org.h2.Driver at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.findClass(ClassLoaderServiceImpl.java:336) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:348) at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:345) ... 28 more

##### Initial SessionFactory creation failed.org.hibernate.service.spi.ServiceException: Unable to create

requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] Exception in thread "main" java.lang.ExceptionInInitializerError: Connection to database error! at orm.hibernate.employees.HibernateUtils.(HibernateUtils.java:17) at orm.hibernate.employees.EmployeeRepository.addNewEmployee(EmployeeRepository.java:16) at orm.hibernate.employees.EmployeesApp.main(EmployeesApp.java:21)

Process finished with exit code 1

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>brudnopis.com</groupId>
<artifactId>brudnopis2</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>

<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.12.Final</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.196</version>
<scope>test</scope>
</dependency>

</dependencies>

</project>

Hibernate Utils 类:

public class HibernateUtils {

private static final SessionFactory sessionFactory;

static {
try {
sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
} catch (Throwable ex) {
ex.printStackTrace();
System.err.println("########### Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError("Connection to database error!");
}
}

public static Session openSession() throws Exception {
Session session;
try {
session = sessionFactory.openSession();
} catch (Exception e) {
e.printStackTrace();
throw new Exception("Connection to database error!");
}
return session;
}

public static void closeSession(){
sessionFactory.close();
}
}

存储库

public class EmployeeRepository {

// Create

public static void addNewEmployee(EmployeeEntity employee){

Session session = null;
try {
session = HibernateUtils.openSession();
session.getTransaction().begin();
session.saveOrUpdate(employee);
session.getTransaction().commit();
}catch (Exception e){
e.printStackTrace();
}finally {
if (session != null && session.isOpen()) {
session.close();
}
}
}

// Read

public static List<EmployeeEntity> listAllEmployees(){

List<EmployeeEntity> listEmployees = new ArrayList<EmployeeEntity>();

Session session = null;
try {
session = HibernateUtils.openSession();
listEmployees = session.createQuery("SELECT e FROM EmployeeEntity e").getResultList();
} catch (Exception e) {
e.printStackTrace();
}finally {
if (session != null && session.isOpen()) {
session.close();
}
}
return listEmployees;
}

// Update

public static void editExistingEmployee(EmployeeEntity employee){

Session session = null;
try {
session = HibernateUtils.openSession();
session.getTransaction().begin();
session.merge(employee);
session.getTransaction().commit();
}catch (Exception e){
e.printStackTrace();
}finally{
if (session != null && session.isOpen()) {
session.close();
}
}
}

//Delete

public static void deleteEmployee(int idToDelete){

Session session = null;
try {
session = HibernateUtils.openSession();
EmployeeEntity employeeToDelete = session.find(EmployeeEntity.class, idToDelete);
session.getTransaction().begin();
session.remove(employeeToDelete);
session.getTransaction().commit();
}catch (Exception e){
e.printStackTrace();
}finally{
if (session != null && session.isOpen()) {
session.close();
}
}
}
}

实体类:

@Entity
@Table(name = "employees")
public class EmployeeEntity {

@Id
@Column(name = "id")
private int id;
@Column(name = "employee_id")
private int employeeId;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;

public EmployeeEntity(int id, int employeeId, String firstName, String lastName) {
this.id = id;
this.employeeId = employeeId;
this.firstName = firstName;
this.lastName = lastName;
}

public EmployeeEntity(){}

@Override
public String toString() {
return "EmployeeEntity{" +
"id=" + id +
", employeeId=" + employeeId +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public int getEmployeeId() {
return employeeId;
}

public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}
}

主类:

public class EmployeesApp {
public static void main(String[] args) throws Exception {

Scanner sc = new Scanner(System.in);

System.out.println("Menu");
System.out.println("====");
System.out.println("1. Write data to database");
System.out.println("2. Read data from database");
System.out.println("3. Exit");

int userChoice = sc.nextInt();

switch(userChoice){
case 1:
EmployeeEntity employee1 = new EmployeeEntity(1,10001,"Jon", "Doe");
EmployeeRepository.addNewEmployee(employee1);
System.out.println(EmployeeRepository.listAllEmployees());
case 3:
break;
}
HibernateUtils.closeSession();
}
}

项目结构:

enter image description here

最佳答案

您的应用程序无法在运行时找到数据库驱动程序,因此会出现错误Caused by: java.lang.ClassNotFoundException: Could not load requested class : org.h2.Driver

按以下方式更改 H2 依赖项:

    <dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.196</version>
<scope>runtime</scope> <!-- Here you are saying this dependency is needed at runtime, not just at testing -->
</dependency>

再见!

关于Java Hibernate - 无法连接到 H2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54990447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com