1、配置Hibernate
<?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="myeclipse.connection.profile">
bbsdriver
</property>
<property name="connection.url">
jdbc:mysql://localhost/meibbs?characterEncoding=UTF-8
</property>
<property name="connection.username">***</property><!--配置数据库账号-->
<property name="connection.password">***</property><!--配置密码-->
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property><!--配置方言-->
<property name="show_sql">true</property><!--控制台打印sql语句-->
<property name="format_sql">true</property><!--格式化数据语句-->
<property name="hbm2ddl.auto">update</property><!--每次运行程序的时候就更新数据语句,这里有create,create-drop,update,validate -->
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property><!--提供二级缓存-->
<property name="cache.use_query_cache">true</property><!--使用查询缓存器-->
<mapping resource="com/bbs/entity/Bbsuser.hbm.xml" />
</session-factory>
</hibernate-configuration>
2、读取Hibernate.cfg.sml建立HibernateFactory
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {
/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
3、建立Dao
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.bbs.entity.HibernateSessionFactory;
public class BaseDao<T> {
List<T> list=null;
SessionFactory fac;
Session session;
public void create(T object) {
Session session = HibernateSessionFactory.getSession();
try {
session.beginTransaction();
session.persist(object);
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
} finally {
session.close();
}
}
public void update(T object) {
Session session = HibernateSessionFactory.getSession();
try {
session.beginTransaction();
session.update(object);
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
} finally {
session.close();
}
}
public void delete(T object) {
Session session = HibernateSessionFactory.getSession();
try {
session.beginTransaction();
session.delete(object);
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
} finally {
session.close();
}
}
@SuppressWarnings("unchecked")
public T find(Class<? extends T> clazz, Serializable id) {
Session session = HibernateSessionFactory.getSession();
try {
session.beginTransaction();
return (T) session.get(clazz, id);
} finally {
session.getTransaction().commit();
session.close();
}
}
@SuppressWarnings("unchecked")
public List<T> list(String hql) {
Session session = HibernateSessionFactory.getSession();
try {
session.beginTransaction();
list=session.createQuery(hql).list();
session.getTransaction().commit();
} finally {
session.close();
}
return list;
}
@SuppressWarnings("unchecked")
public List<T> listsql(String sql) {
Session session = HibernateSessionFactory.getSession();
try {
session.beginTransaction();
list=session.createSQLQuery(sql).list();
session.getTransaction().commit();
} catch (HibernateException e) {
e.printStackTrace();
}finally {
session.close();
}
return list;
}
@SuppressWarnings("unchecked")
public List<T> listsql(String Hql,int max,int start) {
Session session = HibernateSessionFactory.getSession();
try {
session.beginTransaction();
Query query=session.createQuery(Hql);
query.setFirstResult(start);
query.setMaxResults(max);
list=query.list();
return list;
} finally {
session.getTransaction().commit();
session.close();
}
}
public Session getSession()
{
Session session = HibernateSessionFactory.getSession();
return session;
}
public int getListSize()
{
if(list!=null)
{
int i=0;
for(T cc:list)
{
i++;
}
return i;
}
return 0;
}
}
3、实体类的建立
a、一对一关系的建立
实体类
public class Person {
private long id;
private String name;
private IdCard idcard;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public IdCard getIdcard() {
return idcard;
}
public void setIdcard(IdCard idcard) {
this.idcard = idcard;
}
}
public class IdCard {
private long id;
private String value;
private Person person;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
配置文件
Person.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="com.***.Person" table="Person" catalog="bbs">
<id name="id" type="java.lang.Long">
<column name="id" />
<generator class="native" />
</id>
<property name="value" type="java.util.String">
<column name="value" length="10" />
</property>
<one-to-one name="idcard"></one-to-one>
</class>
</hibernate-mapping>
IdCard.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="com.***.IdCard" table="IdCard" catalog="bbs">
<id name="id" type="java.lang.Long">
<column name="id" />
<generator class="foreign">
<param name="property">person</param><!--表示该主键的参数为person-->
</generator>
</id>
<one-to-one name="person" constrained="true"></one-to-one><!--必须要加constrained="true",表示是主键约束,也是外键约束-->
</class>
</hibernate-mapping>
b、多对一以及一对多关系的建立
实体类
import java.util.Set;
public class Department {
private long id;
private String departmentname;
private Set<Employee> emps;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getDepartmentname() {
return departmentname;
}
public void setDepartmentname(String departmentname) {
this.departmentname = departmentname;
}
public Set<Employee> getEmps() {
return emps;
}
public void setEmps(Set<Employee> emps) {
this.emps = emps;
}
}
public class Employee {
private long id;
private String name;
private Department dep;
public int getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Department getDep() {
return dep;
}
public void setDep(Department dep) {
this.dep = dep;
}
}
配置文件
Department.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="Department" table="department" catalog="bbs">
<id name="userid" type="java.lang.Long">
<column name="userid" />
<generator class="native" />
</id>
<set name="emps" inverse="true">
<key>
<column name="employ" />
</key>
<one-to-many class="com.**.Employee" />
</set>
</class>
</hibernate-mapping>
Employee.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="com.***.Employee" table="employee" catalog="bbs">
<id name="userid" type="java.lang.Long">
<column name="userid" />
<generator class="native" />
</id>
<many-to-one name="dep"></many-to-one>
</class>
</hibernate-mapping>
c、多对多关系的建立
实体类
配置文件
4、难度剖析
a、关系的建立
b、hibernate里面的对象状态
这里的对象状态有瞬时状态(transient),持续状态(persisted),脱管或叫游离状态(detached)
详细情况见前面Hibernate1