Spring3 + Hibernate3.6 實現簡單 CRUD
本來是想拿Spring整合Hibernate4的,事實證明我道行尚淺 未遂……
看到這個異常,且在用Hibernate4的同學就要考慮Hibernate的版本問題了
(解決完這個問題發現4里邊把HibernateTemplate取消掉了,所以就沒再死扣)。
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ' XXXXX ': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateTemplate' defined in class path resource [applicationContext-common.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: Lorg/hibernate/cache/CacheProvider;
原來弄過spring+ibatis的整合,其實道理差不多
都是spring幫忙注入,OR框架去數據庫中CRUD,僅有的一點區別就是ibatis的SQL是手動的,Hibernate的HQL是自動的,所以Hibernate要實體Student用Annotation聲明一下
一:model
用Hibernate的方式,聲明實體、表名、主鍵等。
工程里不再需要 hibernate.cfg.xml 了,在spring配置文件的:hibernateProperties標簽里配置就行了
@Entity//測試程序里唯一一個實體 @Table(name="t_student")//指定表名t_student public class Student { private int studentid; private String name; private int age; public String toString() { return " id=>"+studentid+" name=>"+name+" age=>"+age; } //setter&getter @Id//主鍵 @GeneratedValue//自增長 public int getStudentid() { return studentid; }
二:具體service
業務調用具體service時候,就需要其中聚合的DaoImpl,通過setter靠spring注入
@Resource(name="StudentDAOImpl01")指定注入的名字
@Component("StudentService")//組件 public class StudentService { //下邊的setter定義了將要注入的實例 private IStudentDAO studentDAO; public void add(Student stu) {//test調用這個add方法 studentDAO.addStudent(stu); } public List<Student> getAll() { return studentDAO.selectAll(); } public void delById(int id) { studentDAO.delStudentById(id); } public void updateStudent(Student stu) { studentDAO.updateStudent(stu); } public List<Student> selectByName(String name) { return studentDAO.selectStudentByName(name); } //setter&getter public IStudentDAO getStudentDAO() { return studentDAO; } @Resource(name="StudentDAOImpl01")//等StudentDAOImpl的注入 public void setStudentDAO(IStudentDAO studentDAO) { this.studentDAO = studentDAO; } /*其他注入方式*/ }
三:DaoImpl
(IDao就幾個接口就不說了)
要把自己通過@Component("StudentDAOImpl01")準備好,等spring注入到上邊的具體service里,靠名字識別
ibatis這里還要找到實體的配置文件,這里直接用HQL就行了,Hibernate會幫忙生成SQL語句
這用到:
hibernateTemplate.save(stu);
hibernateTemplate.delete(stu);
hibernateTemplate.update(stu);
(Student)hibernateTemplate.get(Student.class,new Integer(id));
hibernateTemplate.find(hql,name);
其中find里邊直接寫HQL就行了,需要傳參的話可以第一參數是帶占位符的String,后一個傳值
@Component("StudentDAOImpl01")//會作為組件,注入到servise里 public class StudentDAOImpl implements IStudentDAO { private HibernateTemplate hibernateTemplate; public HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } @Resource//等待spring配置文件里配的hibernateTemplate注入 public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } //下邊是HQL的具體實現 @Override public void addStudent(Student stu) {//不指定id就能自動BySequence hibernateTemplate.save(stu); System.out.println("插入時返回的對象=》"+stu.getStudentid());//打印返回的值 } @Override public void delStudentById(int id) { //應該先select檢查一下 Student stu = hibernateTemplate.load(Student.class,new Integer(id)); hibernateTemplate.delete(stu); } @Override public void updateStudent(Student stu) { hibernateTemplate.update(stu); } @Override public Student selectStudentById(int id) { Student stu = new Student(); stu = (Student)hibernateTemplate.get(Student.class,new Integer(id)); return stu; } @Override public List<Student> selectStudentByName(String name) { String hql = "from Student t where t.name IN ?"; List<Student> stus = new ArrayList<Student>(); stus = (List<Student>)hibernateTemplate.find(hql,name); return stus; } @Override public List<Student> selectAll() { List<Student> stus = new ArrayList<Student>(); stus = (List<Student>)hibernateTemplate.find("from Student"); return stus; } }
四:spring的配置文件
1.JDBC配置
2.sessionFactory ,這里邊要配上Hibernate.cfg.xml的內容
3.hibernateTemplate
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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/tx http://www.springframework.org/schema/tx/spring-tx-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/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:annotation-config /> <context:component-scan base-package="com.rt" /> <!-- 1.JDBC配置:dataSource --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <value>classpath:jdbc.properties</value> </property> </bean> <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <!-- 2.sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <!-- hibernate具體配置,分項寫在下邊 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> <!-- 注入dataSource對象 --> <property name="dataSource" ref="dataSource" /> <!-- 搜索帶Annotation的實體 --> <property name="packagesToScan"> <list> <value>com.rt.sidemo.model</value> <!--<value>com.rt.sidemo....</value> --> </list> </property> </bean> <!-- Template --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> </beans>
JDBC的配置
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver jdbc.url=jdbc:oracle:thin:@localhost:1521:ORCL jdbc.username=scott jdbc.password=890307
五:test
public class StudentServiceTest { @Test public void testAdd() throws Exception { //Spring讀取spring配置信息 ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-common.xml"); //相當于從代理類得到具體實例,由xml決定怎么選擇類實例化 StudentService service01 = (StudentService)ctx.getBean("StudentService"); Student stu = new Student();//手動組裝User實例 u //stu.setStudentid(???); 用自動增長序列 stu.setName("Spring+Hibernate"); stu.setAge(777); service01.add(stu);//把組裝好的u傳給xml實例化的service ctx.destroy(); } @Test public void testDelById() throws Exception { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-common.xml"); StudentService service01 = (StudentService)ctx.getBean("StudentService"); service01.delById(23);//只需要把id傳給實例化的service ctx.destroy(); } @Test public void testGetAll() throws Exception { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-common.xml"); StudentService service01 = (StudentService)ctx.getBean("StudentService"); System.out.println("查詢全部:"); List<Student> stusAll = (List<Student>)service01.getAll(); for(int i=0;i<stusAll.size();i++) { System.out.println(stusAll.get(i)); } ctx.destroy(); } @Test public void testUpdateStudent() throws Exception { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-common.xml"); StudentService service01 = (StudentService)ctx.getBean("StudentService"); Student stu = new Student();//手動組裝User實例 u stu.setStudentid(25); stu.setName("SH"); stu.setAge(777); service01.updateStudent(stu);//把組裝好的u傳給spring實例化的service ctx.destroy(); } @Test public void testSelectByName() throws Exception { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-common.xml"); StudentService service01 = (StudentService)ctx.getBean("StudentService"); System.out.println("查詢全部:"); String name = "SH"; List<Student> stusAll = (List<Student>)service01.selectByName(name); for(int i=0;i<stusAll.size();i++) { System.out.println(stusAll.get(i)); } ctx.destroy(); } }
來自: http://blog.csdn.net/ruantao1989/article/details/8170108