2013-01-11 26 views
1

我使用STS創建了一個新的MVC模板項目,並添加了支持Hibernate的所有依賴關係。如何在Spring中的Controller方法中使用Hibernate

這是我的根context.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:jdbc="http://www.springframework.org/schema/jdbc" 
xsi:schemaLocation=" 
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd 
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 

<!-- Root Context: defines shared resources visible to all other web components --> 

<jdbc:embedded-database id="dataSource" type="H2"> 
    <jdbc:script location="classpath:schema.sql"/> 
    <jdbc:script location="classpath:test-data.sql"/> 
</jdbc:embedded-database> 

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

<bean id="contactDao" class="com.server.dao.impl.ContactDaoImpl"> 
    <property name="sessionFactory" ref="sessionFactory"></property> 
</bean> 

<bean id="sessionFactory" 
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> 
    <property name="dataSource" ref="dataSource" /> 
    <property name="packagesToScan" value="com.server.model" /> 
    <property name="hibernateProperties"> 
     <props> 
      <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop> 
      <prop key="hibernate.max_fetch_depth">3</prop> 
      <prop key="hibernate.jdbc.fetch_size">50</prop> 
      <prop key="hibernate.jdbc.batch_size">10</prop> 
      <prop key="hibernate.show_sql">true</prop> 
     </props> 
    </property> 
</bean> 

STS自動創建一個名爲HomeController.java樣本控制器:

@Controller 
public class HomeController { 

private static final Logger logger = LoggerFactory.getLogger(HomeController.class); 

/** 
* Simply selects the home view to render by returning its name. 
*/ 
@RequestMapping(value = "/", method = RequestMethod.GET) 
public String home(Locale locale, Model model) { 
    Date date = new Date(); 
    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale); 

    String formattedDate = dateFormat.format(date); 

    model.addAttribute("serverTime", formattedDate); 

    return "home"; 
} 

我想,當Web應用程序在服務器上啓動時,在root-context.xml中聲明的bean將自動由框架實例化。

我的問題是:我怎樣才能得到對象ContactDao實例的引用? 即:我如何在我的數據庫上執行操作?

有人可以幫助我嗎?

感謝

回答

2

您需要使用註釋注入ContactDao在你的控制器:

@Autowired 
public void setContactDao(ContactDao contactDao) { 
    ... 
} 

使用界面(我猜它的ContactDAO),這樣你就可以改變實現(可能對測試有用)。

現在您可以使用您的聯繫人DAO方法使用contactDao對象。

有關自動裝配更多信息,請參閱http://static.springsource.org/spring/docs/current/spring-framework-reference/htmlsingle/#beans-factory-autowire

+0

竟被你要dneed確保您的應用程序conext設置要annaotion驅動太 – NimChimpsky

+0

謝謝,這是問題:) – Mircb

相關問題