Moje POJO jest bardzo proste:
public class Category {
Integer id;
String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Do tego równie proste mapowanie:
<hibernate-mapping package="main">
<class name="Category">
<id name="id" value="null" column="category_id">
<generator class="sequence">
</generator></id></class></hibernate-mapping><paramname="sequence">category_seq
<property name="name">
</property>
Plik konfiguracyjny wygląda następująco:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/testy
</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver
</property>
<property name="hibernate.connection.username">test</property>
<property name="hibernate.connection.password">test</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect
</property>
<property name="hibernate.show_sql">false</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="main\Category.hbm.xml" />
</session-factory>
</hibernate-configuration>
W konfiguracji zawarty jest wpis o automatycznym tworzeniu schematu bazy danych ze zdefiniowanych plików mapowań:
<property name="hbm2ddl.auto">create</property>
Główna klasa projektu wygląda następująco:
public class Main {
public static void main(String[] args) {
Session session = null;
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
Category cat = new Category();
cat.setName("name");
session.beginTransaction();
session.save(cat);
session.flush();
session.getTransaction().commit();
session.close();
System.out.println("end");
}
}
Największą trudność może sprawić poprawne dobranie zależności. Działająca konfiguracja wygląda następująco:
- antlr-2.7.6.jar
- backport-util-concurrent-3.1.jar
- postgresql-8.1-407.jdbc3.jar
- ehcache-1.5.0.jar
- log4j-1.2.14.jar
- commons-collections-3.2.jar
- dom4j-1.6.1.jar
- commons-logging-1.1.1.jar
- hibernate-3.2.5.ga.jar
- jta-1.0.1B.jar
- xml-apis-1.3.03.jar
- cglib-nodep-2.1_3.jar

Brak komentarzy:
Prześlij komentarz