Java自学之路-Java中级教程-32:Hibernate实现数据保存方法save及AOP事务配置

首先用Hibernate来实现保存数据的方法save,这个save方法是sessionFactory.getCurrentSession()的一个方法。上一节已经提到,要 让PersonDaoImpl调用sessionFactory.getCurrentSession().save(person),就需要给PersonDaoImpl注入这个SessionFactory类的实例。


}

第一步,我们重新创建一个PersonDaoSessionImpl来实现Hibernate的方法。


@Repository
public class PersonDaoSessionImpl implements PersonDao {
	
	@Autowired
	private SessionFactory sessionFactory;
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}


	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}


	/**
	 * 增加Person记录
	 * @param person
	 * @return
	 * @throws Exception
	 */
	public int add(Person person) throws Exception {

		int id = (Integer)sessionFactory.getCurrentSession().save(person);
		 return id;

	}


第二步,这里的sessionFactory即为org.hibernate.SessionFactory类的对象,需要在applicationContext.xml中加入这个对象的bean。


同时,在这个bean中配置了dataSource,引用了之前配置的数据源dataSource。

扫描二维码关注公众号,回复: 1946658 查看本文章

这里还有hibernateProperties属性,要配置hibernate.dialect的方言为org.hibernate.dialect.MySQLDialect。当然还有其他数据库的方言类型,比如Oracle数据库的方言为org.hibernate.dialect.OracleDialect,因为每个数据库所使用的sql语法略有不同,即为拥有自己的方言。

这里还要配置一个packagesToScan属性,指定到哪个包中去找数据表对应的类,比如org.spring.model.Person对应数据表new_table,包名value就配置为org.spring.model。


第三步,在Person类上面,加入一个注解@Entity,同时加入另一个注解@Table(name="new_table"),指明这个Person是对应数据表中的new_table表名。另个,还要给Person的id属性加上一个@Id注解,使这个id属性为数据表中的自增序号。



@Component
@Entity
@Table(name="new_table")
public class Person {
	

	@Autowired
	@Transient
	private Foot foot;
	
	@Autowired
	@Transient
	private Hand hand;
	
	@Autowired
	@Transient
	private Head head;
	
	@Id
	private int id;


因为Foot,Hand,Head这三个类在数据表中不存在,需要用@Transient注解,即为忽略这三个属性的映射。


第四步,在web.xml中加入一个Filter配置如下。filter-name是自定义的过滤器名称,filter-class配置为org.springframework.orm.hibernate4.support.OpenSessionInViewFilter,可以看到是spring加载hibernate的OpenSession的。这是因为sessionFactory.getCurrentSession()方法执行里,Session会话需要提前打开,这样才能使用当前会话getCurrentSession()方法。


第五步,在applicationContext.xml中加入事务配置。transactionManager为org.springframework.orm.hibernate4.HibernateTransactionManager的一个实例,其中的属性sessionFactory即为Hibernate的数据库连接工厂类。


下面的aop:config及tx:advice为事务的AOP配置。这里先不解释为什么Hibernate的save方法需要事务,只需要把这个配置先放在这里,使save方法能够顺利执行即可。之后再回来看事务的配置是怎么一回事。


需要说明的是,这个tx的前缀要加入xml的声明,参照前面的做法在applicationContext.xml中加入xmlns:tx="http://www.springframework.org/schema/tx"以及http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd。


经过上面的五步,可以访问http://localhost:8080/springMvcMavenProject/regForm.jsp页面,填写注册信息并提交,数据库的数据表new_table会增加一条记录。


猜你喜欢

转载自blog.csdn.net/weixin_41239710/article/details/80786318
今日推荐