`
xiaotao.2010
  • 浏览: 215432 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Hibernate基于注解_Oracle

 
阅读更多

不细说了直接上代码

 

代码中的注释可以参考Hibernate-学习笔记01

 

1、hibernate.cfg.xml

 

<?xml version='1.0' encoding='UTF-8'?>
<!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="connection.username">its</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
        <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
        <property name="connection.password">its</property>
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
    
    
    	<property name="current_session_context_class">thread</property>  
    	
    	<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>  
    	
    	<property name="show_sql">true</property>  
    	<property name="format_sql">true</property>  
    	<property name="hbm2ddl.auto">update</property>    
    	
    	<!-- 配饰AnnotationConfiguration时使用的  --> 
    	<mapping class="com.scal.entity.Teacher"/> 
    	
    </session-factory>

</hibernate-configuration>

 

 

2、log4j.properties

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=warn, stdout

#log4j.logger.org.hibernate=info
#log4j.logger.org.hibernate=debug

### log HQL query parser activity
#log4j.logger.org.hibernate.hql.ast.AST=debug

### log just the SQL
#log4j.logger.org.hibernate.SQL=debug

### log JDBC bind parameters ###
###log4j.logger.org.hibernate.type=info
#log4j.logger.org.hibernate.type=debug

### log schema export/update ###
log4j.logger.org.hibernate.tool.hbm2ddl=debug

### log HQL parse trees
#log4j.logger.org.hibernate.hql=debug

### log cache activity ###
#log4j.logger.org.hibernate.cache=debug

### log transaction activity
#log4j.logger.org.hibernate.transaction=debug

### log JDBC resource acquisition
#log4j.logger.org.hibernate.jdbc=debug

### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace

 

 

 

3、HibernateSessionFactory

package com.scal.entity;

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

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html }.
 */
public class HibernateSessionFactory {

    /** 
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses  
     * #resourceAsStream style lookup for its configuration file. 
     * The default classpath location of the hibernate config file is 
     * in the default package. Use #setConfigFile() to update 
     * the location of the configuration file for the current session.   
     */
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();    
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

	static {
    	try {
    		/* 使用配置文件的获取config */
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			try{
				/* 使用注解的获取config */
				configuration = new AnnotationConfiguration().configure();   
				sessionFactory = configuration.buildSessionFactory();
			}catch (Exception es) {
				System.err.println("%%%% Error Creating SessionFactory %%%%");
				es.printStackTrace();
			}
			
		}
    }
    private HibernateSessionFactory() {
    }
	
	/**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}

        return session;
    }

	/**
     *  Rebuild hibernate session factory
     *
     */
	public static void rebuildSessionFactory() {
		try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err
					.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	/**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

	/**
     *  return session factory
     *
     */
	public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
     *  return session factory
     *
     *	session factory will be rebuilded in the next call
     */
	public static void setConfigFile(String configFile) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}

	/**
     *  return hibernate configuration
     *
     */
	public static Configuration getConfiguration() {
		return configuration;
	}

}

 

 

4、Teacher (基于注解的实体)

package com.scal.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;

@Entity
public class Teacher implements Serializable{

	private static final long serialVersionUID = 729474527745209202L;
	@Id 
	@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="TEACHER_SEQ")      
	@SequenceGenerator(name="TEACHER_SEQ",allocationSize=1,initialValue=1, sequenceName="TEACHER_SEQ")
	private Long id;
	private String name;
	private String age;
	
	
	public Long getId() {
		return id;
	}
	
	public void setId(Long id) {
		this.id = id;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public static long getSerialVersionUID() {
		return serialVersionUID;
	}
	
	
}

 

5、DoTest

package com.scal.run;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.scal.entity.HibernateSessionFactory;
import com.scal.entity.Teacher;

public class DoTest {

		public static void main(String[] args) {
			SessionFactory sf= HibernateSessionFactory.getSessionFactory();
			Session session = sf.getCurrentSession();
			
			Teacher teacher = new Teacher();
			teacher.setAge("10");
			teacher.setName("tom");
			
			session.beginTransaction();
			session.save(teacher);
			session.getTransaction().commit();
			
			sf.close();
			
		}
}

 

分享到:
评论

相关推荐

    基于注解的springMVC+hibernate+oracle包含数据库查询

    本文将详细解析基于注解的SpringMVC+Hibernate+Oracle数据库集成的实现过程及其核心知识点。 首先,SpringMVC是Spring框架的一部分,它是一个轻量级的MVC(Model-View-Controller)框架,用于处理HTTP请求和响应。...

    hibernate_min_lib_3.5.zip

    这使得开发者能够在不引入过多额外依赖的情况下,快速搭建并运行基于Hibernate的应用程序。 在Hibernate 3.5版本中,核心库主要包含以下几个关键组件: 1. **Hibernate Core**:这是Hibernate的核心模块,提供了...

    一个简单的hibernate_4 链接Oracle例子

    虽然在Hibernate 4中,注解已经成为主要的映射方式,但某些情况下,开发者仍可能使用XML映射文件。映射文件定义了实体类与数据库表之间的关系。如果使用XML映射,`User`类的映射文件可能如下: ```xml ...

    基于注解驱动的Struts_Spring_Hibernate开发

    在现代Java Web开发中,基于注解的Struts、Spring和Hibernate框架集成是常见的技术栈,这三者结合可以构建高效、可维护的业务应用程序。本文将深入探讨这些框架的核心概念,以及如何通过注解来简化开发过程。 **...

    Hibernate_01_HelloWorld.rar

    1. **Hibernate基本概念**:Hibernate是基于Java的持久化框架,通过提供API和配置文件实现对象与数据库表之间的映射。它支持多种数据库,包括Oracle。 2. **配置Hibernate**:使用Hibernate,首先需要在项目中添加...

    Hibernate-Oracle-MySQL-image.rar_oracle

    这篇文档“Hibernate-Oracle-MySQL-image.rar_oracle”聚焦于使用Hibernate处理Oracle和MySQL数据库中的二进制大对象(Blob),特别关注如何存储和检索图片文件。Blob类型常用于存储大型数据,如图像、音频或视频...

    Myeclipse 10.0 + Hibernate 4.3.5 连接 Oracle 11G的演示代码

    标题 "Myeclipse 10.0 + Hibernate 4.3.5 连接 Oracle 11G的演示代码" 描述的是一个整合项目,它将Myeclipse 10.0集成开发环境、Hibernate 4.3.5对象关系映射框架与Oracle 11G数据库相结合,用于演示如何在这样的...

    hibernate框架下对oracle数据库操作所需jar包.zip

    Hibernate提供了一种基于Java语法的查询语言HQL(Hibernate Query Language),以及Criteria API,它们可以更直观地处理数据库查询,而无需直接编写SQL。 9. **缓存机制** Hibernate支持二级缓存,可以提高数据...

    hibernate学习笔记_北大青鸟课堂笔记全文

    Hibernate基于Java,遵循JPA规范,它通过XML或注解方式将Java对象与数据库表进行映射。这种映射机制使得我们能够用面向对象的方式来处理数据,避免了SQL语句的编写,提升了开发效率。 2. Hibernate配置 在使用...

    Hibernate_3.2.0_Reference_zh_CN

    Hibernate支持多种数据库,包括MySQL、Oracle、PostgreSQL等,并提供了丰富的API和工具。 二、安装与配置 在使用Hibernate之前,需要先将其添加到项目的类路径中。通常,这涉及在项目构建工具(如Maven或Gradle)的...

    hibernate@注解方式配置实体类,调用javadoc接口生成数据库表及字段的注释说明

    hibernate@注解方式配置实体类时,利用javadoc接口生成数据库表及字段的注释说明,支持oracle、sqlserver、db2、mysql数据库。因用到java\lib\tools.jar,需要将该jar放入工程lib下(或者tomcat\lib下、或加入...

    hibernate常用注解

    #### 一、JPA与Hibernate注解基础 JPA(Java Persistence API)是一种标准规范,用于实现对象关系映射(ORM),允许开发人员使用注解或XML来描述实体对象与数据库表之间的映射关系。Hibernate是JPA的一种实现,它...

    车辆管理系统(struts+hibernate+spring+oracle).rar

    车辆管理系统(struts+hibernate+spring+oracle),车辆管理系统(struts+hibernate+spring+oracle),车辆管理系统(struts+hibernate+spring+oracle),

    hibernate实例连oracle

    4. **实体映射**:定义Java类作为数据库表的映射,使用Hibernate注解或XML文件描述字段和表之间的关系。 5. **SessionFactory和Session**:通过SessionFactory创建Session对象,它是与数据库交互的主要接口,用于...

    hibernate注解说明文档

    ### Hibernate注解详解 #### 一、概述 Hibernate是一个开源的对象关系映射(ORM)框架,用于Java应用程序中实现数据库操作。它通过提供强大的映射工具和服务,将面向对象的数据模型映射到基于SQL的关系数据库中。...

    hibernate 调用oracle函数

    4. **定义Hibernate Native SQL查询**:由于Hibernate默认不支持调用存储过程或函数,我们需要使用`@NamedNativeQuery`或`@SqlResultSetMapping`注解来定义一个原生SQL查询,用于调用Oracle函数。例如: ```java @...

    hibernate注解配置

    ### Hibernate注解配置详解 #### 一、概述 Hibernate 是一款强大的对象关系映射(ORM)框架,它简化了Java应用程序与数据库之间的交互过程。在使用Hibernate的过程中,开发者可以通过注解来实现对象与数据库表之间...

    HIbernate与oracle数据库应用例子

    本篇将深入探讨如何在实际项目中结合Hibernate与Oracle数据库进行应用。 一、Hibernate简介 Hibernate是一个开放源代码的对象关系映射(ORM)框架,它为开发者提供了在Java应用中操作数据库的强大工具。通过ORM,...

Global site tag (gtag.js) - Google Analytics