码迷,mamicode.com
首页 > Web开发 > 详细

hibernate + maven: helloworld

时间:2014-10-30 15:13:36      阅读:368      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   os   ar   java   for   

 

http://blog.163.com/yandong_8212/blog/static/132153914201389104248638/

 

1. 准备工作: 参考书籍:JAVA PERSISTENCE with HIBERNATE
mave插件:m2e

2. 通过maven创建一个quickstart 的maven工程,并新建一个src/main/resources的source folder用来存放资源文件。
3. 修改pom文件,最简单的helloworld只需要增加hibernate和hsqldb:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.shev</groupId>
<artifactId>hibernate_helloworld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>hibernate_helloworld</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.2.5.Final</version>
</dependency>


<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb-j5</artifactId>
<version>2.2.4</version>
</dependency>


</dependencies>
</project>

 
4. 新建一个Bean, 在src/main/java下新建一个com.shev.hibernate_helloworld 包,并建一个Message 类。

package com.shev.hibernate_helloworld;

public class Message {
private Long id;
private String text;
private Message nextMessage;
public Message() {
super();
// TODO Auto-generated constructor stub
}


public Message(String text) {
super();
this.text = text;
}


public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Message getNextMessage() {
return nextMessage;
}
public void setNextMessage(Message nextMessage) {
this.nextMessage = nextMessage;
}
}

5. src/main/resources下,新建Message.hbm.xml,定义Bean到数据库字段的映射关系:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.shev.hibernate_helloworld.Message" table="MESSAGES">
<id name="id" column="MESSAGE_ID">
<generator class="increment" />
</id>
<property name="text" column="MESSAGE_TEXT" />
<many-to-one
name="nextMessage"
cascade="all"
column="NEXT_MESSAGE_ID"
foreign-key="FK_NEXT_MESSAGE" />
</class>
</hibernate-mapping>

6. src/main/resources下,新建hibernate.cfg.xml定义数据库连接信息等:

<!DOCTYPE hibernate-configuration SYSTEM
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">
org.hsqldb.jdbcDriver
</property>
<property name="hibernate.connection.url">
jdbc:hsqldb:hsql://localhost
</property>
<property name="hibernate.connection.username">
sa
</property>

<property name="hibernate.dialect">
org.hibernate.dialect.HSQLDialect
</property>
<!-- Use the C3P0 connection pool provider -->
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<!-- Show and print nice SQL on stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- List of XML mapping files -->
<mapping resource="Message.hbm.xml" />
</session-factory>
</hibernate-configuration>

7. src/main/java新建HibernateUtil类:

package com.shev.hibernate_helloworld;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.hbm2ddl.SchemaValidator;

public class HibernateUtil {
private static SessionFactory sessionFactory;

static {
Configuration cfg = new Configuration().configure();

 

//SchemaExport是hibernate自带的操作数据库和产生DDL的工具类。
SchemaExport schemaExport = new SchemaExport(cfg);

 

//注意这里第一个参数表示是否输出到控制台,第二个参数表示是否在数据库中执行。这里这样用的目的是,避免每次都去新create一个表,因为默认生成的DDL,当发现有表存在时,会自动删除。因此最好的办法是输出SQL,让DBA去创建。
schemaExport.create(true, false);

 

//如果表跟当前定义不匹配,将会抛出异常。
new SchemaValidator(cfg).validate();

sessionFactory = cfg.buildSessionFactory();
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}

public static void shutdown() {
getSessionFactory().close();
}
}

8. src/main/java下新建HellowWorld类:

package com.shev.hibernate_helloworld;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;


public class HelloWorld {
public static void main(String[] args) {
System.out.println(System.getProperty("user.dir"));//

// First unit of work
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();

Message message = new Message("Hello World");
Long msgId = (Long)session.save(message);
tx.commit();
session.close();

Session newSession = HibernateUtil.getSessionFactory().openSession();
Transaction newTx = newSession.beginTransaction();
List messages = newSession.createQuery("from Message m order by m.text asc").list();
System.out.println(messages.size() + " message(s) found:");

for (Iterator it = messages.iterator(); it.hasNext(); ) {
Message msg = (Message)it.next(); System.out.println(msg.getText()); } newTx.commit(); newSession.close(); HibernateUtil.shutdown(); }}

9. 启动hsqldb.Server:

C:\Users\CW>java -classpath C:\Users\CW\.m2\repository\org\hsqldb\hsqldb-j5\2.2.4\hsqldb-j5-2.2.4.jar org.hsqldb.Server

10. 启动hsqldbManager:

C:\Users\CW>java -classpath C:\Users\CW\.m2\repository\org\hsqldb\hsqldb-j5\2.2.4\hsqldb-j5-2.2.4.jar org.hsqldb.util.DatabaseManagerSwing -url jdbc:hsqldb:hsql://localhost/ -driver org.hsqldb.jdbcDriver

11. maven package打包
12. 运行HelloWorld.java,第一次会抛出异常,不用管它,只需要将下面的语句复制到hsqldbManager中执行:

alter table MESSAGES
drop constraint FK_NEXT_MESSAGE //这两句忽略,可能会报错

drop table MESSAGES if exists

create table MESSAGES (
MESSAGE_ID bigint not null,
MESSAGE_TEXT varchar(255),
NEXT_MESSAGE_ID bigint,
primary key (MESSAGE_ID)
)

alter table MESSAGES
add constraint FK_NEXT_MESSAGE
foreign key (NEXT_MESSAGE_ID)
references MESSAGES

13. 再次运行HellowWorld.java:

...

Hibernate:
select
max(MESSAGE_ID)
from
MESSAGES
Hibernate:
insert
into
MESSAGES
(MESSAGE_TEXT, NEXT_MESSAGE_ID, MESSAGE_ID)
values
(?, ?, ?)
Hibernate:
select
message0_.MESSAGE_ID as MESSAGE_1_0_,
message0_.MESSAGE_TEXT as MESSAGE_2_0_,
message0_.NEXT_MESSAGE_ID as NEXT_MES3_0_
from
MESSAGES message0_
order by
message0_.MESSAGE_TEXT asc
1 message(s) found:
Hello World
九月 09, 2013 11:03:22 上午 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:hsqldb:hsql://localhost]

hsqldbManager里面的界面:
bubuko.com,布布扣

hibernate + maven: helloworld

标签:style   blog   http   io   color   os   ar   java   for   

原文地址:http://www.cnblogs.com/qufanblog/p/4062540.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!