J2EE企业应用实战——基于Hibernate3.0实现DAO

Person类:
public class Person {
private int id;
private String name;
private Date born;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBorn() {
return born;
}
public void setBorn(Date born) {
this.born = born;
}
}
Person的配置文件:







PersonDao接口:
public interface PersonDao{
public Person get(int id);
}
PersonDaoImpl实现类:
public class PersonDaoImpl implements PersonDao{
private SessionFactory sessionFactory;

public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}

@Override
public Person get(int id) {
    return (Person) this.sessionFactory.getCurrentSession().load(Person.class, id);
}

}
beanx.xml文件:


oracle.jdbc.driver.OracleDriver


jdbc:oracle:thin:@127.0.0.1:1521:myoracle


xiaoming


m123

  <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource">
        <ref local="dataSource"/>
    </property>
    <property name="mappingResources">
        <list>
            <value>com/sunyan/bean/Person.hbm.xml</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
            <!-- 
            <prop key="hibernate.hbm2ddl.auto">create</prop> -->
        </props>
    </property>
  </bean>

  <bean id="personDaoImpl" class="com.sunyan.impl.PersonDaoImpl">
    <property name="sessionFactory">
        <ref bean="sessionFactory"/>
    </property>
  </bean>

测试代码:
FileSystemXmlApplicationContext appContext = new FileSystemXmlApplicationContext(new String[]{"classpath:beans.xml"});
BeanFactory factory = (BeanFactory) appContext;
PersonDao pdi = (PersonDao) factory.getBean("personDaoImpl");
Person p = (Person) pdi.get(77);
System.out.println(p.getBorn()+" "+p.getName());
出错提示:
No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

有一点我不明白,你的Dao为什么不直接继承HibernateDaoSupport而是向Dao中注入SessionFactory。如果你同时也使用了Spring框架,那么你可以在配置文件中声明事务,就像这样。


<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
    <property name="transactionManager" ref="transactionManager"/>
</bean>


<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="*" propagation="REQUIRED"/>
    </tx:attributes>
</tx:advice>

<aop:config>
    <aop:pointcut id="service" expression="execution(* com.hibernate..*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="service"/>
</aop:config>

如果不是那你就得实现编程式的事务处理,有这样几个类可以去看看,TranactionManager,TransactionTemplate,这些提供了事务支持。

没有事务包围,你得加上事务。