解析下HibernateSessionFactory.java

democreen 2011-01-07 05:04:58

package org.xmh.db;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {

/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;

static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}

/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();

if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}

return session;
}

/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}

/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);

if (session != null) {
session.close();
}
}

/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}

/**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}

/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}

}





学习hibernate,我现在想从自己手上的一个hibernate+spring的web实例去解读,零基础开始学习hibernate+spring

只要能尽快学会使用,或者能给我提供帮助的,我都给分,
我的疑问:
这个文件是自动生成还是手写的,自动生成的话,请给我详细说说如何自动生成,对于我来讲,参照这个自己也是手敲,
如果是手写,能跟我注释下,让我看明白也行,
关于这个文件的用途以及用到的要点,或者如何去理解,也行,回头我看看大家的意见,谢谢大家。


第二个问题:
String sqlquery = "from Person ";
//该方法用来打印Person表中的所有的用户名
//该语句用来通过HibernateTemplate来查询Person表中的所有记录
List list = this.getHibernateTemplate().find(sqlquery);
System.out.println("表中的数据有: " + list.size() + " 条");
...

List list = this.getHibernateTemplate().find(sqlquery);


跟我讲一下,getHibernateTemplate().find("from Person")
什么意思?讲具体点.
...全文
469 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
ccycxy123 2011-01-09
  • 打赏
  • 举报
回复
给你说你到网上去找个ssh整合的视屏来看看就好了……不过我觉得你要想用hibernate+spring的话,你要明白orm,aop,ioc……不然你只学会现在你看的这个对你来说只是会套用而已,实际开发中你必须要对这些有所了解才能让程序的开发更加合理……希望对你有所帮助。
凡是都是从开始做起走的,不急不躁就好了……
democreen 2011-01-08
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 wangju309 的回复:]
先理解一下spring注入功能,HibernateSessionFactory一般配置在sping配置文件中
学习最快的方法就是找个简单教程,照着做一遍,理解一下都是怎么回事
getHibernateTemplate().find("from Person")
Person实体对应的表需要在hbm.xml文件中配置
hibernate自动解析文件找到表查询数据
[/Quote]

你说的我明白,我今天就是自己动手写了一个,还行,但是对有的地方还是一知半解,比如说:比如说

HibernateSessionFactory.java 这个文件我是真的真的,想有人给我注释下, 哎,其他的问题我百度,谷歌都搞定了,现在就是这个HibernateSessionFactory文件,知道多少都可以过来说两句,
自己敲一遍或者敲点代码,确实是不一样,努力,努力!
神马都是浮云,只有动手才给力!
alongines 2011-01-08
  • 打赏
  • 举报
回复
1 创建Configuration对象
2 加载hibernate.cfg.xml文件
3 创建sessionFactory对象
4 得到Session
5 关闭Session
wangju309 2011-01-07
  • 打赏
  • 举报
回复
先理解一下spring注入功能,HibernateSessionFactory一般配置在sping配置文件中
学习最快的方法就是找个简单教程,照着做一遍,理解一下都是怎么回事
getHibernateTemplate().find("from Person")
Person实体对应的表需要在hbm.xml文件中配置
hibernate自动解析文件找到表查询数据
democreen 2011-01-07
  • 打赏
  • 举报
回复
在spring的配置文件中,随处都可以见到


<!-- 这是第一个例子的Spring配置 -->
<bean id="userbiz" class="org.xmh.biz.PersonBiz">
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>
<!-- 这是第二个例子的Spring配置 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>
<bean id="userDaoTarget" class="org.xmh.biz.PersonBizImpl">
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>

所以search到上面的文件HibernateSessionFactory.java中,希望给予解答,我自己也在google,baidu,谢谢大家,

没人理我吗?
弃用了struts,用spring mvc框架做了几个项目,感觉都不错,而且使用了注解方式,可以省掉一大堆配置文件。本文主要介绍使用注解方式配置的spring mvc,之前写的spring3.0 mvc和rest小例子没有介绍到数据层的内容,现在这一篇补上。下面开始贴代码。 文中用的框架版本:spring 3,hibernate 3,没有的,自己上网下。 先说web.xml配置: [java] view plaincopy 01.<?xml version="1.0" encoding="UTF-8"?> 02. 03. s3h3 04. 05. contextConfigLocation 06. classpath:applicationContext*.xml 07. 08. 09. org.springframework.web.context.ContextLoaderListener 10. 11. 12. 13. spring 14. org.springframework.web.servlet.DispatcherServlet 15. 1 16. 17. 18. spring <!-- 这里在配成spring,下边也要写一个名为spring-servlet.xml的文件,主要用来配置它的controller --> 19. *.do 20. 21. 22. index.jsp 23. 24. spring-servlet,主要配置controller的信息 [java] view plaincopy 01.<?xml version="1.0" encoding="UTF-8"?> 02. 09. 10. 11. <!-- 把标记了@Controller注解的类转换为bean --> 12. 13. <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> 14. 15. 16. <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --> 17. 19. 20. 23. applicationContext.xml代码 [java] view plaincopy 01.<?xml version="1.0" encoding="UTF-8"?> 02. 11. 12. 13. <!-- 自动扫描所有注解该路径 --> 14. 15. 16. 17. 19. 20. 21. 22. ${dataSource.dialect} 23. ${dataSource.hbm2ddl.auto} 24. update 25. 26. 27. 28. 29. com.mvc.entity<!-- 扫描实体类,也就是平时所说的model --> 30. 31. 32. 33. 34. 36. 37. 38. 39. 40. 42. 43. 44. 45. 46. 47. <!-- Dao的实现 --> 48. 49. 50. 51. 52. 53. 54. 55. hibernate.properties数据库连接配置 [java] view plaincopy 01.dataSource.password=123 02.dataSource.username=root 03.dataSource.databaseName=test 04.dataSource.driverClassName=com.mysql.jdbc.Driver 05.dataSource.dialect=org.hibernate.dialect.MySQL5Dialect 06.dataSource.serverName=localhost:3306 07.dataSource.url=jdbc:mysql://localhost:3306/test 08.dataSource.properties=user=${dataSource.username};databaseName=${dataSource.databaseName};serverName=${dataSource.serverName};password=${dataSource.password} 09.dataSource.hbm2ddl.auto=update 配置已经完成,下面开始例子 先在数据库建表,例子用的是mysql数据库 [java] view plaincopy 01.CREATE TABLE `test`.`student` ( 02. `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 03. `name` varchar(45) NOT NULL, 04. `psw` varchar(45) NOT NULL, 05. PRIMARY KEY (`id`) 06.) 建好表后,生成实体类 [java] view plaincopy 01.package com.mvc.entity; 02. 03.import java.io.Serializable; 04. 05.import javax.persistence.Basic; 06.import javax.persistence.Column; 07.import javax.persistence.Entity; 08.import javax.persistence.GeneratedValue; 09.import javax.persistence.GenerationType; 10.import javax.persistence.Id; 11.import javax.persistence.Table; 12. 13.@Entity 14.@Table(name = "student") 15.public class Student implements Serializable { 16. private static final long serialVersionUID = 1L; 17. @Id 18. @Basic(optional = false) 19. @GeneratedValue(strategy = GenerationType.IDENTITY) 20. @Column(name = "id", nullable = false) 21. private Integer id; 22. @Column(name = "name") 23. private String user; 24. @Column(name = "psw") 25. private String psw; 26. public Integer getId() { 27. return id; 28. } 29. public void setId(Integer id) { 30. this.id = id; 31. } 32. 33. public String getUser() { 34. return user; 35. } 36. public void setUser(String user) { 37. this.user = user; 38. } 39. public String getPsw() { 40. return psw; 41. } 42. public void setPsw(String psw) { 43. this.psw = psw; 44. } 45.} Dao层实现 [java] view plaincopy 01.package com.mvc.dao; 02. 03.import java.util.List; 04. 05.public interface EntityDao { 06. public List<Object> createQuery(final String queryString); 07. public Object save(final Object model); 08. public void update(final Object model); 09. public void delete(final Object model); 10.} [java] view plaincopy 01.package com.mvc.dao; 02. 03.import java.util.List; 04. 05.import org.hibernate.Query; 06.import org.springframework.orm.hibernate3.HibernateCallback; 07.import org.springframework.orm.hibernate3.support.HibernateDaoSupport; 08. 09.public class EntityDaoImpl extends HibernateDaoSupport implements EntityDao{ 10. public List<Object> createQuery(final String queryString) { 11. return (List<Object>) getHibernateTemplate().execute( 12. new HibernateCallback<Object>() { 13. public Object doInHibernate(org.hibernate.Session session) 14. throws org.hibernate.HibernateException { 15. Query query = session.createQuery(queryString); 16. List<Object> rows = query.list(); 17. return rows; 18. } 19. }); 20. } 21. public Object save(final Object model) { 22. return getHibernateTemplate().execute( 23. new HibernateCallback<Object>() { 24. public Object doInHibernate(org.hibernate.Session session) 25. throws org.hibernate.HibernateException { 26. session.save(model); 27. return null; 28. } 29. }); 30. } 31. public void update(final Object model) { 32. getHibernateTemplate().execute(new HibernateCallback<Object>() { 33. public Object doInHibernate(org.hibernate.Session session) 34. throws org.hibernate.HibernateException { 35. session.update(model); 36. return null; 37. } 38. }); 39. } 40. public void delete(final Object model) { 41. getHibernateTemplate().execute(new HibernateCallback<Object>() { 42. public Object doInHibernate(org.hibernate.Session session) 43. throws org.hibernate.HibernateException { 44. session.delete(model); 45. return null; 46. } 47. }); 48. } 49.} Dao在applicationContext.xml注入 Dao只有一个类的实现,直接供其它service层调用,如果你想更换为其它的Dao实现,也只需修改这里的配置就行了。 开始写view页面,WEB-INF/view下新建页面student.jsp,WEB-INF/view这路径是在spring-servlet.xml文件配置的,你可以配置成其它,也可以多个路径。student.jsp代码 [xhtml] view plaincopy 01.<%@ page language="java" contentType="text/html; charset=UTF-8" 02. pageEncoding="UTF-8"%> 03.<%@ include file="/include/head.jsp"%> 04. 05.<html> 06.<head> 07.<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 08.<title>添加</title> 09. 11.// --><!-- 13.table{ border-collapse:collapse; } 14.td{ border:1px solid #f00; } 15.--><style mce_bogus="1">table{ border-collapse:collapse; } 16.td{ border:1px solid #f00; }</style> 17.<!-- 18.function add(){ 19. [removed].href="<%=request.getContextPath() %>/student.do?method=add"; 20.} 21. 22.function del(id){ 23.$.ajax( { 24. type : "POST", 25. url : "<%=request.getContextPath()%>/student.do?method=del&id;=" + id, 26. dataType: "json", 27. success : function(data) { 28. if(data.del == "true"){ 29. alert("删除成功!"); 30. $("#" + id).remove(); 31. } 32. else{ 33. alert("删除失败!"); 34. } 35. }, 36. error :function(){ 37. alert("网络连接出错!"); 38. } 39.}); 40.} 41.// --> 47. 48. 序号 49. 姓名 50. 密码 51. 操作 52. 53. 54. "> 55. 56. 57. 58. 59. <input type="button" value="编辑"/> 60. <input type="button" value="${student.id}"/>')" value="删除"/> 61. 62. 63. 64. 65. 66.</body> 67.</html> student_add.jsp [xhtml] view plaincopy 01.<%@ page language="java" contentType="text/html; charset=UTF-8" 02. pageEncoding="UTF-8"%> 03.<%@ include file="/include/head.jsp"%> 04. 05.<html> 06.<head> 07.<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 08.<title>学生添加</title> 09.<!-- 10.function turnback(){ 11. [removed].href="<%=request.getContextPath() %>/student.do"; 12.} 13.// --> 17.
18. 19. 20. 21. 22.
姓名<input id="user" name="user" type="text" /></td>
密码<input id="psw" name="psw" type="text" /></td>
<input type="submit" value="提交"/><input type="button" value="返回" />
23. 24.</form> 25.</body> 26.</html> controller类实现,只需把注解写上,spring就会自动帮你找到相应的bean,相应的注解标记意义,不明白的,可以自己查下@Service,@Controller,@Entity等等的内容。 [java] view plaincopy 01.package com.mvc.controller; 02. 03.import java.util.List; 04. 05.import javax.servlet.http.HttpServletRequest; 06.import javax.servlet.http.HttpServletResponse; 07. 08.import org.apache.commons.logging.Log; 09.import org.apache.commons.logging.LogFactory; 10.import org.springframework.beans.factory.annotation.Autowired; 11.import org.springframework.stereotype.Controller; 12.import org.springframework.ui.ModelMap; 13.import org.springframework.web.bind.annotation.RequestMapping; 14.import org.springframework.web.bind.annotation.RequestMethod; 15.import org.springframework.web.bind.annotation.RequestParam; 16.import org.springframework.web.servlet.ModelAndView; 17. 18.import com.mvc.entity.Student; 19.import com.mvc.service.StudentService; 20. 21.@Controller 22.@RequestMapping("/student.do") 23.public class StudentController { 24. protected final transient Log log = LogFactory 25. .getLog(StudentController.class); 26. @Autowired 27. private StudentService studentService; 28. public StudentController(){ 29. 30. } 31. 32. @RequestMapping 33. public String load(ModelMap modelMap){ 34. List<Object> list = studentService.getStudentList(); 35. modelMap.put("list", list); 36. return "student"; 37. } 38. 39. @RequestMapping(params = "method=add") 40. public String add(HttpServletRequest request, ModelMap modelMap) throws Exception{ 41. return "student_add"; 42. } 43. 44. @RequestMapping(params = "method=save") 45. public String save(HttpServletRequest request, ModelMap modelMap){ 46. String user = request.getParameter("user"); 47. String psw = request.getParameter("psw"); 48. Student st = new Student(); 49. st.setUser(user); 50. st.setPsw(psw); 51. try{ 52. studentService.save(st); 53. modelMap.put("addstate", "添加成功"); 54. } 55. catch(Exception e){ 56. log.error(e.getMessage()); 57. modelMap.put("addstate", "添加失败"); 58. } 59. 60. return "student_add"; 61. } 62. 63. @RequestMapping(params = "method=del") 64. public void del(@RequestParam("id") String id, HttpServletResponse response){ 65. try{ 66. Student st = new Student(); 67. st.setId(Integer.valueOf(id)); 68. studentService.delete(st); 69. response.getWriter().print("{/"del/":/"true/"}"); 70. } 71. catch(Exception e){ 72. log.error(e.getMessage()); 73. e.printStackTrace(); 74. } 75. } 76.} service类实现 [java] view plaincopy 01.package com.mvc.service; 02. 03.import java.util.List; 04. 05.import org.springframework.beans.factory.annotation.Autowired; 06.import org.springframework.stereotype.Service; 07.import org.springframework.transaction.annotation.Transactional; 08. 09.import com.mvc.dao.EntityDao; 10.import com.mvc.entity.Student; 11. 12.@Service 13.public class StudentService { 14. @Autowired 15. private EntityDao entityDao; 16. 17. @Transactional 18. public List<Object> getStudentList(){ 19. StringBuffer sff = new StringBuffer(); 20. sff.append("select a from ").append(Student.class.getSimpleName()).append(" a "); 21. List<Object> list = entityDao.createQuery(sff.toString()); 22. return list; 23. } 24. 25. public void save(Student st){ 26. entityDao.save(st); 27. } 28. public void delete(Object obj){ 29. entityDao.delete(obj); 30. } 31.} OK,例子写完。有其它业务内容,只需直接新建view,并实现相应comtroller和service就行了,配置和dao层的内容基本不变,也就是每次只需写jsp(view),controller和service调用dao就行了。 怎样,看了这个,spring mvc是不是比ssh实现更方便灵活。
使用hibernate编程步骤 1)配置环境,加载hibernate的jar文件,以及连接数据库连接使用的jar文件,并配置CLASSPATH环境变量。 2)写POJO类(普通的java类) 3)写hibernate所需的配置文件,hibernate.cfg.xml ,Xxxxx.hbm.xml 4)调用hibernate API。 a)使用Configuration对象的buildSessionFactory()方法创建SessionFactory对象。 b)使用SessionFactory对象openSession()方法创建Session对象。 c)使用Session的相应方法来操作数据库,将对象信息持久化到数据库。 3.Hibernate的5个核心类或接口: (1)Configuration:用于解析hibernate.cfg.xml文件和XXXXX.hbm.xml文件,并创建SessionFactory对象。Configuration对象用于配置并且启动HibernateHibernate应用通过Configuration实例来指定对象--关系映射文件的位置或者动态配置Hibernate的属性,然后创建SessionFactory实例。 (2)SessionFactory:初始化Hibernate,充当数据存储源的代理,创建Session对象。一个SessinFactory实例对应一个数据存储源,应用从SessionFactory中获得Session实例。如果应用同时访问多个DB,怎需要为每个数据库创建一个单独的SessionFactory实例。 (3)Session:也被称为持久化管理器,对象级数据库操作。 特点: 1)不是线程安全的,因此在设计软件架构时,应该避免多个线程共享同一个Session实例。 2)Session实例是轻量级的,所谓轻量级,是指它的创建和销毁不需要消耗太多的资源。这意味着在程序中可以经常创建或销毁Session对象,例如为每个客户请求分配单独的Session实例,或者为每个工作单位分配单独的Session实例。 3)通常将每一个Session实例和一个DB事务邦定,也就是说,每执行一个DB事务,都应该先创建一个新的Session实例,不论事务执行成功与否,最后都应该调用Session的close()方法,从而释放Session实例占用的资源。 注:每个Session实例都有自己的缓存,这个Session实例的缓存只能被当前的工作单元访问。 (4)Query:执行数据库查询操作。要使用HQL(HibernateQueryLanguage)查询语句,HQL查询语句是面向对象的,它引用类名及类的属性名。 select/update/delete…… from …… where …… group by …… having …… order by …… asc/desc Transaction:用于管理操作事务。它对底层的事务接口做了封装,底层事务接口包括:JDBC API、JTA(JavaTransactionAPI)、CORBA(CommonObjectRequestBroker Architecture)API。

67,515

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧