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. 运行测试

    Hibernate: 十一月 01, 2018 11:54:51 上午 org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection

    INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@6df20ade] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
       
       drop table if exists EVENTS

    十一月 01, 2018 11:54:51 上午 org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
    INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@cda4919] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
    Hibernate:
       
       create table EVENTS (
          EVENTS_ID bigint not null,
           EVENT_DATE datetime(6),
           title varchar(255),
           primary key (EVENTS_ID)
      ) engine=InnoDB
    十一月 01, 2018 11:54:52 上午 org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
    INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@344b8190'
    Hibernate:
       select
           max(EVENTS_ID)
       from
           EVENTS
    Hibernate:    insert    into        EVENTS       (EVENT_DATE, title, EVENTS_ID)    values       (?, ?, ?)Hibernate:    insert    into        EVENTS       (EVENT_DATE, title, EVENTS_ID)    values       (?, ?, ?)十一月 01, 2018 11:54:52 上午 org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateServiceINFO: HHH000397: Using ASTQueryTranslatorFactoryHibernate:    select        event0_.EVENTS_ID as EVENTS_I1_0_,        event0_.EVENT_DATE as EVENT_DA2_0_,        event0_.title as title3_0_    from        EVENTS event0_​十一月 01, 2018 11:54:52 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop

猜你喜欢

转载自www.cnblogs.com/htsg/p/9888578.html