Quick Start
Hibernate是java中常用的ORM框架,經常與Spring整合在一起
本文主要介紹單純的Hibernate,並以hibernate5為主
安裝
http://hibernate.org/orm/releases/5.0/
環境
- Hibernate是jdbc的封裝,須下載
mysql-connector-java-8.0.12.jar
- Hibernate相依於jta,須下載
jta-1.1.jar
- 其他的jar檔,在
hibernate-release-5.0.12.Final.zip
的lib/required/
裡全部都有。
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="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testHibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="my.model.Event"></mapping>
</session-factory>
</hibernate-configuration>
說明:
- 新版jdbc路徑是
com.mysql.cj.jdbc.Driver
- hibernate5的dialog建議使用
org.hibernate.dialect.MySQL5Dialect
Session
Hibernate每次操作db時,需建立session。
// session factory
Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
// 操作db
Session session = sessionFactory.openSession();
session.beginTransaction();
session.saveOrUpdate(entity);
session.getTransaction().commit();
session.close();
DAO
public class HibernateSessionManager {
protected Session getSession() {
// 仿照上方取得session
}
}
public interface BaseDao<T> {
public boolean insert(T entity);
public List<T> list(T entity, Order order, int offset, int limit);
}
public class BaseDaoImpl<T> extends HibernateSessionManager implements BaseDao<T> {
@Override
public boolean insert(T entity) {
getSession().saveOrUpdate(entity);
return true;
}
@Override
public List list(T entity, Order order, int offset, int limit) {
Criteria c = getSession().createCriteria(entity.getClass());
if(order != null) {
c.addOrder(order);
}
if(offset > -1) {
c.setFirstResult(offset);
}
if(limit > -1) {
c.setMaxResults(limit);
}
return c.list();
}
}
public interface EventDao extends BaseDao<Event> {
}
public class EventDaoImpl extends BaseDaoImpl<Event> implements EventDao {
}
說明
BaseDao
及BaseDaoImpl
是Spring慣用的寫法:定義介面及實作,這裡也採用這樣的慣例。BaseDao
代表的是共用的dao,所有的dao將繼承它。- 最後操作db的是EventDaoImpl,實作EventDao介面。雖然目前沒有其他實作,但將來如果有針對Event這個table有特殊的操作,就可以擴充。
Entity
@Entity
@Table(name = "events")
public class Event {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(length = 128)
private String name;
@Column
@Temporal(TemporalType.TIMESTAMP)
private Date datetime;
// getter,setter略
}
主程式
EventDao eventDao = new EventDaoImpl();
// insert
Date date = new Date();
Event e = new Event();
e.setName("name-" + date.getTime());
e.setDatetime(date);
eventDao.insert(e);
// query
List<Event> list = eventDao.list(e, null, 0, 3);
for(Event x : list) {
System.out.println("Event: " + x.getName());
}