第二周(上)

玩了这么长时间的spring却连spring是如何运转的都不知道,晕。
spring关联对应xml文件,一般取名applicationContext.xml,文件中包含各种bean通过自动注入等多种方式进行申明赋值。配合springmvc使用时一种是直接写到mvc-servlet即dispatchservlet对应的xml配置文件中去,但貌似有什么不方便,所以大部分会使用web.xml来进行额外配置。




contextConfigLocation
classpath:applicationContext.xml

org.springframework.web.context.ContextLoaderListener



数据库对应的配置将会在此文件中进行配置,我本次学习使用的是hibernate。按照书上所看一般是要写对应的cfg配置以及对应表的各列来写对应的表属性的xml,此方法 网上很多教程都是这个样子我买的JavaWeb入门上面也是这个方式,但现在更多流行的是注解,因为xml虽然配置和修改方便,但我觉得还是注解好用可以快速开发。在我们的spring配置里面让把hibernate配置成一个bean,托管给了spring平台。我们还可以把数据库的配置文件抽出来名为db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mws?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=zzpdream
connection pool settings jdbc.initPoolSize=5 jdbc.maxPoolSize=20 jdbc.driver = com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://localhost:3306/ssh?useUnicode=true&characterEncoding=utf-8 jdbc.username = root jdbc.password = zzpdream hibernate config hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.hbm2ddl.auto = update









${hibernate.hbm2ddl.auto} ${hibernate.dialect}${hibernate.show_sql}${hibernate.format_sql}falseorg.springframework.orm.hibernate5.SpringSessionContext



这边上面的自动扫描把controller过滤了,而在springmvc配置中又把service过滤,是为了防止什么service dao的操作大家互相注册就乱了,因为数据库bean是配置在spring中的,所以所有的service和dao中对应的上下文应该是spring吧,spring是包含于springmvc的,会优先加载spring。
事务的配置 如果不加上这句 就开启不了注解的方式来申明事务,看网上还有大部分采用aop等xml里面配置的方式,可是我也不太懂就不想看了。事务是为了方便回滚啊什么的,包括限定只能存活着只能取,还有着自动帮你提交的功能??但我当时在配置了事务后还是每次
"hibernate.current_session_context_class" 这个属性如果不加上指明设定上下文,昨天搞了我好久,如果不设置这个属性
sessionFactory.getCurrentSession(); 一用就报错说上下文不对,我设置成thread也报错。上下文不一致。
而sessionFactory.openSession()就能用,但这两者是有区分的。
1:getCurrentSession会把Session和当前的线程关联起来,而openSession只是重新开启一个Session
2:getCurrentSession获得的Session会在事务关闭或者回滚时会自动关闭,而openSession获得的Session必须手动关闭
这就产生了昨天一个神奇的现象,我按照教程配置,最后每次结果页面是插入数据库成功,但数据库中并没有数据。我查了很多教程,有说事务问题,我配置了还是没用。
当时当时我是opensession来获取session 使用如下代码又是有用的,数据库中又有数据了

Session session=getCurrentSession();
Transaction tr=session.beginTransaction();
try {
session.save(entity); //一个方法
} catch (HibernateException e) {
e.printStackTrace();
}
tr.commit();


最终我用事务+指定上下文+getcurrentsession方法也成功可以往数据库中加入数据了。
【第二周(上)】原文配置springmvc+spring+hibernate的地址如下
http://www.cnblogs.com/xrog/p/6359706.html

    推荐阅读