`
tanglei198577
  • 浏览: 59693 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类

Notes of hibernate about Xiaxin

    博客分类:
  • SSH
阅读更多

In order to test hibernate example ,create a simple project is enough,then we shoule have these libs for simple test:hibernate3.jar,log4j-1.2.8.jar and the jar of oracle driver .add them to the liberary;

 

then generate the hibernate.cfg.xml and should put it in the classpath too.

<?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">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

	<session-factory>
		<property name="connection.username">tanglei</property>
		<property name="connection.url">
			jdbc:oracle:thin:@localhost:1521:orcl
		</property>
		<property name="dialect">
			org.hibernate.dialect.Oracle9Dialect
		</property>
		<property name="myeclipse.connection.profile">Oracle</property>
		<property name="connection.password">tanglei</property>
		<property name="connection.driver_class">
			oracle.jdbc.driver.OracleDriver
		</property>
		<property name="hibernate.show_sql">true</property><!--add by myself-->

		<mapping resource="View/TUserTwo.hbm.xml" />

	</session-factory>

</hibernate-configuration>

 then go to the database to create some tables.

create table t_user_two(
   age integer ,
   firstname varchar(30) not null,
   lastname varchar(30) not null ,
   constraint pk_name primary key(firstname,lastname)
 )

 Here I use composite-key for testing.After create this table ,then go to Myeclipse database explorer,

create a new driver connection.here is my configuration:

     driver template: oracle(thin)

     driver name: oracle(you can define your own)

     Connection url:  jdbc:oracle:thin:@localhost:1521:orcl

     username:(database login name)

     password:(database login password)

after this ,add the oracle jar to this driver,press the button "Add jars" for adding.

then open this connection.find your table ,then right click on it to find Hibernate Reverse engineering for auto-genrate OR Mapping file of this table.When you select the Id generator, had better to choose uuid.hex. (If you choose sequense,you shoule create it first in database like this:

create sequence serial increment by 1 start with 1 minvalue 1 maxvalue 999

 ,then should add this sequence to the paramter for generate class:

        <id name="id" type="java.lang.Long">
            <column name="ID" precision="5" scale="0" />
            <generator class="sequence" >
              <param name="sequence">serial</param>
            </generator>
        </id>

 ,or it will thrown exception);

After reverse enginnerring of this table ,we can get five files.

     TUserTwo.hbm.xml:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="View.TUserTwo" table="T_USER_TWO" schema="TANGLEI">
        <composite-id name="id" class="View.TUserTwoId">
            <key-property name="firstname" type="java.lang.String">
                <column name="FIRSTNAME" length="30" />
            </key-property>
            <key-property name="lastname" type="java.lang.String">
                <column name="LASTNAME" length="30" />
            </key-property>
        </composite-id>
        <property name="age" type="java.lang.Integer">
            <column name="AGE" precision="22" scale="0" />
        </property>
    </class>
</hibernate-mapping>

 AbstractTUserTwo is pojo:

package View;

/**
 * AbstractTUserTwo entity provides the base persistence definition of the
 * TUserTwo entity.
 * 
 * @author MyEclipse Persistence Tools
 */

public abstract class AbstractTUserTwo implements java.io.Serializable {

	// Fields

	private TUserTwoId id;
	private int age;

	// Constructors

	/** default constructor */
	public AbstractTUserTwo() {
	}

	/** minimal constructor */
	public AbstractTUserTwo(TUserTwoId id) {
		this.id = id;
	}

	/** full constructor */
	public AbstractTUserTwo(TUserTwoId id, int age) {
		this.id = id;
		this.age = age;
	}

	// Property accessors

	public TUserTwoId getId() {
		return this.id;
	}

	public void setId(TUserTwoId id) {
		this.id = id;
	}

	public int getAge() {
		return this.age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}

 

AbstractTUserTwoId is just for composite-key object:

package View;

/**
 * AbstractTUserTwoId entity provides the base persistence definition of the
 * TUserTwoId entity.
 * 
 * @author MyEclipse Persistence Tools
 */

public abstract class AbstractTUserTwoId implements java.io.Serializable {

	// Fields

	private String firstname;
	private String lastname;

	// Constructors

	/** default constructor */
	public AbstractTUserTwoId() {
	}

	/** full constructor */
	public AbstractTUserTwoId(String firstname, String lastname) {
		this.firstname = firstname;
		this.lastname = lastname;
	}

	// Property accessors

	public String getFirstname() {
		return this.firstname;
	}

	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}

	public String getLastname() {
		return this.lastname;
	}

	public void setLastname(String lastname) {
		this.lastname = lastname;
	}

	public boolean equals(Object other) {
		if ((this == other))
			return true;
		if ((other == null))
			return false;
		if (!(other instanceof AbstractTUserTwoId))
			return false;
		AbstractTUserTwoId castOther = (AbstractTUserTwoId) other;

		return ((this.getFirstname() == castOther.getFirstname()) || (this
				.getFirstname() != null
				&& castOther.getFirstname() != null && this.getFirstname()
				.equals(castOther.getFirstname())))
				&& ((this.getLastname() == castOther.getLastname()) || (this
						.getLastname() != null
						&& castOther.getLastname() != null && this
						.getLastname().equals(castOther.getLastname())));
	}

	public int hashCode() {
		int result = 17;

		result = 37 * result
				+ (getFirstname() == null ? 0 : this.getFirstname().hashCode());
		result = 37 * result
				+ (getLastname() == null ? 0 : this.getLastname().hashCode());
		return result;
	}

}

 TUserTwo extends AbstractTUserTwo , TUserTwoId.java extends AbstractTUserTwoId.java

Ok,done,now we can test it:

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

import View.TUser;
import View.TUserTwo;
import View.TUserTwoId;

import junit.framework.Assert;
import junit.framework.TestCase;


public class HiberTest extends TestCase{

	Session session = null;
	//init method
	protected void setUp(){
		try {
			Configuration config = new  Configuration().configure();
			session = config.buildSessionFactory().openSession();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//close method
	protected void close(){	
		try {
			session.close();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//test method
	public void testInsert(){
		Transaction trans = null;
		try {
			trans = session.beginTransaction();
			//TUser user = new TUser();
			//user.setName("Tanglei");
			//session.save(user);
/*			TUserTwo user = new TUserTwo();
			TUserTwoId userId = new TUserTwoId();
            user.setAge(10);
			userId.setFirstname("tan");
			userId.setLastname("le");
			user.setId(userId);
			session.save(user);*/
			TUserTwo user = new TUserTwo();
			TUserTwoId userId = new TUserTwoId();
			userId.setFirstname("tan");
			userId.setLastname("le");
			user.setId(userId);
			user = (TUserTwo)session.load(TUserTwo.class, userId);
			System.out.println(user.getAge());
			session.flush();
			trans.commit();
			//Assert.assertEquals(user.getId().intValue()>0, true);
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Assert.fail(e.getMessage());
		    if(trans!=null){
			   try {
				trans.rollback();
			} catch (HibernateException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		    }
		}		
	}
	
	public  static void main(String args[]){
		HiberTest tt = new HiberTest();
		tt.setUp();
		tt.testInsert();
		tt.close();
	}
}

 then we can find this on console:

Hibernate: select tusertwo0_.FIRSTNAME as FIRSTNAME1_0_, tusertwo0_.LASTNAME as LASTNAME1_0_, tusertwo0_.AGE as AGE1_0_ from TANGLEI.T_USER_TWO tusertwo0_ where tusertwo0_.FIRSTNAME=? and tusertwo0_.LASTNAME=?
10

 

by the way , you shoule add properties file log4j.properties for log4j:

# define an appender named console, which is set to be a ConsoleAppender
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
## LAYOUTS ##
# assign a SimpleLayout to console appender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# assign a PatternLayout to file appender
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d(ABSOLUTE) %5p %c(1):%L - %m%n

log4j.rootLogger=error,stdout

log4j.logger.net.sf.hibernate = error

 

0
0
分享到:
评论

相关推荐

    notes of text about machine learning

    this is abour infiniband roce protocol and implementation on linux

    hibernate(notes)

    【标题】:Hibernate 教程笔记 【描述】:Hibernate 是一个开源的Java持久化框架,它简化了数据库与Java应用程序之间的交互。本教程笔记将深入探讨Hibernate的核心概念、配置、对象关系映射(ORM)以及操作数据库的...

    CS229 Lecture Notes

    CS229 Lecture Notes

    A Chinese Notes of MLAPP,MLAPP 中文笔记项目 https:--z-MLAPP-CN.zip

    A Chinese Notes of MLAPP,MLAPP 中文笔记项目 https:--z-MLAPP-CN

    Notes SQL 8.5.1用于odbc连接Lotus Notes数据库

    Lotus Notes是一款强大的企业级协作应用软件,而SQL(Structured Query Language)是用于管理和处理关系数据库的标准语言。在标题和描述中提到的“Notes SQL 8.5.1”是IBM提供的一款工具,它允许开发者通过ODBC...

    notes2 --notes2

    notes2 notes2notes2 notes2notes2 notes2v

    Chinese_notes_about_R_learning,_the_book_is_

    Chinese_notes_about_R_learning,_the_book_is_《R_in__R-learning

    windows 手动安装Sticky Notes 便签.zip

    在不包含Sticky Notes 便签的操作系统中手动安装Sticky Notes 便签,windows server2016测试通过;包含x86及x64; 方法:1、新建 C:\Program Files\Sticky Notes 2、拷贝 en-US、slc.dll、StickyNotes.exe 至 C:\...

    Notes模板,适合于notes初学者!

    Notes模板详解 Notes是一款功能强大且灵活的协作软件,但许多用户并不了解Notes的模板机制和数据库结构,导致在使用Notes时遇到很多问题。今天,我们将详细介绍Notes模板的概念、创建模板的方法、模板的应用场景,...

    IBM LotusNotes JAVA库 NCSO.jar Notes.jar

    IBM LotusNotes是一款强大的企业级协同应用软件,它集成了电子邮件、日历、任务管理、文档共享、数据库等多种功能。在LotusNotes系统中,开发者可以利用其提供的API进行应用程序的开发,实现定制化的业务需求。这里...

    Power Notes

    【Power Notes】是一款功能强大的笔记软件,专为个人和专业人士设计,旨在提高组织、管理和分享信息的效率。这款软件提供了一种便捷的方式来记录、分类和查找各种类型的信息,包括文字、图片、链接、附件等,使得...

    GeeksForGeeks Theory Of Computation and Automata Lecture Notes

    GeeksForGeeks Theory Of Computation and Automata Lecture Notes

    如何改变LotusNotes 工作区字体的大小

    ### 如何改变LotusNotes工作区字体的大小 在日常工作中,我们经常需要根据个人习惯或视觉需求调整软件界面中的字体大小。对于使用LotusNotes的用户来说,更改工作区内的字体大小同样是一项实用的功能。本文将详细...

    C-Primer-Plus-good-notes-.zip_Goodnotes window版_goodnotes window

    这个压缩包文件"**C-Primer-Plus-good-notes-.zip**"显然包含了一份针对该书的优质笔记,特别适合在Windows环境下使用Goodnotes阅读和学习。 **Goodnotes**是一款广受欢迎的数字笔记应用,尤其适用于Windows用户。...

    火热!!cfa一级2024最新notes下载

    "2024 notes"通常指的是针对2024年CFA考试的复习笔记或教材,这些材料通常由知名培训机构如Schweser等提供,精炼了官方学习材料,并加入了解题技巧和重点解析。SchweserNotes是CFA备考中广受欢迎的一套辅助资料,它...

    Lotus Notes 自定义信头方法

    Lotus Notes,作为一款历史悠久且功能强大的邮件客户端,提供了自定义信头的方法,让用户的邮件更具特色。本文将详细介绍如何在Lotus Notes中定制专属的信头。 ### 一、理解Lotus Notes信头概念 在Lotus Notes中,...

    升级Notes8方法

    【升级Notes8方法】 在升级 Lotus Notes 8 时,为了确保程序的稳定性和数据的安全,需要遵循一系列的步骤和注意事项。以下是一个详尽的升级指南: **一、升级前的准备工作** 1. **确认用户信息**:首先,确定用户...

    Lotus Notes初学入门

    Lotus Notes初学入门 Lotus Notes 是一种功能强大且灵活的数据库管理系统,由 IBM 公司开发。作为一名研发人员,学习 Lotus Notes 是非常有必要的。本文将从基础知识开始,逐步深入学习 Lotus Notes,帮助读者快速...

    Delphi访问NOTES数据库

    Delphi 访问 NOTES 数据库 Delphi 是一款功能强大且灵活的编程语言,可以与多种数据库集成,以实现数据的存取和操作。NOTES 数据库是一种文档型数据库,广泛应用于企业信息化、文档管理和知识管理等领域。那么,...

Global site tag (gtag.js) - Google Analytics