Hibernate快速入门

参考:http://docs.jboss.org/hibernate/orm/5.1/quickstart/html_single/

下载:http://sourceforge.net/projects/hibernate/files/hibernate-orm/5.1.0.Final/hibernate-release-5.1.0.Final.zip/download

1. bootstrap a hibernate SessionFactory

编写hibernate配置文件hibernate.cfg.xml,放在classpath下。

<?xml version='1.0' encoding='utf-8'?>
<!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>
        <!-- 数据库连接设置 -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql:///test</property>
        <property name="connection.username">duan</property>
        <property name="connection.password">123456</property>

        <!-- 数据库连接池设置(内置的,并没有什么用) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL方言 -->
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>

        <!-- 禁用二级缓存  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- 在标准输出流显示执行的SQL -->
        <property name="show_sql">true</property>

        <!-- 启动的时候重建数据库 -->
        <property name="hbm2ddl.auto">create</property>

        <!-- 使用了注解的映射实体类 -->
        <mapping class="org.hibernate.tutorial.annotations.Event"/>

    </session-factory>
</hibernate-configuration>

2. use annotations to provide mapping information

编写使用了注解的映射实体类Event.java。如何使用注解参考:http://www.cnblogs.com/hippiebaby/p/5465725.html

@Entity
@Table( name = "EVENTS" )
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;
    }

    @Id
    @GeneratedValue
    public Long getId() {
        return id;
    }

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

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "EVENT_DATE")
    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;
    }
}

3. use the hibernate native APIs

用JUnit测试。

public class AnnotationsIllustrationTest extends TestCase {
    private SessionFactory sessionFactory;

    @Override
    protected void setUp() throws Exception {
        // 在应用中SessionFactory只在开始的时候配置一次
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                    .configure() // 默认从hibernate.cfg.xml中获取配置
                    .build();
        try {
            sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
        } catch (Exception e) {
            // The registry would be destroyed by the SessionFactory, 
            // but we had trouble building the SessionFactory.
            // so destroy it manually.
            StandardServiceRegistryBuilder.destroy( registry );
        }
    }
    
    @Override
    protected void tearDown() throws Exception {
        if ( sessionFactory != null ) {
            sessionFactory.close();
        }
    }
    
    @SuppressWarnings({ "unchecked" })
    public void testBasicUsage() {
        // 从SessionFactory中获得Session
        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
        session.close();

        session = sessionFactory.openSession();
        session.beginTransaction();
        // 查询所有的Event
        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();
    }
}
原文地址:https://www.cnblogs.com/hippiebaby/p/5510163.html