Hibernate程序错误 [英] Hibernate program errors

查看:109
本文介绍了Hibernate程序错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用eclipse EE学习本教程: hibernate-tutorial - 对于期初。有我得到的错误。还有一件事是我在任何一个hibernate发行版中都找不到所有提到的jar文件,所以我从> openlogic-hibernate-3.3.1.GA-all-bin-1 & lib / jpa 来自 hibernate-release-4.0.0.CR5 ,因为它不包含在3.3.1中。
我在MySql中创建了表。



编辑
这里是我使用的Jar文件列表:

  lib \mysql-connector-java-5.1.18-bin.jar 
lib\slf4j-simple-1.6。 4.jar
lib\antlr-2.7.6.jar
lib\commons-collections-3.1.jar
lib\dom4j-1.6.1.jar
lib \hibernate3.jar
lib \hibernate-cglib-repack-2.1_3.jar
lib\hibernate-entitymanager-4.0.0.CR5.jar
lib\javassist-3.4 .GA.jar
lib \jta-1.1.jar
lib\slf4j-api-1.5.2.jar

以下是错误:

 线程mainjava.lang中的异常。 ExceptionInInitializerError 
at com.hib.HibernateUtil.buildSessionFactory(HibernateUtil.java:16)
at com.hib.HibernateUtil。< clinit>(HibernateUtil.java:7)
at com.hib .Test.addUser(Test.java:61)
at com.hib.Test.main(Test.java:20)
导致:java.lang.IllegalAccessError:尝试访问字段org.slf4j.LoggerFactory中的org.slf4j.impl.StaticLoggerBinder.SINGLETON org.slf4j.LoggerFactory中的
。< clinit>(LoggerFactory.java:60)$ or $ $ b $ org.hibernate.cfg.Configuration 。< clinit>(Configuration.java:151)
at com.hib.HibernateUtil.buildSessionFactory(HibernateUtil.java:11)​​
... 3 more

以下是程式档案:

Test.Java

  import java.util.Iterator; 
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Test {

/ **
* @param args
* /
public static void main(String [] args ){

Test tst = new Test();
$ b $ **
*增加记录
* /
tst.addUser(Saranga,Rath);
tst.addUser(Isuru,Sampath);
tst.addUser(Saranga,Jaya);
tst.addUser(Prasanna,Milinda);

tst.addTask(1,Call,下午5点拨打电话Pubudu);
tst.addTask(1,购物,为Kity购买食物);
tst.addTask(2,Email,发送生日祝愿Pubudu);
tst.addTask(2,短信,发送信息给爸爸);
tst.addTask(2,Office,给老板打电话);
$ b $ ** ** b $ b *检索数据
* /
tst.getFullName(Saranga);

/ **
*完整更新记录
* /
User user = new User();
user.setId(1);
user.setFirstName(Saranga);
user.setLastName(Rathnayake);
tst.updateUser(user);

/ **
*部分更新记录
* /
tst.updateLastName(3,Jayamaha);

/ **
*删除记录
* /
User user1 = new User();
user1.setId(4);
tst.deleteUser(user1);


private void addUser(String firstName,String lastName){

Transaction trns = null;
Session session = HibernateUtil.getSessionFactory()。openSession();
尝试{
trns = session.beginTransaction();

User user = new User();

user.setFirstName(firstName);
user.setLastName(lastName);

session.save(user);

session.getTransaction()。commit();
} catch(RuntimeException e){
if(trns!= null){
trns.rollback();
}
e.printStackTrace();
}最后{
session.flush();
session.close();


$ b $ private void addTask(int userID,String title,String description){

Transaction trns = null;
Session session = HibernateUtil.getSessionFactory()。openSession();
尝试{
trns = session.beginTransaction();

任务任务=新任务();

task.setUserID(userID);
task.setTitle(title);
task.setDescription(description);

session.save(task);

session.getTransaction()。commit();
} catch(RuntimeException e){
if(trns!= null){
trns.rollback();
}
e.printStackTrace();
}最后{
session.flush();
session.close();
}
}

private void updateLastName(int id,String lastName){
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory()。openSession();
尝试{
trns = session.beginTransaction();
String hqlUpdate =update User u set u.lastName =:newLastName where u.id =:oldId;
int updatedEntities = session.createQuery(hqlUpdate)
.setString(newLastName,lastName)
.setInteger(oldId,id)
.executeUpdate();

trns.commit();
} catch(RuntimeException e){
if(trns!= null){
trns.rollback();
}
e.printStackTrace();
}最后{
session.flush();
session.close();
}

}

private void updateUser(用户用户){
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory()。openSession();
尝试{
trns = session.beginTransaction();

session.update(user);

session.getTransaction()。commit();
} catch(RuntimeException e){
if(trns!= null){
trns.rollback();
}
e.printStackTrace();
}最后{
session.flush();
session.close();
}
}

private void getFullName(String firstName){
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory()。openSession();
尝试{
trns = session.beginTransaction();
列表<用户> users = session.createQuery(from User as u where u.firstName =:firstName)
.setString(firstName,firstName)
.list();
for(Iterator< User> iter = users.iterator(); iter.hasNext();){
User user = iter.next();
System.out.println(user.getFirstName()++ user.getLastName());
}
trns.commit();
} catch(RuntimeException e){
if(trns!= null){
trns.rollback();
}
e.printStackTrace();
}最后{
session.flush();
session.close();
}
}

private void deleteUser(用户用户){
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory()。openSession();
尝试{
trns = session.beginTransaction();

session.delete(user);

session.getTransaction()。commit();
} catch(RuntimeException e){
if(trns!= null){
trns.rollback();
}
e.printStackTrace();
}最后{
session.flush();
session.close();





HibernateUtil.java

  package com.hib; 

import org.hibernate.SessionFactory;
导入org.hibernate.cfg.Configuration;

public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory(){
try {
//从hibernate.cfg.xml创建SessionFactory
返回新的Configuration().configure()。buildSessionFactory();
}
catch(Throwable ex){
//确保您记录异常,因为它可能被吞噬
System.err.println(初始化SessionFactory创建失败。 + ex);
抛出新的ExceptionInInitializerError(ex);


public static SessionFactory getSessionFactory(){
return sessionFactory;


hibernate.cfg.xml

 <?xml version =1.0encoding =utf-8?> 
<!DOCTYPE hibernate-configuration PUBLIC
- // Hibernate / Hibernate配置DTD 3.0 // EN
http://www.hibernate.org/dtd/hibernate-configuration -3.0.dtd>
< hibernate-configuration>
< session-factory>
<! - 数据库连接设置 - >
< property name =connection.driver_class> com.mysql.jdbc.Driver< / property>
< property name =connection.url> jdbc:mysql:// localhost / userdata< / property>
< property name =connection.username> root< / property>
< property name =connection.password>< / property>

<! - JDBC连接池(使用内置) - >
< property name =connection.pool_size> 1< / property>

<! - - SQL方言 - >
< property name =dialect> org.hibernate.dialect.MySQLDialect< / property>

<! - 启用Hibernate的自动会话上下文管理 - >
< property name =current_session_context_class>线程< / property>

<! - 禁用二级缓存 - >
< property name =cache.provider_class> org.hibernate.cache.NoCacheProvider< / property>

<! - 将所有执行的SQL回复到stdout - >
< property name =show_sql> true< / property>

<! - 在启动时删除并重新创建数据库模式 - >
< property name =hbm2ddl.auto>更新< / property>

<! - 映射文件 - >
< mapping resource =user.hbm.xml/>
< mapping resource =task.hbm.xml/>

< / session-factory>
< / hibernate-configuration>

task.hbm.xml

 <?xml version =1.0?> 
<!DOCTYPE hibernate-mapping PUBLIC
- // Hibernate / Hibernate映射DTD 3.0 // EN
http://hibernate.sourceforge.net/hibernate-mapping-3.0 .dtd>

< hibernate-mapping>
< class name =com.hib.Tasktable =tasks>
< id name =idtype =intcolumn =id>
< generator class =native/>
< / id>

< property name =userID>
< column name =user_id/>
< / property>
< property name =title>
< column name =title/>
< / property>
< property name =description>
< column name =description/>
< / property>
< / class>
< / hibernate-mapping>

user.hbm.xml

 <?xml version =1.0?> 
<!DOCTYPE hibernate-mapping PUBLIC
- // Hibernate / Hibernate映射DTD 3.0 // EN
http://hibernate.sourceforge.net/hibernate-mapping-3.0 .dtd>

< hibernate-mapping>
< class name =com.hib.Usertable =users>
< id name =idtype =intcolumn =id>
< generator class =native/>
< / id>

< property name =firstName>
< column name =first_name/>
< / property>
< property name =lastName>
< column name =last_name/>
< / property>
< / class>
< / hibernate-mapping>

任务分类

  package com.hib; 

public class Task {

private Integer id;
private Integer userID;
私有字符串标题;
私有字符串描述;

public Integer getId(){
return id;
}
public void setId(Integer id){
this.id = id;
}
public Integer getUserID(){
return userID;
}
public void setUserID(Integer userID){
this.userID = userID;
}
public String getTitle(){
return title;
}
public void setTitle(String title){
this.title = title;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description = description;


用户等级

  package com.hib; 

public class User {
private Integer id;
private String firstName;
private String lastName;

public Integer getId(){
return id;
}
public void setId(Integer id){
this.id = id;
}
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;
}
}


解决方案

运行时异常是由 slf4j 造成的( Hibernate使用的日志框架)。确保你已经提供了与你的类路径中编译的slf4j API匹配的正确实现,例如,对于Hibernate 3.3.1(根据 pom )正确的版本是 1.5.2 (根据您的环境选择目标日志机制,例如simple / log4j / jdk14)。


I am following this tutorial using eclipse EE : hibernate-tutorial-for-begin. There are the errors I am getting. One more thing is that I couldn't find all mentioned jar files in any one hibernate distribution, so I have all jars from openlogic-hibernate-3.3.1.GA-all-bin-1 & lib/jpa from hibernate-release-4.0.0.CR5 bec it was not included in 3.3.1. I made tables in MySql.

EDIT Here is list of Jar files I am using:

lib\mysql-connector-java-5.1.18-bin.jar
lib\slf4j-simple-1.6.4.jar
lib\antlr-2.7.6.jar
lib\commons-collections-3.1.jar
lib\dom4j-1.6.1.jar
lib\hibernate3.jar
lib\hibernate-cglib-repack-2.1_3.jar
lib\hibernate-entitymanager-4.0.0.CR5.jar
lib\javassist-3.4.GA.jar
lib\jta-1.1.jar
lib\slf4j-api-1.5.2.jar

Here are the errors:

Exception in thread "main" java.lang.ExceptionInInitializerError
    at com.hib.HibernateUtil.buildSessionFactory(HibernateUtil.java:16)
    at com.hib.HibernateUtil.<clinit>(HibernateUtil.java:7)
    at com.hib.Test.addUser(Test.java:61)
    at com.hib.Test.main(Test.java:20)
Caused by: java.lang.IllegalAccessError: tried to access field org.slf4j.impl.StaticLoggerBinder.SINGLETON from class org.slf4j.LoggerFactory
    at org.slf4j.LoggerFactory.<clinit>(LoggerFactory.java:60)
    at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:151)
    at com.hib.HibernateUtil.buildSessionFactory(HibernateUtil.java:11)
    ... 3 more 

Here are program files:

Test.Java

import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Test {

 /**
  * @param args
  */
 public static void main(String[] args) {

  Test tst = new Test();

  /**
   * adding records
   */
  tst.addUser("Saranga", "Rath");
  tst.addUser("Isuru", "Sampath");
  tst.addUser("Saranga", "Jaya");
  tst.addUser("Prasanna", "Milinda");

  tst.addTask(1, "Call", "Call Pubudu at 5 PM");
  tst.addTask(1, "Shopping", "Buy some foods for Kity");
  tst.addTask(2, "Email", "Send birthday wish to Pubudu");
  tst.addTask(2, "SMS", "Send message to Dad");
  tst.addTask(2, "Office", "Give a call to Boss");

  /**
   *  retrieving data
   */
  tst.getFullName("Saranga");

  /**
   * full updating records
   */
  User user = new User();
  user.setId(1);
  user.setFirstName("Saranga");
  user.setLastName("Rathnayake");
  tst.updateUser(user);

  /**
   * partial updating records
   */
  tst.updateLastName(3, "Jayamaha");

  /**
   * deleting records
   */
  User user1 = new User();
  user1.setId(4);
  tst.deleteUser(user1);
 }

 private void addUser(String firstName, String lastName) {

  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();

   User user = new User();

   user.setFirstName(firstName);
   user.setLastName(lastName);

   session.save(user);

   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 }

 private void addTask(int userID, String title, String description) {

  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();

   Task task = new Task();

   task.setUserID(userID);
   task.setTitle(title);
   task.setDescription(description);

   session.save(task);

   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 }

 private void updateLastName(int id, String lastName) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
   String hqlUpdate = "update User u set u.lastName = :newLastName where u.id = :oldId";
   int updatedEntities = session.createQuery( hqlUpdate )
   .setString( "newLastName", lastName )
   .setInteger( "oldId", id )
   .executeUpdate();

   trns.commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }

 }

 private void updateUser(User user) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();

   session.update(user);

   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 }

 private void getFullName(String firstName) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
   List<User> users = session.createQuery("from User as u where u.firstName = :firstName")
   .setString( "firstName", firstName )
   .list();
   for (Iterator<User> iter = users.iterator(); iter.hasNext();) {
    User user = iter.next();
    System.out.println(user.getFirstName() +" " + user.getLastName());
   }
   trns.commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 }

 private void deleteUser(User user) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();

   session.delete(user);

   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 }
}

HibernateUtil.java

package com.hib;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
 private static final SessionFactory sessionFactory = buildSessionFactory();
 private static SessionFactory buildSessionFactory() {
  try {
   // Create the SessionFactory from hibernate.cfg.xml
   return new Configuration().configure().buildSessionFactory();
  }
  catch (Throwable ex) {
   // Make sure you log the exception, as it might be swallowed
   System.err.println("Initial SessionFactory creation failed." + ex);
   throw new ExceptionInInitializerError(ex);
  }
 }
 public static SessionFactory getSessionFactory() {
  return sessionFactory;
 }
}

hibernate.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>
 <session-factory>
  <!-- Database connection settings -->
  <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="connection.url">jdbc:mysql://localhost/userdata</property>
  <property name="connection.username">root</property>
  <property name="connection.password"></property>

  <!-- JDBC connection pool (use the built-in) -->
  <property name="connection.pool_size">1</property>

  <!-- SQL dialect -->
  <property name="dialect">org.hibernate.dialect.MySQLDialect</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 files -->
  <mapping resource="user.hbm.xml"/>
  <mapping resource="task.hbm.xml"/>

 </session-factory>
</hibernate-configuration>

task.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
 <class name="com.hib.Task" table="tasks">
  <id name="id" type="int" column="id" >
   <generator class="native"/>
  </id>

  <property name="userID">
   <column name="user_id" />
  </property> 
  <property name="title">
   <column name="title" />
  </property>
  <property name="description">
   <column name="description"/>
  </property>
 </class>
</hibernate-mapping>

user.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
 <class name="com.hib.User" table="users" >
  <id name="id" type="int" column="id" >
   <generator class="native"/>
  </id>

  <property name="firstName">
   <column name="first_name" />
  </property>
  <property name="lastName">
   <column name="last_name"/>
  </property>
 </class>
</hibernate-mapping>

Task Class

package com.hib;

public class Task {

 private Integer id;
 private Integer userID;
 private String title;
 private String description;

 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public Integer getUserID() {
  return userID;
 }
 public void setUserID(Integer userID) {
  this.userID = userID;
 }
 public String getTitle() {
  return title;
 }
 public void setTitle(String title) {
  this.title = title;
 }
 public String getDescription() {
  return description;
 }
 public void setDescription(String description) {
  this.description = description;
 }
}

User Class

package com.hib;

public class User {
 private Integer id;
 private String firstName;
 private String lastName;

 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 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;
 }
}

解决方案

The runtime exception you've got is caused by slf4j (logging framework used by Hibernate). Make sure that you have provided the correct implementation that matches the slf4j API Hibernate was compiled with in your classpath, e.g. for Hibernate 3.3.1 (according to pom) the correct version is 1.5.2 (choose the target logging mechanism, e.g. simple/log4j/jdk14, according to your environment).

这篇关于Hibernate程序错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆