`
shenshuibomb
  • 浏览: 25673 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
社区版块
存档分类
最新评论

A simple Hibernate sample

阅读更多

Some days ago. I bought a book named Java Persistence with Hibernate.

Now , I will show a simple sample for everybody who wanna learn the skill of Hibernate.

Step one.

Create a class named Message,Of course ,you should have created a project in IDE.

Message.java
package hello;

public class Message {
private Long id;
private String text;
private Message nextMessage;
Message()
{

}
public Message(String text)
{
this.text = text;
}
public Long getId() {
return id;
}

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

public Message getNextMessage() {
return nextMessage;
}

public void setNextMessage(Message nextMessage) {
this.nextMessage = nextMessage;
}

public String getText() {
return text;
}

public void setText(String text) {
this.text = text;
}

}


Step two.

create a XML named Message.hbm.xml.Just like the following.

Message.hbm.xml

<?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="hello.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>

Step three.

Write you property file.

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>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@126.1.1.63:1521:oradb</property>
<property name="hibernate.connection.username">timesheet</property>
<property name="hibernate.connection.password">timesheet</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.use_sql_comments">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping resource="hello/Message.hbm.xml"/>
</session-factory>
</hibernate-configuration>

Step four

Configurating you DataBase,and run the main method like this

Oh.I forgot that ,before you run this project ,you'd better create a manage bena for Hibernate.

I write a class named HibernateUtil.

HibernateUtil.java

package persistence;

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

public class HibernateUtil {
private static SessionFactory sessionFactory;
static
{
try
{
sessionFactory = new Configuration().configure().buildSessionFactory();
}
catch(Throwable ex)
{
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
public static void shutdown()
{
getSessionFactory().close();
}
}

then you should have the Main Class lik this.


package hello;

import org.hibernate.*;
import java.util.*;
import persistence.*;

/**
*
* @author zhangqi
*/
public class HelloWorld {

public static void main(String[] args)
{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Message message = new Message("Hello World2");
Long msgId =(Long)session.save(message);
System.out.println(msgId);
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 iter = messages.iterator();iter.hasNext();)
{
Message loadedMsg =(Message)iter.next();
System.out.println(loadedMsg.getId() +" "+loadedMsg.getText());
}
newTx.commit();;
newSession.close();
HibernateUtil.shutdown();

}
}
Yeah.run it ,you will get the answer

分享到:
评论

相关推荐

    java轻量级ORM实现-jorm (Just ORM)

    Hibernate support, and a similar sample of queries; Support additional SQL clause, an extension of inquiries; Support for optimistic locking; A rich set of tools for SQL statements;

    Getting.started.with.Spring.Framework.2nd.Edition1491011912.epub

    The book shows a simple internet banking application that is developed incrementally in each chapter of the book and covers the topics mentioned above. You can post your feedback and questions to the ...

    Manning - Eclipse In Action.pdf

    - **Sample Plug-ins**: Examples of simple plug-ins to illustrate key concepts and best practices. **Chapter 9: Working with Plug-ins in Eclipse** - **Managing Plug-ins**: Techniques for installing, ...

    jpa-showcase:jpa展示柜

    + Simple examples of CRUD in JPA + Demo QUERY and TYPEDQUERY + Configuration of JPA using Hibernate Provider - jpa-sample-02: + Examples of type mappings + Examples of Large Object Mapping, ...

    ibatis与spring整合

    &lt;dataSource type="SIMPLE"&gt; &lt;property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost/sample"/&gt; &lt;property name="Pool.PingQuery" value="select 1 from sample"/&gt; ``` ...

    ibatis简单实现与配置

    &lt;property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost/sample"/&gt; ``` 4. 数据源配置还包含了池相关的参数,如`Pool.MaximumIdleConnections`(最大空闲连接数)和`Pool.MaximumCheckoutTime`...

    xmlbean轻轻松松读写XML的利器

    **XMLBean**是一款类似于Hibernate这样的对象关系映射(Object Relational Mapping,ORM)工具的产品,它将复杂的XML读写操作简化为对JavaBean的操作,从而极大地简化了XML的读写过程,使得即使是不熟悉XML的开发者...

Global site tag (gtag.js) - Google Analytics