Я новичок в Hibernate и пытаюсь создать небольшое приложение на Java, используя Maven в IntelliJ Idea.У меня есть эта ошибка в заголовке выше, и ответы на ту же проблему здесь, в стеке, не помогли мне до сих пор.
Что это за файл "Person.hbm.xml".Я должен создать это?Когда это ресурс сопоставления, Hibernate не должен создавать его сам?
Я получаю эту ошибку при запуске моей маленькой программы:
Exception in thread "main" org.hibernate.boot.MappingNotFoundException: Mapping (RESOURCE) not found : HibernateExposed/Person.hbm.xml : origin(HibernateExposed/Person.hbm.xml)
at org.hibernate.boot.spi.XmlMappingBinderAccess.bind(XmlMappingBinderAccess.java:56)
at org.hibernate.boot.MetadataSources.addResource(MetadataSources.java:274)
at org.hibernate.boot.cfgxml.spi.MappingReference.apply(MappingReference.java:70)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:412)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:86)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at Persistencia.HibernateUtils.<init>(HibernateUtils.java:10)
at Main.Main.main(Main.java:16)
Это мой класс конфигурации базы данных:HibernateUtils:
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtils {
//Fábrica de sessões de banco de dados constante no padrão SINGLETON
SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
}
И ниже, мой класс сущностей, который я пытаюсь сохранить:
import javax.persistence.Entity;
import java.sql.Date;
@Entity
public class Produto {
private String nome;
private int cod;
private float valor;
private Date dataValidade;
protected Produto() {
}
public Produto(String nome, int cod, float valor, Date dataValidade) {
this.nome = nome;
this.cod = cod;
this.valor = valor;
this.dataValidade = dataValidade;
}
/*public Produto getProdutoPorNome(String nome) {
Produto buscaResult = //Resultado da busca.
}
*/
public boolean excluirProduto(int cod) {
boolean deuCerto=false;
return deuCerto;
}
}
И мой Основной класс:
package Main;
import Persistencia.HibernateUtils;
import ProcessoDeVenda.Produto;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import java.util.Date;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Session sessao;
HibernateUtils hiber = new HibernateUtils();
SessionFactory session = hiber.getSessionFactory();
Produto produto;
try {
sessao = session.openSession();
Date data = new Date(05, 12, 2018);
float valor = (float) 42000.0;
produto = new Produto("Carro", 1, valor, (java.sql.Date) data);
System.out.println(produto.toString());
}catch (Exception sqlException) {
System.out.println(sqlException);
}
}
}
Проектструктура с расположением файла hibernate.cfg.xml.
И содержимое моего файла hibernate.cfg.xml: посмотрите на ресурс "mapping""tag.
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.h2.Driver</property>
<property name="connection.url">jdbc:h2:~/PDV</property>
<property name="connection.username">Lucas</property>
<property name="connection.password">mypass</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="HibernateExposed/Person.hbm.xml" />
</session-factory>
</hibernate-configuration>
Теперь я пытаюсь отобразить классы прямо на hibernate.cfg.xml.(Почему hibernate не делает это сам? Я использую аннотации ...)
Я удалил
<mapping resource="HibernateExposed/Person.hbm.xml" />
И там, где я сопоставил класс:
<mapping class="src.main.java.ProcessoDeVenda.Produto" />
И ошибка просто изменилась на это:
Exception in thread "main" 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:417)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:86)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at Persistencia.HibernateUtils.<init>(HibernateUtils.java:10)
at Main.Main.main(Main.java:16)
Caused by: org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:105)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:123)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:41)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:58)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections.addConnections(DriverManagerConnectionProviderImpl.java:363)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections.<init>(DriverManagerConnectionProviderImpl.java:282)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections.<init>(DriverManagerConnectionProviderImpl.java:260)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections$Builder.build(DriverManagerConnectionProviderImpl.java:401)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:112)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:75)
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)
... 15 more
Caused by: org.h2.jdbc.JdbcSQLException: Database may be already in use: null. Possible solutions: close all other connection(s); use the server mode [90020-197]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:357)
at org.h2.message.DbException.get(DbException.java:168)
at org.h2.mvstore.db.MVTableEngine$Store.convertIllegalStateException(MVTableEngine.java:188)
at org.h2.mvstore.db.MVTableEngine$Store.open(MVTableEngine.java:168)
at org.h2.mvstore.db.MVTableEngine.init(MVTableEngine.java:100)
at org.h2.engine.Database.getPageStore(Database.java:2538)
at org.h2.engine.Database.open(Database.java:709)
at org.h2.engine.Database.openDatabase(Database.java:286)
at org.h2.engine.Database.<init>(Database.java:280)
at org.h2.engine.Engine.openSession(Engine.java:66)
at org.h2.engine.Engine.openSession(Engine.java:179)
at org.h2.engine.Engine.createSessionAndValidate(Engine.java:157)
at org.h2.engine.Engine.createSession(Engine.java:140)
at org.h2.engine.Engine.createSession(Engine.java:28)
at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:351)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:124)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:103)
at org.h2.Driver.connect(Driver.java:69)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:38)
... 30 more
Caused by: java.lang.IllegalStateException: The file is locked: nio:C:/Users/Lucas_Pletsch/PDV.mv.db [1.4.197/7]
at org.h2.mvstore.DataUtils.newIllegalStateException(DataUtils.java:870)
at org.h2.mvstore.FileStore.open(FileStore.java:173)
at org.h2.mvstore.MVStore.<init>(MVStore.java:350)
at org.h2.mvstore.MVStore$Builder.open(MVStore.java:2934)
at org.h2.mvstore.db.MVTableEngine$Store.open(MVTableEngine.java:155)
... 45 more
Это моя консоль базы данных H2, показывающая конфигурации, которые я передал в hibernate.cfg.xml, например, JDBC URL, класс драйвера ...
Я импортировал H2 в файл POM.xml моего проекта:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>