Hibernate4 测试类(新的hibernate使用方法)

package com.qhn;

import static org.junit.Assert.*;

import java.sql.Date;

import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.Test;

@SuppressWarnings("deprecation")
public class HibernateTest {

    @Test
    public void test() {

        //1. SessionFectory

        SessionFactory sessionFactory = null;

        Configuration configuration = new Configuration().configure();

        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
            .applySettings(configuration.getProperties())
            .buildServiceRegistry();

        sessionFactory = configuration.buildSessionFactory(serviceRegistry);

        //2. Sesson

        Session session = sessionFactory.openSession();

        //3. 开启事务

        Transaction transaction = session.beginTransaction();

        //4. 执行保存操作

        News news = new News("java","HI",new Date(new java.util.Date().getTime()));

        session.save(news);

        //5. 提交事物

        transaction.commit();

        //6. 关闭Session

        session.close();

        //7. 关闭SessionFectory

        sessionFactory.close();
    }

}

你可能感兴趣的:(Hibernate,Java,IntelliJ,IDEA)