1. 写一个domain类来映射数据库表
2. 写一个*.hbm.xml文件来配置映射
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.jforum.dao.common"> <class name="Member" table="T_MEMBER_INFO"> <id name="id" column="id" type="java.lang.Integer"> <generator class="sequence"> <param name="sequence">FORUM_MEMBER_ID_SEQ</param> </generator> </id> <property column="username" length="200" name="username" not-null="true" type="string"/> <property column="password" length="100" name="password" not-null="true" type="string"/> <property column="groupid" length="9" name="groupid" not-null="true" type="java.lang.Integer"/> </class> </hibernate-mapping>
3. applicationContext.xml文件中配置读取hbm.xml
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref local="dataSource" /> </property> <property name="mappingResources"> <list> <!-- <value>com/jforum/domain/Employee.hbm.xml</value> --> <value>com/ROCKY/domains/member/Member.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> </props> </property> </bean>
4. 实现dao,使用template
package com.ROCKY.daos.member; import java.util.List; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate3.HibernateTemplate; import com.ROCKY.domains.member.Member; public class MemberDao { private SessionFactory sessionFactory; private HibernateTemplate hibernateTemplate; /** * 设置hibernateTemplate * * @return 返回hibernateTemplate */ public HibernateTemplate getHibernateTemplate() { if (hibernateTemplate == null) { hibernateTemplate = new HibernateTemplate(sessionFactory); } return hibernateTemplate; } /** * 获取sessionFactory * * @param sessionFactory 要设置的sessionFactory */ public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Member get(Integer id) { return getHibernateTemplate().get(Member.class, id); } @SuppressWarnings("unchecked") public List<Member> findByName(String name) { return (List<Member>)getHibernateTemplate().find("from Member m where m.username=?", name); } }
5. 也可以用
package com.ROCKY.daos.member; import java.util.List; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.ROCKY.domains.member.Member; public class MemberDaoHibernate extends HibernateDaoSupport { public Member get(Integer id) { return getHibernateTemplate().get(Member.class, id); } @SuppressWarnings("unchecked") public List<Member> findByName(String name) { return (List<Member>)getHibernateTemplate().find("from Member m where m.username=?", name); } }