`
xiaofengtoo
  • 浏览: 484309 次
  • 性别: Icon_minigender_1
  • 来自: xiamen
社区版块
存档分类
最新评论

spring2.5 + hibernate3.2 标注(annotation)开发的简单示例

阅读更多
转载于:IamHades的专栏http://blog.csdn.net/IamHades/archive/2008/01/11/2038188.aspx
看过此文,我并不是很赞同实际项目中用此方案,但依然可以借鉴。

以下是作者的处理:
首先来定义一个hibernate(jpa?)的基于annotation方式的pojo:

/**//*
 * Account.java
 *
 * Created on 2007-12-29, ÏÂÎç05:51:47
 */
package spring.withouttemplate.model;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

/** *//**
 * @author icechen
 * 
 */
@Entity
public class Account implements Serializable ...{
    private Long id;
    private String name;

    @Id
    @GeneratedValue
    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;
    }
}



然后定义一个操作数据库的interface:

/*
 * AccountRepository.java
 *
 * Created on 2007-12-29, 下午05:52:56
 */
package spring.withouttemplate.dao;

import spring.withouttemplate.model.Account;

/** *//**
 * @author icechen
 *
 */
public interface AccountRepository ...{
    public Account loadAccount(String username);
    public Account save(Account account);
}



接下来是该接口的spring实现,也是基于annotation方式,而且不再使用hibernatetamplate,也就不需要继承spring的特定类,真正做到零侵入:


/*
 * HibernateAccountRepository.java
 *
 * Created on 2007-12-29, 下午05:53:34
 */
package spring.withouttemplate.dao;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import spring.withouttemplate.model.Account;

/** *//**
 * 设计一个非侵入式的spring bean,不再继承spring的api来实现,而直接操作hibernate的session
 * 
 * @author icechen
 * 
 */
// 这个声明相当重要,spring必须对操作数据库的bean声明事务,否则就无法绑定hibernate的session
// 通常情况下,声明为“只读”模式会对sql进行优化,所以这里默认声明为true
// 但是“写”操作必须覆盖声明为“false”
@Service("demo")
@Transactional(readOnly = true)
@Repository
public class HibernateAccountRepository implements AccountRepository ...{

    private SessionFactory factory;

//    public HibernateAccountRepository(SessionFactory factory) {
//        this.factory = factory;
//    }

    // 此声明对不写数据库的操作,根据spring的默认机制来决定是true或者false,否则跟全局声明保持一致
    @Transactional(propagation = Propagation.SUPPORTS)
    public Account loadAccount(String username) ...{
        return (Account) factory.getCurrentSession().createQuery("from Account acc where acc.name = :name").setParameter("name", username)
                .uniqueResult();
    }

    // 数据库的写操作,必须声明为false,否则无法将数据写如数据库
    @Transactional(readOnly = false)
    public Account save(Account account) ...{
        factory.getCurrentSession().saveOrUpdate(account);
        return account;
    }

    @Autowired(required = true)
    public void setFactory(SessionFactory factory) ...{
        this.factory = factory;
    }

}



最后写个类来测试这段程序是否正常工作:
*
 * SpringDemo.java
 *
 * Created on 2007-12-29, 下午06:10:10
 */
package spring.withouttemplate.dao;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.context.support.FileSystemXmlApplicationContext;

import spring.withouttemplate.model.Account;

/** *//**
 * @author icechen
 *
 */
public class SpringDemo ...{

    /** *//**
     * @param args
     */
    public static void main(String[] args) ...{
        Collection<String> files = new ArrayList<String> ();
        files.add("etc/beans.xml");
        files.add("etc/dataAccessContext-local.xml");

        FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(files.toArray(new String[0]));
        AccountRepository demo = (AccountRepository) ctx.getBean("demo");
        Account account = demo.loadAccount("icechen");
        System.out.println(account.getId());
        Account newAccount = new Account();
        newAccount.setName("jay");
        newAccount = demo.save(newAccount);
        System.out.println(newAccount.getId());
    }

}



别忙,还有重要的事没有做,我们还需要少许配置(虽然使用了annotation方式,但是不等于不需要配置):

最后一段测试程序中两个xml:

beans.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
    <context:annotation-config />
    <context:component-scan base-package="*" />
    <!-- 
        <bean id="accountRepo"
        class="spring.withouttemplate.dao.HibernateAccountRepository">
        <constructor-arg ref="sessionFactory" />
        </bean>
    -->
</beans>


dataAccessContext-local.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <!-- ========================= GENERAL DEFINITIONS ========================= -->
    <!-- Configurer that replaces ${...} placeholders with values from properties files -->
    <!-- (in this case, mail and JDBC related properties) -->

    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>etc/jdbc.properties</value>
            </list>
        </property>
    </bean>

    <bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName">
            <value>${jdbc.driverClassName}</value>
        </property>
        <property name="url">
            <value>${jdbc.url}</value>
        </property>
        <property name="username">
            <value>${jdbc.username}</value>
        </property>
        <property name="password">
            <value>${jdbc.password}</value>
        </property>
    </bean>

    <!-- Hibernate SessionFactory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref local="dataSource" />
        </property>

        <property name="configurationClass"
            value="org.hibernate.cfg.AnnotationConfiguration" />

        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
    </bean>



    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean
        class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />

    <bean
        class="org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor">
        <property name="transactionInterceptor">
            <ref bean="transactionInterceptor" />
        </property>
    </bean>

    <bean id="transactionInterceptor"
        class="org.springframework.transaction.interceptor.TransactionInterceptor">
        <property name="transactionManager">
            <ref bean="transactionManager" />
        </property>
        <property name="transactionAttributeSource">
            <bean
                class="org.springframework.transaction.annotation.AnnotationTransactionAttributeSource" />
        </property>
    </bean>
</beans>

最后当然还需要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>
        <!-- show sql -->
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <!-- mapping class -->
        <mapping class="spring.withouttemplate.model.Account" />

    </session-factory>
</hibernate-configuration>

文中代码:http://download.csdn.net/source/335193
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics