我制作了一个简单的测试程序,用于测试hibernate的persist()方法和createQuery()方法。
它与1个mySQL测试数据库通信,该数据库只有一个名为Message的表。该表有2列,即id(主键)和文本。有关工作台中的设置,请参见下图。
这是hibernate可执行java文件
package com.hibernate.hibernate;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
/**
*
* @author maurice
*/
public class Hibernate {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Message message = new Message();
String hql = "FROM Message";
Query query = session.createQuery(hql);
List results = query.list();
System.out.print(results);
//message.setText("hoi");
//session.persist(message);
session.close();
}
}
这是配置并返回sessionFactory
的hibernateUtil文件package com.hibernate.hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
// loads configuration and mappings
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry
= new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
// builds a session factory from the service registry
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
return sessionFactory;
}
}
这里是使用hibernate持久化的Annotated POJO。
package com.hibernate.hibernate;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author maurice
*/
@Entity
@Table(name = "message")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Message.findAll", query = "SELECT m FROM Message m"),
@NamedQuery(name = "Message.findById", query = "SELECT m FROM Message m WHERE m.id = :id"),
@NamedQuery(name = "Message.findByText", query = "SELECT m FROM Message m WHERE m.text = :text")})
public class Message implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "id")
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
@Column(name = "text")
private String text;
public Message() {
}
public Message(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Message)) {
return false;
}
Message other = (Message) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.hibernate.hibernate.Message[ id=" + id + " ]";
}
}
最后,这是hibernate.cfg.xml配置文件。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">scott</property>
<property name="hibernate.connection.password">tiger</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class = "com.hibernate.hibernate.Message"/>
</session-factory>
</hibernate-configuration>
运行项目时的日志文件。它没有错误,只是冻结
cd C:\book\Hibernate; "JAVA_HOME=C:\\Program Files\\Java\\jdk1.8.0_71" cmd /c "\"\"C:\\Program Files\\NetBeans 8.1\\java\\maven\\bin\\mvn.bat\" -Dexec.args=\"-classpath %classpath com.hibernate.hibernate.Hibernate\" -Dexec.executable=\"C:\\Program Files\\Java\\jdk1.8.0_71\\bin\\java.exe\" -Dexec.classpathScope=runtime -Dmaven.ext.class.path=\"C:\\Program Files\\NetBeans 8.1\\java\\maven-nblib\\netbeans-eventspy.jar\" -Dfile.encoding=UTF-8 org.codehaus.mojo:exec-maven-plugin:1.2.1:exec\""
Running NetBeans Compile On Save execution. Phase execution is skipped and output directories of dependency projects (with Compile on Save turned on) will be used instead of their jar artifacts.
Scanning for projects...
------------------------------------------------------------------------
Building Hibernate 1.0-SNAPSHOT
------------------------------------------------------------------------
Downloading: file:C:\book\Hibernate/lib/unknown/binary/hibernate-jpamodelgen-4.3.1.Final/SNAPSHOT/maven-metadata.xml
Downloading: file:C:\book\Hibernate/lib/unknown/binary/hibernate-jpamodelgen-4.3.1.Final/SNAPSHOT/hibernate-jpamodelgen-4.3.1.Final-SNAPSHOT.pom
The POM for unknown.binary:hibernate-jpamodelgen-4.3.1.Final:jar:SNAPSHOT is missing, no dependency information available
Downloading: file:C:\book\Hibernate/lib/unknown/binary/mysql-connector-java-5.1.23-bin/SNAPSHOT/maven-metadata.xml
Downloading: file:C:\book\Hibernate/lib/unknown/binary/mysql-connector-java-5.1.23-bin/SNAPSHOT/mysql-connector-java-5.1.23-bin-SNAPSHOT.pom
The POM for unknown.binary:mysql-connector-java-5.1.23-bin:jar:SNAPSHOT is missing, no dependency information available
--- exec-maven-plugin:1.2.1:exec (default-cli) @ Hibernate ---
mrt 09, 2017 7:29:43 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
mrt 09, 2017 7:29:43 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.1.Final}
mrt 09, 2017 7:29:43 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
mrt 09, 2017 7:29:43 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
mrt 09, 2017 7:29:43 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
mrt 09, 2017 7:29:43 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
mrt 09, 2017 7:29:43 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
mrt 09, 2017 7:29:44 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
mrt 09, 2017 7:29:44 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
mrt 09, 2017 7:29:44 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/hibernate?zeroDateTimeBehavior=convertToNull]
mrt 09, 2017 7:29:44 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=scott, password=****}
mrt 09, 2017 7:29:44 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
mrt 09, 2017 7:29:44 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
mrt 09, 2017 7:29:46 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
mrt 09, 2017 7:29:46 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
mrt 09, 2017 7:29:46 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
mrt 09, 2017 7:29:48 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
mrt 09, 2017 7:29:48 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
mrt 09, 2017 7:29:48 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
mrt 09, 2017 7:29:48 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: hibernate.message
mrt 09, 2017 7:29:48 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [id, text]
mrt 09, 2017 7:29:48 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: []
mrt 09, 2017 7:29:48 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [primary]
mrt 09, 2017 7:29:48 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
[]
下面是一个关于冻结意味着什么的视觉示例,负载杆卡住了。
有谁知道造成这种情况的原因是什么?任何帮助将不胜感激,谢谢。
答案 0 :(得分:1)
我注意到您在程序结束时尚未关闭SessionFactory
:
sessionFactory.close();
此外,始终结束当前正在运行的数据库事务至关重要。因此,如果一切正常,您应该调用 commit ,并在catch块中调用 rollback ,以防出现任何异常。
修复你得到的错误:
Unknown entity: com.hibernate.hibernate.Message
你需要让Hibernate知道这个映射:
configuration.addAnnotatedClass(Message.class);