hibernate学习 hibernate-tutorials(一)——basic

1.配置hibernate的数据库连接

<!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">org.h2.Driver</property>
        <property name="connection.url">jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"/>
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.H2Dialect</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="org/hibernate/tutorial/hbm/Event.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
ps:如果使用xml配置,则 <mapping resource="org/hibernate/tutorial/hbm/Event.hbm.xml"/> 。 resource属性,注解则是class属性。

2.创建实体类Event.java


3.配置实体与数据库表的映射xml文件

<hibernate-mapping package="org.hibernate.tutorial.hbm">
    <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>

4.启动查询加载hibernate

sessionFactory = new Configuration()
                .configure() // configures settings from hibernate.cfg.xml
                .buildSessionFactory();

5. 获取session与数据库进行交互

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();
}

6.运行结果

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running org.hibernate.tutorial.hbm.NativeApiIllustrationTest
七月 16, 2016 7:15:30 下午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
七月 16, 2016 7:15:30 下午 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.11.Final}
七月 16, 2016 7:15:30 下午 org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
七月 16, 2016 7:15:30 下午 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
七月 16, 2016 7:15:30 下午 org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
七月 16, 2016 7:15:30 下午 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
七月 16, 2016 7:15:30 下午 org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: org/hibernate/tutorial/hbm/Event.hbm.xml
七月 16, 2016 7:15:30 下午 org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
七月 16, 2016 7:15:31 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
七月 16, 2016 7:15:31 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [org.h2.Driver] at URL [jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE]
七月 16, 2016 7:15:31 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=sa, password=****}
七月 16, 2016 7:15:31 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
七月 16, 2016 7:15:31 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
七月 16, 2016 7:15:31 下午 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
七月 16, 2016 7:15:31 下午 org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
七月 16, 2016 7:15:31 下午 org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
七月 16, 2016 7:15:31 下午 org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
七月 16, 2016 7:15:31 下午 org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
Hibernate: drop table EVENTS if exists
Hibernate: create table EVENTS (EVENT_ID bigint not null, EVENT_DATE timestamp, title varchar(255), primary key (EVENT_ID))
七月 16, 2016 7:15:31 下午 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 EVENT_ID1_0_, event0_.EVENT_DATE as EVENT_DA2_0_, event0_.title as title3_0_ from EVENTS event0_
Event (2016-07-16 19:15:31.74) : Our very first event!
Event (2016-07-16 19:15:31.827) : A follow up event
七月 16, 2016 7:15:31 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE]
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.659 sec

由于实体配置的主键生成是<generator class="increment"/> ,所以事务开始新增记录时,会查询最大值后加1。这种方法适合所有数据库。
select max(EVENT_ID) from EVENTS

项目源码参考(readme文件有相关测试运行的命令):

 git@code.csdn.net:xiaozaq/hibernate-tutorials.git



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值