Hibernate 5 入门指南-基于类注解

  1. 首先创建hibernate.cfg.xml配置文件并做简单的配置

    <hibernate-configuration>
       <session-factory>
           <!-- Database connection settings -->
           <property name="connection.url">jdbc:mysql://localhost:3306/databaseName?useSSL=false&amp;serverTimezone=UTC&amp;verifyServerCertifate=false&amp;allowPublicKeyRetrieval=true</property>
           <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
           <property name="connection.username">root</property>
           <property name="connection.password">passwd</property>

           <!-- SQL dialect -->
           <property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>

           <!-- Echo all executed SQL to stdout -->
           <property name="show_sql">true</property>
           <property name="format_sql">true</property>

           <!-- Drop and re-create the database schema on startup -->
           <property name="hbm2ddl.auto">create</property>

           <!-- JDBC connection pool (use the built-in) -->
           <property name="connection.pool_size">1</property>

           <!-- Disable the second-level cache -->
           <property name="cache.provider_class">org.hibernate.cache.internal.NoCachingRegionFactory</property>
       </session-factory>
    </hibernate-configuration>
  2. 创建实体Java类

    import java.util.Date;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Table;
    import javax.persistence.Temporal;
    import javax.persistence.TemporalType;

    import org.hibernate.annotations.GenericGenerator;

    @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(generator="increment")
       @GenericGenerator(name="increment", strategy = "increment")
       @Column(name = "EVENTS_ID")
       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. 向hibernate.cfg.xml文件中添加映射信息

    <mapping class="类路径.Event"/>
  4. JUnit测试测试程序

    import java.util.Date;
    import java.util.List;

    import junit.framework.TestCase;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.boot.MetadataSources;
    import org.hibernate.boot.registry.StandardServiceRegistry;
    import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

    public class AnnotationsIllustrationTest extends TestCase {
       private SessionFactory sessionFactory;

       @Override
       protected void setUp() throws Exception {
           // A SessionFactory is set up once for an application!
           final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                  .configure() // configures settings from 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() {
           // 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();   }}
  5. 运行测试

上一篇:如何使用Iveely的数据存储引擎 Iveely Database


下一篇:一起学习造*(二):从零开始写一个Redux