hibernate_Eclipse+hibernate+mysql配置

原工做環境是myecilpse,考慮到myeclipse愈來愈冗餘,且myeclipse集成度高,封裝了較多操做,不少細節都是傻瓜式配置,不便於成長,依賴度過高,遂工做平臺從myeclipse轉到eclipse下。html

工具:java

eclipsemysql

hibernate eclipse toolweb

hibernate ormsql

mysql jdbc drivershell

slf4j數據庫

log4japache

下載各工具後,hibernate eclipse壓縮包放到eclipse dropin目錄下解壓縮,啓動eclipse.api

1,建立java project test,hibernate orm下載解壓後,hibernate3.jar以及lib目錄下requeire目錄下jar包導入工程;把mysql jdbc driver jar包導入工程,session

2,配置hibernate映射文件:hibernate.cfg.xml

     到hibernate-distribution-3.5.0-Final\project\tutorials\web\src\main\resources目錄下把hibernate配置文件拷貝到test/src目錄下,根據具體狀況修改配置文件,配置見文尾附錄;

3,建立映射文件,映射類: Event.hbm.xml,Event類

    test工程下建立包:com.xinju.hibernate,包下建立配置文件 Event.hbm.xml,映射類:,代碼見附錄

4,運行測試類。

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder
Exception in thread "main" java.lang.ExceptionInInitializerError
	at com.xinju.hibernate.HibernateUtil.<clinit>(HibernateUtil.java:17)
	at com.xinju.hibernate.test.main(test.java:9)
Caused by: java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder
	at org.slf4j.LoggerFactory.getSingleton(LoggerFactory.java:223)
	at org.slf4j.LoggerFactory.bind(LoggerFactory.java:120)
	at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:111)
	at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:269)
	at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:242)
	at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:255)
	at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:165)
	at com.xinju.hibernate.HibernateUtil.<clinit>(HibernateUtil.java:13)
	... 1 more
Caused by: java.lang.ClassNotFoundException: org.slf4j.impl.StaticLoggerBinder
	at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
	at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
	... 9 more

或者是報錯:

Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/apache/log4j/Level

運行報錯,緣由在於hibernate require包不包含slf4j引用包,需下載slf4j包,包的版本根據slf4j-api.1.5.8.jar,下載slf4j1.5.8,解壓slf4j-log4j12-1.5.8.jar以及log4j-1.2.17.jar

這一部分官方文檔3.5節日誌部分有詳細描述。

修改後運行以下:

16:02:48,939  INFO Environment:564 - Hibernate 3.5.0-Final
16:02:48,939  INFO Environment:597 - hibernate.properties not found
16:02:48,955  INFO Environment:775 - Bytecode provider name : javassist
16:02:48,955  INFO Environment:656 - using JDK 1.4 java.sql.Timestamp handling
16:02:49,033  INFO Configuration:1518 - configuring from resource: /hibernate.cfg.xml
16:02:49,033  INFO Configuration:1495 - Configuration resource: /hibernate.cfg.xml
16:02:49,095  INFO Configuration:655 - Reading mappings from resource : com/xinju/hibernate/Event.hbm.xml
16:02:49,158  INFO HbmBinder:348 - Mapping class: com.xinju.hibernate.Event -> EVENT
16:02:49,158  INFO Configuration:1633 - Configured SessionFactory: null
16:02:49,205  INFO DriverManagerConnectionProvider:64 - Using Hibernate built-in connection pool (not for production use!)
16:02:49,205  INFO DriverManagerConnectionProvider:65 - Hibernate connection pool size: 2
16:02:49,205  INFO DriverManagerConnectionProvider:68 - autocommit mode: false
16:02:49,205  INFO DriverManagerConnectionProvider:103 - using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/test
16:02:49,205  INFO DriverManagerConnectionProvider:109 - connection properties: {user=root, password=****}
16:02:49,580  INFO SettingsFactory:117 - RDBMS: MySQL, version: 5.6.12-log
16:02:49,580  INFO SettingsFactory:118 - JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.17 ( Revision: ${bzr.revision-id} )
16:02:49,595  INFO Dialect:222 - Using dialect: org.hibernate.dialect.MySQLDialect
16:02:49,595  INFO TransactionFactoryFactory:59 - Using default transaction strategy (direct JDBC transactions)
16:02:49,595  INFO TransactionManagerLookupFactory:80 - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
16:02:49,595  INFO SettingsFactory:169 - Automatic flush during beforeCompletion(): disabled
16:02:49,595  INFO SettingsFactory:173 - Automatic session close at end of transaction: disabled
16:02:49,595  INFO SettingsFactory:180 - JDBC batch size: 15
16:02:49,595  INFO SettingsFactory:183 - JDBC batch updates for versioned data: disabled
16:02:49,595  INFO SettingsFactory:188 - Scrollable result sets: enabled
16:02:49,611  INFO SettingsFactory:196 - JDBC3 getGeneratedKeys(): enabled
16:02:49,611  INFO SettingsFactory:204 - Connection release mode: auto
16:02:49,611  INFO SettingsFactory:228 - Maximum outer join fetch depth: 2
16:02:49,611  INFO SettingsFactory:231 - Default batch fetch size: 1
16:02:49,611  INFO SettingsFactory:235 - Generate SQL with comments: disabled
16:02:49,611  INFO SettingsFactory:239 - Order SQL updates by primary key: disabled
16:02:49,611  INFO SettingsFactory:243 - Order SQL inserts for batching: disabled
16:02:49,611  INFO SettingsFactory:410 - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
16:02:49,611  INFO ASTQueryTranslatorFactory:47 - Using ASTQueryTranslatorFactory
16:02:49,611  INFO SettingsFactory:251 - Query language substitutions: {}
16:02:49,611  INFO SettingsFactory:256 - JPA-QL strict compliance: disabled
16:02:49,611  INFO SettingsFactory:261 - Second-level cache: enabled
16:02:49,611  INFO SettingsFactory:265 - Query cache: disabled
16:02:49,611  INFO SettingsFactory:395 - Cache region factory : org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge
16:02:49,611  INFO RegionFactoryCacheProviderBridge:61 - Cache provider: org.hibernate.cache.NoCacheProvider
16:02:49,611  INFO SettingsFactory:275 - Optimize cache for minimal puts: disabled
16:02:49,611  INFO SettingsFactory:284 - Structured second-level cache entries: disabled
16:02:49,611  INFO SettingsFactory:304 - Echoing all SQL to stdout
16:02:49,611  INFO SettingsFactory:313 - Statistics: disabled
16:02:49,611  INFO SettingsFactory:317 - Deleted entity synthetic identifier rollback: disabled
16:02:49,611  INFO SettingsFactory:332 - Default entity-mode: pojo
16:02:49,611  INFO SettingsFactory:336 - Named query checking : enabled
16:02:49,611  INFO SettingsFactory:340 - Check Nullability in Core (should be disabled when Bean Validation is on): enabled
16:02:49,626  INFO SessionFactoryImpl:199 - building session factory
16:02:49,736  INFO SessionFactoryObjectFactory:105 - Not binding factory to JNDI, no JNDI name configured
Hibernate: insert into EVENT (title, date) values (?, ?)


數據庫確認記錄導入。


附:

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>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="connection.username">root</property>
        <property name="connection.password">aaa</property>

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

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

        <!-- Enable Hibernate's current session context -->
        <property name="current_session_context_class">org.hibernate.context.ManagedSessionContext</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">create</property> -->

        <mapping resource="com/xinju/hibernate/Event.hbm.xml"/>

    </session-factory>

</hibernate-configuration>

映射文件Event.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 package="com.xinju.hibernate">

    <class name="Event" table="EVENT">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="title" type="string">
            <column name="title" />
        </property>
        <property name="date" type="date">
            <column name="date" length="10" />
        </property>

    </class>


</hibernate-mapping>

   Event實體類:

package com.xinju.hibernate;

// Generated 2015-2-27 11:46:36 by Hibernate Tools 3.4.0.CR1

import java.util.Date;

/**
 * Event generated by hbm2java
 */
public class Event implements java.io.Serializable {

	private Integer id;
	private String title;
	private Date date;

	public Event() {
	}

	public Event(String title, Date date) {
		this.title = title;
		this.date = date;
	}

	public Integer getId() {
		return this.id;
	}

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

	public String getTitle() {
		return this.title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public Date getDate() {
		return this.date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

}

hibernate工具類HibernateUtil:

package com.xinju.hibernate;

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

public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            sessionFactory = 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;
    }

}


測試代碼:

package com.xinju.hibernate;
import java.util.Date;
import org.hibernate.Session;

public class test {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Event e = new Event("t27",new Date());
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.getTransaction().begin();
		session.save(e);
		session.getTransaction().commit();		
	}
}


有問題多讀官方文檔,本身動手實踐。

相關文章
相關標籤/搜索