`
zxsqi
  • 浏览: 28118 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

hibernate 4.1.5 学习笔记(1)

阅读更多

hibernate 学习记录:

 

1. 在eclipse中新建一个web项目,然后添加hibernate 4.1.5中的jar包到项目中,主要是“hibernate-release-4.1.5.Final\lib\required”  目录中的jar包

 

2. 由于我使用的mysql 5.0 ,所以要添加 mysql-connector的jar包到项目中。

 

3. 添加junit的jar包到项目中,因为项目测试要用到这个jar包

 

4.在mysql 中建立一个数据库,在hibernate的配置文件中要用到,例如:buy360 

 

5.在项目的src 目录下添加 hibernate.cfg.xml 内容如下:

 

 

<?xml version='1.0' encoding='utf-8'?>
<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ Copyright (c) 2010, Red Hat Inc. or third-party contributors as
  ~ indicated by the @author tags or express copyright attribution
  ~ statements applied by the authors.  All third-party contributions are
  ~ distributed under license by Red Hat Inc.
  ~
  ~ This copyrighted material is made available to anyone wishing to use, modify,
  ~ copy, or redistribute it subject to the terms and conditions of the GNU
  ~ Lesser General Public License, as published by the Free Software Foundation.
  ~
  ~ This program is distributed in the hope that it will be useful,
  ~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  ~ or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
  ~ for more details.
  ~
  ~ You should have received a copy of the GNU Lesser General Public License
  ~ along with this distribution; if not, write to:
  ~ Free Software Foundation, Inc.
  ~ 51 Franklin Street, Fifth Floor
  ~ Boston, MA  02110-1301  USA
  -->
<!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/buy360</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

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

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

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.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/buy/user/Event.hbm.xml"/>

    </session-factory>

</hibernate-configuration>

 

6. 然后创建一个实体类(javabean) , 代码如下:

 

 

/*
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
 * indicated by the @author tags or express copyright attribution
 * statements applied by the authors.  All third-party contributions are
 * distributed under license by Red Hat Inc.
 *
 * This copyrighted material is made available to anyone wishing to use, modify,
 * copy, or redistribute it subject to the terms and conditions of the GNU
 * Lesser General Public License, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this distribution; if not, write to:
 * Free Software Foundation, Inc.
 * 51 Franklin Street, Fifth Floor
 * Boston, MA  02110-1301  USA
 */
package com.buy.user;

import java.util.Date;

public class Event {
	private Long id;

	private String title;
	private Date date;

	public Event() {
		// this form used by Hibernate
	}

	public Event(String title, Date date) {
		// for application use, to create new events
		this.title = title;
		this.date = date;
	}

	public Long getId() {
		return id;
	}

	private void setId(Long id) {
		this.id = id;
	}

	public Date getDate() {
		return date;
	}

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

	public String getTitle() {
		return title;
	}

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

 

7. 在实体类的目录下,添加 Events.hbm.xml , 内容如下:

 

 

<?xml version="1.0"?>

<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ Copyright (c) 2010, Red Hat Inc. or third-party contributors as
  ~ indicated by the @author tags or express copyright attribution
  ~ statements applied by the authors.  All third-party contributions are
  ~ distributed under license by Red Hat Inc.
  ~
  ~ This copyrighted material is made available to anyone wishing to use, modify,
  ~ copy, or redistribute it subject to the terms and conditions of the GNU
  ~ Lesser General Public License, as published by the Free Software Foundation.
  ~
  ~ This program is distributed in the hope that it will be useful,
  ~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  ~ or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
  ~ for more details.
  ~
  ~ You should have received a copy of the GNU Lesser General Public License
  ~ along with this distribution; if not, write to:
  ~ Free Software Foundation, Inc.
  ~ 51 Franklin Street, Fifth Floor
  ~ Boston, MA  02110-1301  USA
  -->

<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.buy.user">

    <class name="Event" table="EVENTS">
        <id name="id" column="EVENT_ID">
            <generator class="increment"/>
        </id>
        <property name="date" type="timestamp" column="EVENT_DATE"/>
        <property name="title"/>
    </class>

</hibernate-mapping>

 

8. 然后创建一个测试类AnnotationsIllustrationTest.java ,代码如下:

 

 

/*
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
 * indicated by the @author tags or express copyright attribution
 * statements applied by the authors.  All third-party contributions are
 * distributed under license by Red Hat Inc.
 *
 * This copyrighted material is made available to anyone wishing to use, modify,
 * copy, or redistribute it subject to the terms and conditions of the GNU
 * Lesser General Public License, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this distribution; if not, write to:
 * Free Software Foundation, Inc.
 * 51 Franklin Street, Fifth Floor
 * Boston, MA  02110-1301  USA
 */
package com.buy.user.test;

import java.util.Date;
import java.util.List;

import junit.framework.TestCase;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import com.buy.user.Event;

/**
 * Illustrates the use of Hibernate native APIs.  The code here is unchanged from the {@code basic} example, the
 * only difference being the use of annotations to supply the metadata instead of Hibernate mapping files.
 *
 * @author Steve Ebersole
 */
public class AnnotationsIllustrationTest extends TestCase {
	private SessionFactory sessionFactory;
	private ServiceRegistry serviceRegistry;

	@Override
	protected void setUp() throws Exception {
		// A SessionFactory is set up once for an application
		Configuration cfg = new Configuration();  
        cfg.configure(); 
		serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
        sessionFactory = new Configuration()
                .configure() // configures settings from hibernate.cfg.xml
                .buildSessionFactory(serviceRegistry);
	}

	@Override
	protected void tearDown() throws Exception {
		if ( sessionFactory != null ) {
			sessionFactory.close();
		}
	}

	@SuppressWarnings({ "unchecked" })
	public void testBasicUsage() {
		// create a couple of events...
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.save( new Event( "Our very first event!", new Date() ) );
		session.save( new Event( "A follow up event", new Date() ) );
		session.getTransaction().commit();
		session.close();

		// now lets pull events from the database and list them
		session = sessionFactory.openSession();
        session.beginTransaction();
        List result = session.createQuery( "from Event" ).list();
		for ( Event event : (List<Event>) result ) {
			System.out.println( "Event (" + event.getDate() + ") : " + event.getTitle() );
		}
        session.getTransaction().commit();
        session.close();
	}
}

 

9. 运行测试类,出现下列结果,表示成功。

 

 

2012-7-18 14:27:37 org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
2012-7-18 14:27:37 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.5.Final}
2012-7-18 14:27:37 org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
2012-7-18 14:27:37 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
2012-7-18 14:27:37 org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
2012-7-18 14:27:37 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
2012-7-18 14:27:38 org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: com/buy/user/Event.hbm.xml
2012-7-18 14:27:38 org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
2012-7-18 14:27:38 org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
2012-7-18 14:27:38 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
2012-7-18 14:27:38 org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: com/buy/user/Event.hbm.xml
2012-7-18 14:27:38 org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
2012-7-18 14:27:39 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
2012-7-18 14:27:39 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 1
2012-7-18 14:27:39 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
2012-7-18 14:27:39 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/buy360]
2012-7-18 14:27:39 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=root, password=****}
2012-7-18 14:27:40 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2012-7-18 14:27:40 org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
2012-7-18 14:27:40 org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
2012-7-18 14:27:40 org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
2012-7-18 14:27:41 org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
Hibernate: drop table if exists EVENTS
Hibernate: create table EVENTS (EVENT_ID bigint not null, EVENT_DATE datetime, title varchar(255), primary key (EVENT_ID))
2012-7-18 14:27:41 org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: select max(EVENT_ID) from EVENTS
Hibernate: insert into EVENTS (EVENT_DATE, title, EVENT_ID) values (?, ?, ?)
Hibernate: insert into EVENTS (EVENT_DATE, title, EVENT_ID) values (?, ?, ?)
Hibernate: select event0_.EVENT_ID as EVENT1_0_, event0_.EVENT_DATE as EVENT2_0_, event0_.title as title0_ from EVENTS event0_
Event (2012-07-18 14:27:41.0) : Our very first event!
Event (2012-07-18 14:27:41.0) : A follow up event
分享到:
评论

相关推荐

    hibernate 4.1.5 source code

    1. JPA支持:在4.1.5版本中,Hibernate进一步增强了对Java Persistence API (JPA)的支持,使得开发者可以同时利用JPA的规范和Hibernate的高级特性。 2. 第二代Criteria API:此版本改进了Criteria API,使其更加...

    Hibernate 4.1.5 SP1 API chm格式

    Hibernate 4.1.5 SP1 API chm格式方便携带和查询 如果文件打开看不到右边的内容,是因为你的操作系统为了安全对下载的chm文件进行了锁定,只需要在打开前右键单击该chm文件选择“属性”,然后在“常规”选项卡的...

    Hibernate-4.1.5-API

    Hibernate4.1.5的API文档,英文版

    hibernate-release-4.1.5.SP1

    《Hibernate 4.1.5.SP1:持久化框架的核心技术与应用》 Hibernate,作为Java领域中的一个著名对象关系映射(ORM)框架,它极大地简化了数据库操作,使得开发者能够以面向对象的方式处理数据库交互。本次我们将深入...

    hibernate-release-4.1.5.SP1.zip

    《Hibernate 4.1.5.SP1:Java ORM框架的核心技术与实践》 Hibernate,作为Java领域中的一个著名对象关系映射(ORM)框架,它极大地简化了数据库操作,使得开发者能够以面向对象的方式处理数据库交互。这次我们关注...

    spring-3.2.0+struts-2.3.4+hibernate-4.1.5

    本人的此jar合集只能保证SSH2的基础环境,至于更复杂的功能,可能此集合已经包含,或者您可以从您下载的Spring或者hibernate或者struts中寻找您需要的jar包,按要求添加即可。 【因本人能力有限,不能保证此jar集合...

    struts2.3.2+hibernate4.3.8+spring4.1.5整合jar包

    在这个"struts2.3.2+hibernate4.3.8+spring4.1.5整合jar包"中,包含了这三个框架的特定版本,这些版本被广泛认为是稳定且兼容的,适合用于实际项目开发。 Struts2是一个MVC(Model-View-Controller)框架,主要用于...

    spring-3.2.0+struts-1.3.10+hibernate-4.1.5

    本人的此jar合集只能保证SSH2的基础环境,至于更复杂的功能,可能此集合已经包含,或者您可以从您下载的Spring或者hibernate或者struts中寻找您需要的jar包,按要求添加即可。 【因本人能力有限,不能保证此jar集合...

    Struts2.3.20Spring4.1.5Hibernate4.3.8整合

    关于目前最新S2SH版本的整合测试,Struts2.3.20、Spring4.1.5、Hibernate4.3.8

    spring 4.1.5 官方lib包

    1. **Spring Core**:这是框架的基础,提供IoC容器和DI服务,管理应用对象的生命周期和依赖关系。 2. **Spring Beans**:定义了如何创建、配置和管理应用中的bean。XML和Java配置都是可选的,4.1.5版本对这两种方式...

    artdialog4.1.5

    1. **基本使用**: 使用artdialog4.1.5时,你需要在HTML文件中引入必要的CSS和JavaScript文件。通常,这包括`artDialog.css`和`artDialog.js`,以及可能的皮肤文件。之后,你可以通过JavaScript调用artdialog函数来...

    SSH整合jar包--spring4.1.5 hibernate4.3.1 struts2.2.1

    1. **Spring框架**(4.1.5版本):Spring是Java企业级应用的基石,它提供了全面的编程和配置模型,使得开发者可以专注于业务逻辑而不是基础设施。在4.1.5版本中,Spring加强了对Java 8的支持,改进了数据访问层,...

    mapper-4.1.5.jar

    tk.mabatis的jar包 4.1.5版本。可参考以下方式使用 &lt;tk-mapper.version&gt;4.1.5 &lt;pagehelper.version&gt;1.2.10 &lt;!-- Mybatis通用Mapper --&gt; &lt;groupId&gt;tk.mybatis &lt;artifactId&gt;mapper ${tk-...

    httpasyncclient-4.1.5-API文档-中文版.zip

    赠送jar包:httpasyncclient-4.1.5.jar; 赠送原API文档:httpasyncclient-4.1.5-javadoc.jar; 赠送源代码:httpasyncclient-4.1.5-sources.jar; 赠送Maven依赖信息文件:httpasyncclient-4.1.5.pom; 包含翻译后...

    Spring4.1.5-javadoc-api.rar

    数据访问与集成(Data Access/Integration)模块是Spring处理数据库操作的关键,包括JDBC、ORM(对象关系映射)支持如Hibernate、MyBatis等,以及JPA(Java Persistence API)。Spring MVC作为Web开发的一部分,提供...

    Spring Framework4.1.5

    4.1.5版本对JPA和Hibernate的支持更加完善,事务管理也更为智能化,可以更好地适应各种数据库环境。 四、Web层 Spring的Web MVC框架在4.1.5版本中提供了对RESTful风格的支持,包括JSON绑定和HTTP方法约束。同时,它...

    eLabsim4.1.5.exe

    eLabsim4.1.5.exe

    hibernate-release-5.4.15.Final.zip

    1. **实体管理**:Hibernate的核心功能之一是实体管理,通过注解或者XML配置,可以将Java对象映射到数据库表,使得开发者可以使用对象来操作数据,而不是SQL语句。 2. **持久化模型**:Hibernate支持JPA(Java ...

    zeromq-4.1.5.zip

    zeromq-4.1.5.zip ZeroMQ \zero-em-queue\, \ØMQ\:  Ø  Connect your code in any language, on any platform.  Ø  Carries messages across inproc, IPC, TCP, TIPC, multicast.  Ø  Smart patterns ...

    FlashFXP_4.1.5

    FlashFXP 4.1.5 破解 支持SFTP协议

Global site tag (gtag.js) - Google Analytics