我正在使用eclipse EE:hibernate-tutorial-for-begin来学习本教程。我有错误。还有一件事是我无法在任何一个hibernate发行版中找到所有提到的jar文件,所以我有来自openlogic-hibernate-3.3.1.GA-all-bin-1
&的所有jar文件。来自lib/jpa
的{{1}}因为它未包含在3.3.1中。
我在MySql中制作了表格。
修改 这是我正在使用的Jar文件列表:
hibernate-release-4.0.0.CR5
以下是错误:
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
以下是程序文件:
Test.Java
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
HibernateUtil.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();
}
}
}
hibernate.cfg.xml中
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;
}
}
task.hbm.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>
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.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>
任务类
<?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>
用户类
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;
}
}
答案 0 :(得分:0)
您获得的运行时异常是由slf4j
(Hibernate使用的日志框架)引起的。确保您提供了与在类路径中编译的Hibernate的slf4j API相匹配的正确实现,例如:对于Hibernate 3.3.1(根据pom),正确的版本是1.5.2(根据您的环境选择目标日志记录机制,例如simple / log4j / jdk14)。
答案 1 :(得分:0)
这不是编译时错误,而是运行时。您缺少slf4j-log4j12.jar绑定或其他,具体取决于您要使用的基础日志框架。
下载答案 2 :(得分:0)
尝试将hibernate-jpa-xxx.jar
添加到您的类路径中。
也验证数据库连接配置。