开发环境配置(hibernate4)和简单增删改查

来源:互联网 发布:开淘宝网店详细步骤 编辑:程序博客网 时间:2024/06/04 05:31

导入架包

上面最后导入是的Oracle的架包,如果需要其他的数据库架包可以自己导入

在eclipse上安装hibernate tools插件。

注意:安装hibernate 插件必须要在有网路的情况下才能下载安装成功
Eclipse的“Help”-->"Eclipse Marketplace", 输入hibernate查找,因为Hibernate是JBoss的一种,所以安装的是JBoss Tools,安装的时候只选择Hiberante Tools即可。





点击第二个按钮后,会进入一个窗口,点击窗口右下角的‘我接受协议’即可安装完成,安装完成后eclipse会自动重启


Hibernate.cfg.XML全局配置文件

注意hibernate.cfg.xml文件在必须配置在classpath目录下
HibernateTools的安装完成!选择工程下的SRC目录,然后右键 New->Other->Hibernate->Hibernate Configuration File(cfg.xml)。


创建Hibernate Configuration File(cfg.xml)进行文件的配置
<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property><property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property><property name="hibernate.connection.username">scott</property><property name="hibernate.connection.password">123</property>
 <!-- hibernate 所使用的数据库方言 -->        <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- hibernate 所使用的mysql数据库方言  <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property> -->
<!-- 在控制台显示sql语句 --><property name="show_sql">true</property><!-- 以格式化的方式输出SQL语句 --><property name="format_sql">true</property><!-- 引入hbm配置文件  注意:这里引入的是实体类包中的hbm配置文件,但文件路径是以 / 来分割,而不是‘.’--><mapping resource="com/mingde/po/Students.hbm.xml"/><mapping resource="com/mingde/po/Classes.hbm.xml"/></session-factory></hibernate-configuration>

创建持久化类(普通的类)(Persistent Objects)

package com.mingde.po;import java.sql.Date;public class Students {private int sid;private String sname;private String ssex;private Date sdate;private int cid;
//以下省略//一个无参构造器
//一个不包含外键的有参构造器
//一个包含全部属性的有参构造器
//get 和 set 方法
//toString 方法}
Classes.java省略

 创建对象-关系映射文件(*.hbm.xml)

右键某个类会默认为该类创建 hbm.xml 文件


下面的信息会根据JavaBean自己生成


重点:每当创建一个hbm.xml文件后一定要将其文件引入到hibernate.cfg.xml文件中,否则无法关联到

没额

在Utils 包中创建类HibernateSessionFactory.java

package com.mingde.utils;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;import org.hibernate.service.ServiceRegistry;import org.hibernate.service.ServiceRegistryBuilder;public class HibernateSessionFactory {/** 引入sessionFactory (sessionFactory:session工厂) */private static SessionFactory sessionFactory;/**构造Configuration配置   */private static Configuration config=new Configuration();/**定义一个ThreadLocal(本地路线)对象用于存放session (仅仅用于存放session,好来判断SessionFactory是否为空)*/private static ThreadLocal<Session> threadLocal=new ThreadLocal<>();static{//1.读取放在classpath下的全局文件hibernate.cfg.xmlconfig.configure();//2.构造ServiceRegistry对象(注册服务) 通过在classpath下的全局文件hibernate.cfg.xml的配置建立起注册服务ServiceRegistry sr=new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();//3.生成一个sessionFactorysessionFactory =config.buildSessionFactory(sr);}//获取session对象public static Session getSession(){Session session=threadLocal.get();//threadLocal(本地路线)是用来存放sessioin的,是用来判断session里面是否有已经有打开了的工厂,以确保可以正常开工,//如果session里面没有工厂,那么就进行重新创注册服务的sessionFactory(sessioin工厂)工厂(sessionFactory),如果有那就进行下面的操作,打开session进行工作if(null==session || !session.isOpen()){if(sessionFactory == null){//重新创建起session工厂rebuildSessionFactory();}}//如果sessionFactory工厂不为空,那么就让sessionFactory工厂将session打开,然后将其赋给session,打开了的sessionFactory工厂可以进行开工;(比如:开启事务,执行命令,提交事务,回滚事务)session=(sessionFactory!=null)?sessionFactory.openSession():null;//将session设置到threadLocal中threadLocal.set(session);return session;}//重建sessionFactoryprivate static void rebuildSessionFactory() {//1.读取hibernate.cfg.xmlconfig.configure();//2.构造ServiceRegistry对象(注册服务) 先new一个注册服务对象,然后请求设置安装配置性能,接着建立起服务注册对象ServiceRegistry serviceRegistry =new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();//3.利用配置建立生成一个注册服务的sessionFactory(sessioin工厂)sessionFactory =config.buildSessionFactory(serviceRegistry);}//关闭sessionpublic static void closeSession(){//将threadLocal的值session值赋给sessioin,然后将threadLocal的值设置为空,如果session的值不为空,那么就关闭清空sessionSession session=threadLocal.get();threadLocal.set(null);if(session!=null){session.close();}}}
总的来说:就是利用配置性能来创建一个注册服务的工厂
读取hibernate.cfg.xml,通过配置的性能来创建服务注册对象,再通过注册服务对象来建立起工厂,(有了注册服务的工厂就可以进行开工,比如:开启事务,执行命令,提交事务,回滚事务),再将工厂放入session里面,以便外部取用session里面的工厂进行开工


用HIbernate做增删改查

配置文件就是什么的文件

Dao包的BaseDaoImpl.java
package com.mingde.dao.impl;import java.util.List;import org.hibernate.Session;import org.hibernate.Transaction;import com.mingde.dao.IBaseDao;import com.mingde.po.Students;import com.mingde.utils.HibernateSessionFactory;public class BaseDaoImpl implements IBaseDao {@Overridepublic List findAll(String hql)  {List list = null;//1.得到session对象Session session = HibernateSessionFactory.getSession();Transaction tx = null;try {//2.开启事务tx = session.beginTransaction();//3.执行命令list =  session.createQuery(hql).list();//4.提交事务tx.commit();} catch (Exception e) {e.printStackTrace();//回滚事务tx.rollback();}finally{//关闭事务HibernateSessionFactory.closeSession();}return list;}@Overridepublic void add(Students st) {//1.得到session对象Session session=HibernateSessionFactory.getSession();Transaction tx = null;try{//2.开启事务tx = session.beginTransaction();//3.执行命令session.save(st);//4.提交事务tx.commit();}catch(Exception e){e.printStackTrace();//数据回滚tx.rollback();}finally{//关闭事务HibernateSessionFactory.closeSession();}}@Overridepublic Students findOne(Class<Students> class1, int sid) {Students st=null;//得到session对象Session session=HibernateSessionFactory.getSession();Transaction tx=null;try {//开启事务tx=session.beginTransaction();//执行命令st=(Students) session.get(class1, sid);//提交事务tx.commit();} catch (Exception e) {e.printStackTrace();//数据回滚tx.rollback();}finally {//关闭事务HibernateSessionFactory.closeSession();}return st;}@Overridepublic void update(Students st) {//得到session对象Session session =HibernateSessionFactory.getSession();//开启事务Transaction tx=session.beginTransaction();try{//执行命令session.update(st);//提交事务tx.commit();}catch(Exception e){e.printStackTrace();//事务回滚tx.rollback();}finally{//关闭事务HibernateSessionFactory.closeSession();}}@Overridepublic void del(Students st) {//得到sessioin对象Session session=HibernateSessionFactory.getSession();Transaction tx=null;try {//开启事务tx=session.beginTransaction();//执行命令session.delete(st);//提交事务tx.commit();} catch (Exception e) {e.printStackTrace();//事务回滚tx.rollback();}finally{//关闭事务HibernateSessionFactory.closeSession();}}}

Struts.xml文件的配置
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"    "http://struts.apache.org/dtds/struts-2.3.dtd"><struts><constant name="struts.devMode" value="true"></constant><constant name="struts.enable.DynamicMethodInvocation" value="true"></constant><package name="struts" extends="struts-default"><action name="*_*" class="com.mingde.action.StudentsAction" method="{2}"><result name="{2}">/WEB-INF/{1}/{2}.jsp</result><result name="to_list" type="redirect">{1}_list</result><result name="list" >/WEB-INF/{1}/list.jsp</result></action></package></struts>

Action类
package com.mingde.action;import java.util.ArrayList;import java.util.List;import com.mingde.dao.IBaseDao;import com.mingde.dao.impl.BaseDaoImpl;import com.mingde.po.Classes;import com.mingde.po.Students;import com.opensymphony.xwork2.ActionSupport;@SuppressWarnings("serial")public class StudentsAction extends ActionSupport {private IBaseDao bd=new BaseDaoImpl();private List<Students> slist=new ArrayList<>();private List<Classes> clist=new ArrayList<>();private Students st=new Students();public String list() throws Exception {slist=bd.findAll("from Students");return "list";}public String toAdd() throws Exception {clist=bd.findAll("from Classes");return "toAdd";}public String toUpdate() throws Exception {clist=bd.findAll("from Classes");st=bd.findOne(Students.class,st.getSid());return "toUpdate";}public String add() throws Exception {bd.add(st);return "to_list";}public String update() throws Exception {bd.update(st);return "to_list";}public String del() throws Exception {bd.del(st);return "to_list";}/**************** get   set 方法 ****************/public List<Students> getSlist() {return slist;}public Students getSt() {return st;}public void setSt(Students st) {this.st = st;}public void setSlist(List<Students> slist) {this.slist = slist;}public List<Classes> getClist() {return clist;}public void setClist(List<Classes> clist) {this.clist = clist;}}

目录



JSP页面

list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><h2>列表</h2><table width=800 align="center" border=1 cellspacing=0><tr><td colspan=6><s:a href="students_toAdd">添加</s:a></td></tr><tr><th>编号</th><th>姓名</th><th>性别</th><th>生日</th><th>班级编号</th><th>操作</th></tr><s:iterator value="slist"><tr align="center"><td><s:property value="sid" /></td><td><s:property value="sname" /></td><td><s:property value="ssex" /></td><td><s:property value="sdate" /></td><td><s:property value="cid" /></td><td><s:a href="students_toUpdate?st.sid=%{sid}">修改</s:a><s:a href="students_del?st.sid=%{sid}" onclick="return confirm('确定删除?')" >删除</s:a></td></tr></s:iterator></table></body></html>

toAdd.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><s:form action="students_add"><s:textfield name="st.sname" label="姓名"></s:textfield><s:radio name="st.ssex" list="#{'M':'男','F':'女' }" value="'M'" label="性别" ></s:radio><s:textfield name="st.sdate" label="生日"></s:textfield><s:select list="clist" name="st.cid" listKey="cid" listValue="cname" label="班级" ></s:select><s:submit value="添加"></s:submit></s:form></body></html>

toUpdate.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><s:form action="students_update"><s:hidden name="st.sid"></s:hidden><s:textfield name="st.sname" label="姓名"></s:textfield><s:radio name="st.ssex" list="#{'M':'男','F':'女' }"  label="性别" ></s:radio><s:textfield name="st.sdate" label="生日"></s:textfield><s:select list="clist" name="st.cid" listKey="cid" listValue="cname" label="班级" ></s:select><s:submit value="修改"></s:submit></s:form></body></html>

注意:

Students.hbm.xml是通过实体类在创建的,所以2者有着关联,再将Students.hbm.xml引入到hibernate.cfg.xml文件下,3者的关系密不可分,3者一定要关联着,否则无法使用

原创粉丝点击