Work on DAO example.

This commit is contained in:
Ilkka Seppala
2015-04-13 21:22:03 +03:00
parent 0bded40738
commit 82eebeaee0
8 changed files with 188 additions and 45 deletions

View File

@ -2,39 +2,27 @@ package com.iluwatar;
import java.util.List; import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class App public class App {
{ public static void main( String[] args ) {
public static void main( String[] args ) { WizardDao dao = new WizardDao();
persistData(dao);
SessionFactory sessionFactory = new Configuration() queryData(dao);
.addAnnotatedClass(Wizard.class) }
.addAnnotatedClass(Spellbook.class)
.addAnnotatedClass(Spell.class) public static void persistData(WizardDao dao) {
.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect") Spell spell = new Spell("Fireball");
.setProperty("hibernate.connection.url", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1") Spellbook spellbook = new Spellbook("Book of fire");
.setProperty("hibernate.current_session_context_class", "thread") spellbook.getSpells().add(spell);
.setProperty("hibernate.show_sql", "true") Wizard wizard = new Wizard("Jugga");
.setProperty("hibernate.hbm2ddl.auto", "create") wizard.getSpellbooks().add(spellbook);
.buildSessionFactory(); dao.persist(wizard);
}
Session session = sessionFactory.getCurrentSession();
session.beginTransaction(); public static void queryData(WizardDao dao) {
Wizard wizard = new Wizard(); List<Wizard> wizards = dao.findAll();
wizard.setFirstName("Jugga"); for (Wizard w: wizards) {
Spellbook spellbook = new Spellbook(); System.out.println(w);
Spell spell = new Spell(); }
spellbook.getSpells().add(spell);
wizard.getSpellbooks().add(spellbook);
session.persist(wizard);
Query query = session.createQuery("from Wizard");
List<?> list = query.list();
Wizard p1 = (Wizard) list.get(0);
System.out.println(String.format("id=%d firstName=%s", p1.getId(), p1.getFirstName()));
session.getTransaction().commit();
} }
} }

View File

@ -1,24 +1,131 @@
package com.iluwatar; package com.iluwatar;
public abstract class DaoBase<E extends BaseEntity> { import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
public abstract class DaoBase<E extends BaseEntity> {
@SuppressWarnings("unchecked")
protected Class<E> persistentClass = (Class<E>) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
protected final SessionFactory sessionFactory = createSessionFactory();
private SessionFactory createSessionFactory() {
SessionFactory sessionFactory = new Configuration()
.addAnnotatedClass(Wizard.class)
.addAnnotatedClass(Spellbook.class)
.addAnnotatedClass(Spell.class)
.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
.setProperty("hibernate.connection.url", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1")
.setProperty("hibernate.current_session_context_class", "thread")
.setProperty("hibernate.show_sql", "true")
.setProperty("hibernate.hbm2ddl.auto", "create")
.buildSessionFactory();
return sessionFactory;
}
private Session getSession() {
return sessionFactory.openSession();
}
E find(Long id) { E find(Long id) {
Session session = getSession();
Transaction tx = null;
E result = null;
try {
tx = session.beginTransaction();
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(persistentClass);
criteria.add(Restrictions.idEq(id));
result = (E) criteria.uniqueResult();
tx.commit();
}
catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
finally {
session.close();
}
return result;
} }
void persist(E e) { void persist(E entity) {
Session session = getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.persist(entity);
tx.commit();
}
catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
finally {
session.close();
}
} }
E merge(E e) { E merge(E entity) {
Session session = getSession();
Transaction tx = null;
E result = null;
try {
tx = session.beginTransaction();
result = (E) session.merge(entity);
tx.commit();
}
catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
finally {
session.close();
}
return result;
} }
void remove(E e) { void delete(E entity) {
Session session = getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.delete(entity);
tx.commit();
}
catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
finally {
session.close();
}
} }
List<E> findAll() { List<E> findAll() {
Session session = getSession();
Transaction tx = null;
List<E> result = null;
try {
tx = session.beginTransaction();
Criteria criteria = session.createCriteria(persistentClass);
result = criteria.list();
}
catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
finally {
session.close();
}
return result;
} }
} }

View File

@ -10,6 +10,14 @@ import javax.persistence.Table;
public class Spell extends BaseEntity { public class Spell extends BaseEntity {
private String name; private String name;
public Spell() {
}
public Spell(String name) {
this();
this.name = name;
}
@ManyToOne @ManyToOne
@JoinColumn(name="SPELLBOOK_ID_FK", referencedColumnName="ID") @JoinColumn(name="SPELLBOOK_ID_FK", referencedColumnName="ID")
@ -22,4 +30,9 @@ public class Spell extends BaseEntity {
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
@Override
public String toString() {
return name;
}
} }

View File

@ -0,0 +1,5 @@
package com.iluwatar;
public class SpellDao extends DaoBase<Spell> {
}

View File

@ -17,6 +17,11 @@ public class Spellbook extends BaseEntity {
public Spellbook() { public Spellbook() {
spells = new HashSet<Spell>(); spells = new HashSet<Spell>();
} }
public Spellbook(String name) {
this();
this.name = name;
}
private String name; private String name;
@ -50,4 +55,9 @@ public class Spellbook extends BaseEntity {
public void setSpells(Set<Spell> spells) { public void setSpells(Set<Spell> spells) {
this.spells = spells; this.spells = spells;
} }
@Override
public String toString() {
return name;
}
} }

View File

@ -0,0 +1,5 @@
package com.iluwatar;
public class SpellbookDao extends DaoBase<Spellbook> {
}

View File

@ -16,17 +16,22 @@ public class Wizard extends BaseEntity {
spellbooks = new HashSet<Spellbook>(); spellbooks = new HashSet<Spellbook>();
} }
private String firstName; public Wizard(String name) {
this();
this.name = name;
}
private String name;
@OneToMany(mappedBy = "wizard", orphanRemoval = true, cascade = CascadeType.ALL) @OneToMany(mappedBy = "wizard", orphanRemoval = true, cascade = CascadeType.ALL)
private Set<Spellbook> spellbooks; private Set<Spellbook> spellbooks;
public String getFirstName() { public String getFirstName() {
return firstName; return name;
} }
public void setFirstName(String firstName) { public void setFirstName(String firstName) {
this.firstName = firstName; this.name = firstName;
} }
public Set<Spellbook> getSpellbooks() { public Set<Spellbook> getSpellbooks() {
@ -35,5 +40,10 @@ public class Wizard extends BaseEntity {
public void setSpellbooks(Set<Spellbook> spellbooks) { public void setSpellbooks(Set<Spellbook> spellbooks) {
this.spellbooks = spellbooks; this.spellbooks = spellbooks;
}
@Override
public String toString() {
return name;
} }
} }

View File

@ -0,0 +1,5 @@
package com.iluwatar;
public class WizardDao extends DaoBase<Wizard> {
}