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