標籤:hibernate java 資料庫 singleton
以前學習java的時候,一開始就學習了hibernate,那時候總覺得ssh非常高大上,所以就急忙看了下相關視頻。不過因為實際需要不高,所以後來一直沒有使用上hibernate組件。現在一年過去了,也瘋狂學習了java一段時間了,做過幾個不大的項目,但是總算對java有些瞭解。現在參加了工作,公司使用的就是ssh,所以這兩天又重新開始搗鼓hibernate。這次學習直接使用editplus,直接開發。看了官網的demo,發現英語也沒有想象中那麼困難。哈哈,把自己的學習記錄下來吧。這裡主要記錄三個方面:
1.如何搭建hibernate
2.幾種常用映射關係(one - to -one,one - to - many, many - to - one, many - to - many)
搭建hibernate(直接使用文字編輯器)
第一步:這個過程也不複雜,主要是下載到hibernate相關jar包,然後將必要的jar引入到classpath中,具體什麼是classpath,大家可以百度下。如果不匯入到classpath中,會出現不能找到類的異常。為什麼會出現這種情況呢?大家可以百度下,java 的類載入過程。
第二步:編寫hibernate.cfg.xml檔案。這個大家不用手寫,直接去hibernate文章中copy一個即可。下面給出My Code
<?xml version='1.0' encoding='utf-8' ?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_demo</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.show_sql">true</property> <!--if the value='create, means create table, every time open hibernate, if will drop the old scheme'--> <property name="hbm2ddl.auto">update</property> <mapping resource="User.xml"/> <mapping resource="Address.xml"/> </session-factory></hibernate-configuration>
第三步:開始製作一個工具類,用來初始化hibernate組件。由於難度不高,直接給出代碼,這些在文章中都已經有了,大家可以自己下載document看看。下面是代碼:
import java.io.*;import org.hibernate.*;import org.hibernate.cfg.*;/** * that is a hibernate config util * */public class HibernateConfigurationUtil{ private static HibernateConfigurationUtil singleton = new HibernateConfigurationUtil("hibernate.cfg.xml"); private static SessionFactory factory;/** * singleton pattern * */private HibernateConfigurationUtil(String configXml){ init(configXml);} public void init(String configXml){ Configuration cfg = new Configuration().configure(new File("hibernate.cfg.xml")); factory = cfg.buildSessionFactory(); // build the session factory} public static SessionFactory getSessionFactory(){ if(factory == null) return null;return factory;} /** * open a new Session * * */public static Session openSession(){ Session session = factory.openSession();return session;}}
注意下,這個類使用單例設計模式,因為hibernate組建在啟動Configuration時,是非常耗時的,而且這個對象在啟動之後不能改變,所以每個工程中,啟動一次即可。
第三步:編寫BaseHibernateDao,這個類注意是封裝了save, delete, update, load這四個方法。
import java.io.*;import org.hibernate.*;import org.hibernate.cfg.*;/** * that is the base hibernate dao, * it define a series of method to access database * if you want to 'delete, update a object, the object must exists in hibernate memery' * * @author luohong * @date 2014-08-07 * */public class BaseHibernateDao{public BaseHibernateDao(){} /** * try to save a object * */public void save(Object object){ Session session = HibernateConfigurationUtil.openSession();// open transactionTransaction transaction = session.beginTransaction();session.save(object);// commint transactiontransaction.commit();}/** * try to update a object * */public void update(Object object){ Session session = HibernateConfigurationUtil.openSession();// open transactionTransaction transaction = session.beginTransaction();session.update(object);// commint transactiontransaction.commit();} /** * try to delete a object * */public void delete(Object object){ Session session = HibernateConfigurationUtil.openSession();// open transactionTransaction transaction = session.beginTransaction();session.delete(object);// commint transactiontransaction.commit();} /** * try to load a object from database by className and id * */public Object load(Class<?> className, Serializable id){Session session = HibernateConfigurationUtil.openSession(); // there is no need for transactionreturn session.load(className, id);}}
注意:在save, update, delete方法中,只用了Transaction,要開啟事務,否則資料庫找不到相關記錄。
第四步:到了這裡之後,就非常簡單了,只需要針對具體的類,擴充BaseHibernateDao即可。下面給出一個一對多的例子。類比情景:使用者(User)擁有多個住址(Address)首先給出兩個類:
import java.util.*;public class User{private int id;private String password;private String name; private Set<Address> addressSet;public void setAddressSet(Set<Address> addressSet){ this.addressSet = addressSet;}public Set<Address> getAddressSet(){ return addressSet;}public void setName(String name){ this.name = name;}public String getName(){ return name;}public void setId(int id){ this.id = id;}public int getId(){ return id;}public void setPassword(String password){ this.password = password;}public String getPassword(){ return password;}public String toString(){ return "id = " + id + ", name = " + name + ", password = " + password + ", addressSet = " + addressSet;}}
/** * that is the user address * a user have many address, but a adress belong to a user * It is the classical 1 * n relationship * @author luohong * @date 2014-08-07 * */ public class Address {//=====================properties============================= private int id; //private User belongTo; private String code; private String city; private String street; private String homeNumber;//===================setter and getter======================== public void setId(int id){ this.id = id; } public int getId(){ return id; }/* public void setBelongTo(User user){ this.belongTo = belongTo; } public User getBelongTo(){ return belongTo; }*/ public void setCode(String code){ this.code = code; } public String getCode(){ return code; } public void setCity(String city){ this.city = city; } public String getCity(){ return city; } public void setHomeNumber(String homeNumber){ this.homeNumber = homeNumber; } public String getHomeNumber(){ return homeNumber; } public String getStreet(){ return street; } public void setStreet(String street){ this.street = street; }//========================toString================================ public String toString(){ return "id = " + id + ", city = " + city + ", street = " + street + ", homeNumber = " + homeNumber + ", code = " + code;// + ", belongTo = " + belongTo; } }
給出相關的User.xml, Address.xml;這個例子使用的是單向一對多。
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping><class name="User" table="user"><id name="id"><generator class="increment"/></id> <property name="password"/><property name="name"/><!--one to many--><set name="addressSet" cascade="all"> <!--define the foreight column name--> <key column="user_id"/><!--define the foreight table name--><one-to-many class="Address"/> </set></class></hibernate-mapping>
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping><class name="Address" table="address"><id name="id"><generator class="increment"/></id><property name="code"/><property name="city"/><property name="street"/><property name="homeNumber"/></class></hibernate-mapping>
然後編寫一個UserDao,繼承BaseHibernateDao,也很簡單,哈哈,一看就懂,這就是hibernate的厲害之處。
import java.util.*;import org.hibernate.*;/** * user dao extends BaseHibernateDao * you can add new functions to the custom dao * * * @author luohong * @date 2014-08-07 * */public class UserDao extends BaseHibernateDao{ /** * delete a user by userId * * */public void deleteById(String id){if (id == null) return; // do nothingString hql = "delete User where id=?";// 1 open session Session session = HibernateConfigurationUtil.openSession(); // 2 create a queryQuery query = session.createQuery(hql);// 3 set the parameter to queryquery.setString(1, id);// 4 execute queryquery.executeUpdate();} /** * find all user from database * */public List<User> findAllUsers(){ String hql = "from User";Session session = HibernateConfigurationUtil.openSession();Query query = session.createQuery(hql);List userList = query.list();return (List<User>)userList;}}
剩下的就是測試啦,come on...
import java.io.*;import java.util.*;/** * hibernate orm 架構demo * @author luohong * @date 2014-08-06 * * */public class HibernateDemo{public static void main(String[] args) throws Exception{ UserDao userDao = new UserDao(); User user = new User();user.setName("luohong");user.setPassword("luohong"); Set<Address> addressSet = new HashSet<Address>();for(int i=0; i<3; i++){Address address = new Address();address.setCode("111");address.setCity("hongkang");address.setStreet("universal street");address.setHomeNumber("a-2846");//address.setBelongTo(user);addressSet.add(address);}user.setAddressSet(addressSet);userDao.save(user);}}