本文共 3445 字,大约阅读时间需要 11 分钟。
org.springframework.orm.hibernate3.LocalSessionFactoryBean是spring提供的使用XML配置的sessionFactory,是不支持Annotation的。可以使用: org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean让sessionFactory支持Annotation注解的形式来配置。 改写为(加了Properties的配置,Properties里面提供了hibernate的一些配置,如方言等属性):
product.hbm.xml hibernate.dialect=org.hibernate.dialect.HSQLDialect
可以看到hibernate的映射方式(mappingResources)是xml的,我们想注入一个使用Annnotation的注解实体类,可以这样改写:
product.hbm.xml org.hibernate.dialect.MySQLDialect true
做一下实验要引入hibernate的jar包 User的Annotation注解实体类写法: User.java:
cn.edu.hpu.model.user org.hibernate.dialect.MySQLDialect true
package cn.edu.hpu.model;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;@Entitypublic class User { private int id; private String name; @Id @GeneratedValue 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; } }UserDaoImpl的save方法就要用SessionFactory进行数据库数据的add了:
package cn.edu.hpu.dao.Impl;import javax.annotation.Resource;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.springframework.stereotype.Component;import cn.edu.hpu.dao.UserDao;import cn.edu.hpu.model.User;@Component("u")public class UserDaoImpl implements UserDao{ private SessionFactory sessionFactory; @Resource public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public SessionFactory getSessionFactory() { return sessionFactory; } public void save(User u) { Session s=sessionFactory.openSession(); s.beginTransaction(); s.save(u); s.getTransaction().commit(); System.out.println("add success!!"); }}(中间出了一次错,java.lang.IllegalStateException: @Resource annotation requires a single-arg。问题出现在配置resource的时候出现错误! 解决方案!@resource配置在了get上(正确的是应该配置在set上)) 测试类:
package cn.edu.hpu.service;import org.junit.Test;import org.springframework.beans.factory.BeanFactory;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import cn.edu.hpu.dao.UserDao;import cn.edu.hpu.model.User;public class UserServiceTest { @Test public void testAdd() throws Exception{ ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml"); UserService userService=(UserService)ctx.getBean("userService"); System.out.println(userService.getClass()); User u=new User(); u.setName("jack"); userService.add(u); ctx.destroy(); }}测试成功,数据库储存了一条名为"jack"的字段。
以上是初步的整合,下一次总结是进一步整合。
转载请注明出处: