Hibernate demo之使用注解

1.新建maven项目 testHibernate,pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>testHibernateAnno</groupId>
    <artifactId>testHibernateAnno</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <!-- 添加Hibernate依赖 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>3.6.10.Final</version>
        </dependency>

        <!-- 添加Log4J依赖 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-nop</artifactId>
            <version>1.6.4</version>
        </dependency>

        <!-- 添加javassist -->
        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.12.0.GA</version>
        </dependency>

        <!-- mysql数据库的驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>




    </dependencies>


</project>
View Code

2.在resource文件夹下新建hibernate.cfg.xml文件

<?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>
        <!-- Database connection settings -->
        <property name="connection.driver_class">org.gjt.mm.mysql.Driver</property>
        <property name="connection.url">jdbc:mysql://192.168.32.95:3306/db2</property>
        <property name="connection.username">DB_WX_APP</property>
        <property name="connection.password">LH_longfor</property>
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</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">update</property>
        <!--<mapping resource="mapper/Event.hbm.xml"/>-->
    </session-factory>
</hibernate-configuration>
View Code

3.新建实体类 Event.java

package com.demo.demo;

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


  @Entity
  @Table(name="EVENTS")
public class Event {
      @Id
      @Column(name = "EVENT_ID")
    private Long id;//id
      @Column(name = "TITLE")
    private String title;//标题
      @Column(name = "EVENT_DATE")
    private Date date;//日期
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }
}
View Code

4.新建测试类 Test.java

package com.demo.demo;

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

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


public class Test {
    private static SessionFactory factory;
    /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Test mgr = new Test();
            try{
                factory = new AnnotationConfiguration().
                        configure().
                        //addPackage("com.xyz") //add package if used.
                                addAnnotatedClass(Event.class).
                                buildSessionFactory();
            }catch (Throwable ex) {
                System.err.println("Failed to create sessionFactory object." + ex);
                throw new ExceptionInInitializerError(ex);
            }

            Event e=new Event();
          e.setId(10011L);
          e.setTitle("aaa");
          e.setDate(new Date());

          Session sesion=factory.openSession();
          sesion.beginTransaction();
          sesion.save(e);
          sesion.getTransaction().commit();
          System.out.println("OK");


        }



}
View Code

运行test类,输出OK

 

  在hibernate4之后就移除了AnnotationConfiguration()方法了,Configuration已经包含了注解的方法,所以你可以直接用:

Configuration con = new Configuration();
SessionFactory sf = con.configure().buildSessionFactory();
Session s = sf.openSession();

 

来获得用注解声明映射关系的Session了,加上配置:

  <mapping class="student.Teacher"/>

就OK了,方便了很多。

 

但在配置过程中我还报了一个错误:

1
No identifier specified for entity: student.Teacher

  这是因为我把主键id的注解加在了setId上,把他加在getId上就解决了。(真是粗心)

 

https://pan.baidu.com/s/1ayir_7wk20y9CESFvCa2qg

posted @ 2018-02-05 09:51  甜菜波波  阅读(265)  评论(0编辑  收藏  举报