這裏使用Spring3.0+Hibernate3.3作爲例子。
例子中的實體類也是用的Hibernate註解裏的實體(上一篇Blog)
一、Spring的一些常用註解
1.@Autowired註解(不推薦使用,建議使用@Resource)
@Autowired可以對成員變量、方法和構造函數進行標註,來完成自動裝配的工作。@Autowired的標註位置不同,它們都會在Spring在初始化這個bean時,自動裝配這個屬性。
2.@Resource註解
JSR-250標準註解,推薦使用它來代替Spring專有的@Autowired註解。@Resource的作用相當於@Autowired,只不過@Autowired按byType自動注入,而@Resource默認按byName自動注入罷了。@Resource有兩個屬性是比較重要的,分別是name和type,Spring將 @Resource註解的name屬性解析爲bean的名字,而type屬性則解析爲bean的類型。所以如果使用name屬性,則使用byName的自動注入策略,而使用type屬性時則使用byType自動注入策略。如果既不指定name也不指定type屬性,這時將通過反射機制使用byName自動注入策略。
@Resource裝配順序:
a.如果同時指定了name和type,則從Spring上下文中找到唯一匹配的bean進行裝配,找不到則拋出異常
b.如果指定了name,則從上下文中查找名稱(id)匹配的bean進行裝配,找不到則拋出異常
c.如果指定了type,則從上下文中找到類型匹配的唯一bean進行裝配,找不到或者找到多個,都會拋出異常
d.如果既沒有指定name,又沒有指定type,則自動按照byName方式進行裝配(見2);如果沒有匹配,則回退爲一個原始類型(UserDao)進行匹配,如果匹配則自動裝配
3.@Component註解 (不推薦使用)
只需要在對應的類上加上一個@Component註解,就將該類定義爲一個Bean了。Spring還提供了更加細化的註解形式:@Repository、@Service、@Controller,它們分別對應存儲層Bean,業務層Bean,和展示層Bean。這些註解與@Component的語義是一樣的,完全通用,在Spring以後的版本中可能會給它們追加更多的語義。所以,我們推薦使用@Repository、@Service、@Controller來替@Component。
二、Spring3.0的頭部文件
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> </beans>
三、dao和daoImpl
dao:
package org.e276.dao;
import java.util.List;
import org.e276.entity.Employee;
/**
* 接口
*
* @author miao
*
*/
public interface EmployeeDao {
/**
* 根據id查詢員工
*
* @param id
* @return
*/
public Employee findEmployeeById(Integer id);
/**
* 刪除多個員工
*
* @param ids
* @return
*/
public int deleteEmployees(Integer... ids);
/**
* 查詢所有的工資,並按升序排序
*
* @return
*/
public List<Employee> findAllEmployees();
/**
* 查詢所有大於平均工資的員工信息
*
* @return
*/
public List<Employee> findEmployeeGtAvgSalary();
}
daoImpl:
package org.e276.dao.impl;
import java.sql.SQLException;
import java.util.List;
import org.e276.dao.EmployeeDao;
import org.e276.entity.Employee;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
/**
* 接口實現類
*
* @author miao
*
*/
@Repository("employeeDao")
public class EmployeeDaoImpl extends HibernateDaoSupport implements EmployeeDao {
/**
* 注入會話工廠,方法名字在可以隨便起,給Spring用來注入
*/
@Autowired
public void injectSessionFactory(SessionFactory sessionFactory) {
super.setSessionFactory(sessionFactory);
}
@Override
public Employee findEmployeeById(Integer id) {
return super.getHibernateTemplate().get(Employee.class, id);
}
@Override
public int deleteEmployees(Integer... ids) {
int count = 0;
for (Integer id : ids) {
super.getHibernateTemplate().bulkUpdate("delete from Employee where id=?", id);
count++;
}
return count;
}
@SuppressWarnings("unchecked")
@Override
public List<Employee> findAllEmployees() {
DetachedCriteria criteria = DetachedCriteria.forClass(Employee.class);
criteria.addOrder((Order.asc("salary")));
return super.getHibernateTemplate().findByCriteria(criteria);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public List<Employee> findEmployeeGtAvgSalary() {
return (List<Employee>) super.getHibernateTemplate().execute(new HibernateCallback() {
String sql = "select id, name, sex, salary, birthday, depart_id from employee where salary>(select avg(salary) from employee)";
@Override
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query query = session.createSQLQuery(sql).addEntity(Employee.class);
return query.list();
}
});
}
}
四、biz和bizImpl
biz:
package org.e276.biz;
import java.util.List;
import org.e276.entity.Employee;
import org.springframework.transaction.annotation.Transactional;
/**
* 業務接口
*
* @author miao
*
*/
public interface EmployeeBiz {
/**
* 根據id查詢員工
*
* @param id
* @return
*/
public Employee findEmployeeById(Integer id);
/**
* 刪除多個員工,支持註解事務
*
* @param ids
* @return
*/
@Transactional
public int deleteEmployees(Integer... ids);
/**
* 查詢所有的工資,並按升序排序
* @return
*/
public List<Employee> findAllEmployees();
/**
* 查詢所有大於平均工資的員工信息
* @return
*/
public List<Employee> findEmployeeGtAvgSalary();
}
bizImpl:
package org.e276.biz.impl;
import java.util.List;
import org.e276.biz.EmployeeBiz;
import org.e276.dao.EmployeeDao;
import org.e276.entity.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 業務接口實現類
* @author miao
*
*/
@Service("employeeBiz")
public class EmployeeBizImpl implements EmployeeBiz {
//無需set方法
@Autowired
private EmployeeDao employeeDao;
@Override
public Employee findEmployeeById(Integer id) {
return employeeDao.findEmployeeById(id);
}
@Override
public int deleteEmployees(Integer... ids) {
return employeeDao.deleteEmployees(ids);
}
@Override
public List<Employee> findAllEmployees() {
return employeeDao.findAllEmployees();
}
@Override
public List<Employee> findEmployeeGtAvgSalary() {
return employeeDao.findEmployeeGtAvgSalary();
}
}
五、Spring的配置文件
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 哪個包裏面的類由Spring管理 --> <context:component-scan base-package="org.e276" /> <!-- 表示隱式的向Spring容器註冊 --> <context:annotation-config /> <!-- 會話工廠 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="configLocation" value="file:src/hibernate.cfg.xml"> </property> </bean> <!-- 事務管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <!-- 有關注解式事務的配置 --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
六、測試類
package org.e276.test;
import java.util.List;
import org.e276.biz.EmployeeBiz;
import org.e276.entity.Employee;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 測試類
*
* @author miao
*
*/
public class SpringEmployee {
static ApplicationContext context;
EmployeeBiz employeeBiz;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
context = new ClassPathXmlApplicationContext("applicationContext.xml");
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
context = null;
}
@Before
public void setUp() throws Exception {
employeeBiz = context.getBean("employeeBiz", EmployeeBiz.class);
}
@After
public void tearDown() throws Exception {
employeeBiz = null;
}
/**
* 根據id查詢員工
*/
public void findEmployeeById() {
Employee employee = employeeBiz.findEmployeeById(1000);
System.out.println(employee);
}
/**
* 刪除多條記錄 刪除編號50,100,150的員工
*/
public void deleteEmployees() {
int row = employeeBiz.deleteEmployees(50, 100, 150);
System.out.println("共" + row + "條記錄被刪除!");
}
/**
* 查詢所有的員工,並按工資升序排序
*/
public void findAllEmployees() {
List<Employee> list = employeeBiz.findAllEmployees();
for (Employee employee : list) {
System.out.println(employee);
}
}
/**
* 查詢所有大於平均工資的員工信息
*/
@Test
public void findEmployeeGtAvgSalary() {
List<Employee> list = employeeBiz.findEmployeeGtAvgSalary();
for (Employee employee : list) {
System.out.println(employee);
}
}
}
七、demo