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