• 重拾Hibernate(1)之环境配置


    1、新建Web Project工程

    2、导入所需jar包

       

    3、Student.java

    package com.itmyhome;
    
    import javax.persistence.Entity;
    import javax.persistence.Table;
    
    @Entity
    @Table(name="T_STUDENT")
    public class Student extends BizEntity{
    	private String name;
    	private String score;
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public String getScore() {
    		return score;
    	}
    	public void setScore(String score) {
    		this.score = score;
    	}
    	
    }
    


    Teacher.java

    package com.itmyhome;
    
    import javax.persistence.Entity;
    import javax.persistence.Table;
    
    @Entity
    @Table(name="T_TEACHER")
    public class Teacher extends BizEntity{
    	private String name;
    	private String title;
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public String getTitle() {
    		return title;
    	}
    	public void setTitle(String title) {
    		this.title = title;
    	}
    	
    }
    


    BizEntity.java

    package com.itmyhome;
    
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import org.hibernate.annotations.GenericGenerator;
    
    public class BizEntity {
    	private String id;
    
    	@Id @GeneratedValue(strategy=GenerationType.AUTO,generator="bizGenerator")
    	@GenericGenerator(strategy = "uuid", name = "bizGenerator")
    	public String getId() {
    		return id;
    	}
    
    	public void setId(String id) {
    		this.id = id;
    	}
    
    	
    
    	
    }
    


    BizEntity.java是所有实体类的父类,id自动生成策略为uuid

    4、hibernate.hbm.xml

    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC
            "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
            "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    
    <hibernate-mapping>
    		<property name="dialect">org.hibernate.dialect.OracleDialect</property>
    		<property name="connection.url">jdbc:oracle:thin:@172.16.1.4:1521:orcl</property>
    		<property name="connection.username">username</property>
    		<property name="connection.password">123</property>
    		<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
    		<property name="current_session_context_class">thred</property>
    		
    		<property name="show_sql">true</property>
    		<property name="format_sql">true</property>
    		<property name="hbm2ddl.auto">true</property>
    
    </hibernate-mapping>


    5、Test.java测试

    package com.itmyhome;
    
    import org.hibernate.cfg.AnnotationConfiguration;
    import org.hibernate.tool.hbm2ddl.SchemaExport;
    
    public class Test {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		//new SchemaExport(new AnnotationConfiguration().configure()).create(true, true);
                      Teacher t = new Teacher();
                      t.setName("张三");
      
                      Configuration cfg = new AnnotationConfiguration();
                      SessionFactory factory =cfg.configure().buildSessionFactory();
                      Session session = factory.openSession();
                      session.beginTransaction();
                      session.save(t);
                      session.getTransaction().commit();
    	}
    }

    SchemaExport自动生成数据表

    运行程序:

    SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
    SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
    Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder


    此错误是缺少slf4j-nop.x.jar包   添加一个该包(slf4j-nop-1.5.8.jar)

    Exception in thread "main" java.lang.IllegalAccessError: tried to access field org.slf4j.impl.StaticLoggerBinder.SINGLETON from class org.slf4j.LoggerFactory

    此错误是slf4j版本错误。slf4j-api是1.5.2而slf4j-nop是1.5.8

    删除slf4j-api.1.5.2添加一个1.5.8的

    Exception in thread "main" java.lang.NoClassDefFoundError: org/hibernate/annotations/common/reflection/ReflectionManager
    


    此错误是少一个jar包,引入hibernate-commons-annotations.jar

    Caused by: org.xml.sax.SAXParseException: The content of element type "property" must match "(meta*,(column|formula)*,type?)".
    	at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:236)


    此错误是hibernate-cfg.xml配置文件错误(刚开始我是从文档中copy的,而那个是mapping实体类的映射文件)

    <?xml version="1.0"?>
    <!DOCTYPE hibernate-configuration PUBLIC
            "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
            "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    
    <hibernate-configuration>
    	<session-factory>
    		<property name="dialect">org.hibernate.dialect.OracleDialect</property>
    		<property name="connection.url">jdbc:oracle:thin:@172.16.1.4:1521:orcl</property>
    		<property name="connection.username">username</property>
    		<property name="connection.password">123</property>
    		<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
    		<property name="current_session_context_class">thred</property>
    		<property name="show_sql">true</property>
    		<property name="format_sql">true</property>
    		<property name="hbm2ddl.auto">true</property>
       </session-factory>
    </hibernate-configuration>


     

    Exception in thread "main" org.hibernate.HibernateException: JDBC Driver class not found: oracle.jdbc.driver.OracleDriver


    没有引入oracle驱动

    Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.itmyhome.Teacher

    没有在hibernate.cfg.xml中加入映射

    	<mapping class="com.itmyhome.Teacher"/>
    	<mapping class="com.itmyhome.Student"/>


    然后运行:

    Exception in thread "main" org.hibernate.AnnotationException: No identifier specified for entity: com.itmyhome.Teacher


    在BizEntity类上面加上@MappedSuperclass注解  用在实体的继承过程中的父类上。

    如果直接再次运行的话 会报错 表或视图不存在

    而应用SchemaExport先生成表 

    hibernate生成的表语句为:

        drop table T_STUDENT cascade constraints
    
        drop table T_TEACHER cascade constraints
    
        create table T_STUDENT (
            id varchar2(255) not null,
            name varchar2(255),
            score varchar2(255),
            primary key (id)
        )
    
        create table T_TEACHER (
            id varchar2(255) not null,
            name varchar2(255),
            title varchar2(255),
            primary key (id)
        )


    此时再插入一条teacher数据:

    Hibernate: 
        insert 
        into
            T_TEACHER
            (name, title, id) 
        values
            (?, ?, ?)

    最终所需jar包


    结束



     

  • 相关阅读:
    判断文件是否正在使用
    批量复制文件
    PAT 甲级 1116 Come on! Let's C (20 分)
    PAT 甲级 1116 Come on! Let's C (20 分)
    1123 Is It a Complete AVL Tree (30 分)
    1123 Is It a Complete AVL Tree (30 分)
    C++ sort()和is_sorted()的升序降序和自定义排序
    C++ sort()和is_sorted()的升序降序和自定义排序
    PAT 甲级 1103 Integer Factorization (30 分)
    PAT 甲级 1103 Integer Factorization (30 分)
  • 原文地址:https://www.cnblogs.com/itmyhome/p/4131478.html
Copyright © 2020-2023  润新知