Hibernate 一对一的增删改查

xiaoxiao2021-02-27  166

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?> <!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.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> <!-- 配置数据库发言 --> <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property> <!-- 将执行的sql语句输出到控制台上 --> <property name="show_sql" /> <!-- 将输出的sql语句进行格式化 --> <property name="format_sql" /> <!-- 配置hbm.xml文件 --> <mapping resource="com/mingde/po/Classes.hbm.xml"/> <mapping resource="com/mingde/po/Students.hbm.xml"/> <mapping resource="com/mingde/po/UserInfo.hbm.xml"/> </session-factory> </hibernate-configuration>

创建实体类

Classes.java

package com.mingde.po; import java.sql.Date; public class Classes { private int cid; private String cname; private Date copendate; public Classes() { super(); } public Classes(int cid, String cname, Date copendate) { super(); this.cid = cid; this.cname = cname; this.copendate = copendate; } public int getCid() { return cid; } public void setCid(int cid) { this.cid = cid; } public String getCname() { return cname; } public void setCname(String cname) { this.cname = cname; } public Date getCopendate() { return copendate; } public void setCopendate(Date copendate) { this.copendate = copendate; } @Override public String toString() { return "Classes [cid=" + cid + ", cname=" + cname + ", copendate=" + copendate + "]"; } }

Students.java

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; //在学生实体类中可查询出其对应的账户信息 private UserInfo userinfo; public Students() { super(); } public Students(int sid, String sname, String ssex, Date sdate, int cid) { super(); this.sid = sid; this.sname = sname; this.ssex = ssex; this.sdate = sdate; this.cid = cid; } public Students(int sid, String sname, String ssex, Date sdate, int cid, UserInfo userinfo) { super(); this.sid = sid; this.sname = sname; this.ssex = ssex; this.sdate = sdate; this.cid = cid; this.userinfo = userinfo; } public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getSsex() { return ssex; } public void setSsex(String ssex) { this.ssex = ssex; } public Date getSdate() { return sdate; } public void setSdate(Date sdate) { this.sdate = sdate; } public int getCid() { return cid; } public void setCid(int cid) { this.cid = cid; } public UserInfo getUserinfo() { return userinfo; } public void setUserinfo(UserInfo userinfo) { this.userinfo = userinfo; } @Override public String toString() { return "Students [sid=" + sid + ", sname=" + sname + ", ssex=" + ssex + ", sdate=" + sdate + ", cid=" + cid + ", userinfo=" + userinfo + "]"; } }

UserInfo.java

package com.mingde.po; public class UserInfo { private int userid; private String username; private String password; //关联学生类 private Students students; public UserInfo() { super(); } public UserInfo(int userid, String username, String password) { super(); this.userid = userid; this.username = username; this.password = password; } public Students getStudents() { return students; } public void setStudents(Students students) { this.students = students; } public int getUserid() { return userid; } public void setUserid(int userid) { this.userid = userid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "Userinfo [userid=" + userid + ", username=" + username + ", password=" + password + "]"; } }

hbm.xml文件配置

Classes.hbm.xml

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated 2017-8-4 15:41:45 by Hibernate Tools 3.5.0.Final --> <hibernate-mapping> <class name="com.mingde.po.Classes" table="CLASSES"> <id name="cid" type="int"> <column name="CID" /> <generator class="assigned" /> </id> <property name="cname" type="java.lang.String"> <column name="CNAME" /> </property> <property name="copendate" type="java.sql.Date"> <column name="COPENDATE" /> </property> </class> </hibernate-mapping>

Students.hbm.xml

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated 2017-8-4 15:51:26 by Hibernate Tools 3.5.0.Final --> <hibernate-mapping> <class name="com.mingde.po.Students" table="STUDENTS"> <!-- 定义主键 --> <id name="sid" type="int"> <column name="SID" /> <generator class="sequence" > <param name="sequence">sequ06</param> </generator> </id> <!-- 定义除主键外的其它字段,用property标签定义 --> <property name="sname" type="java.lang.String"> <column name="SNAME" /> </property> <property name="ssex" type="java.lang.String"> <column name="SSEX" /> </property> <property name="sdate" > <column name="SDATE" /> </property> <property name="cid" type="int"> <column name="CID" /> </property> <!-- 定义一对一的共享主键关联关系 -->   <!--    cascade:代表级联,即对当前的对象作增、删、改操作时,也会对其级联的对象作相应的操作,可取值:   1、save-update:代表对当前对象添加、修改时,也会对关联的对象作添加、修改操作   2、delete:代表对当前对象删除时,也会对关联的对象作删除操作 3、all:相当于save-update+delete两个操作 4、delete-oraph:删除孤儿对象,就是代表对某个多方对象对应的一方对象删除后,那么其余的多方对象  就会失去对一方对象的关联,也就是相当于孤儿,使用此选项,当删除一方对象时会主动删除这些多余的孤儿对象。 5、all-delete-orpah:相当于前面的四项之和。   lazy="false":默认是false,所以不用写,这里是查询时会自动去加载查询所关联的类的信息 fetch="join":默认的,所以不用写,这里是查询关联的表时,使用连接查询   -->   <!-- 配置一对一关联映射 --> <one-to-one name="userinfo" class="com.mingde.po.UserInfo" cascade="all" fetch="join" lazy="false" ></one-to-one> </class> </hibernate-mapping>

UserInfo.hbm.xml

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated 2017-8-4 15:51:26 by Hibernate Tools 3.5.0.Final --> <hibernate-mapping> <class name="com.mingde.po.UserInfo" table="USERINFO"> <id name="userid" type="int"> <column name="USERID" /> <!-- 这里的主键启用了外键,其主键值为students的主键值,这里使用了共享主键 --> <generator class="foreign" > <param name="property">students</param> </generator> </id> <property name="username" type="java.lang.String"> <column name="USERNAME" /> </property> <property name="password" type="java.lang.String"> <column name="PASSWORD" /> </property> <!-- 配置一对一关联映射 --> <one-to-one name="students" class="com.mingde.po.Students"></one-to-one> </class> </hibernate-mapping>

配置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.xml config.configure(); //2.构造ServiceRegistry对象(注册服务) 通过在classpath下的全局文件hibernate.cfg.xml的配置建立起注册服务 ServiceRegistry sr=new ServiceRegistryBuilder() .applySettings(config.getProperties()) .buildServiceRegistry(); //3.生成一个sessionFactory sessionFactory =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; } //重建sessionFactory private static void rebuildSessionFactory() { //1.读取hibernate.cfg.xml config.configure(); //2.构造ServiceRegistry对象(注册服务) 先new一个注册服务对象,然后请求设置安装配置性能,接着建立起服务注册对象 ServiceRegistry serviceRegistry =new ServiceRegistryBuilder() .applySettings(config.getProperties()) .buildServiceRegistry(); //3.利用配置建立生成一个注册服务的sessionFactory(sessioin工厂) sessionFactory =config.buildSessionFactory(serviceRegistry); } //关闭session public static void closeSession(){ //将threadLocal的值session值赋给sessioin,然后将threadLocal的值设置为空,如果session的值不为空,那么就关闭清空session Session session=threadLocal.get(); threadLocal.set(null); if(session!=null){ session.close(); } } }

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.enable.DynamicMethodInvocation" value="true"></constant> <constant name="struts.devMode" 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> </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 List<Students> slist=new ArrayList<>(); private IBaseDao bd=new BaseDaoImpl(); 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=(Students) bd.findOne(Students.class,st.getSid()); return "toUpdate"; } public String add() throws Exception { st.getUserinfo().setStudents(st); //建立起学生→用户→学生关联关系,保持一对一的连接 bd.add(st); return "to_list"; } public String update() throws Exception { st.getUserinfo().setStudents(st); //建立起学生→用户→学生关联关系,保持一对一的连接 bd.update(st); return "to_list"; } public String del() throws Exception { //根据学生编号查询学生和该学生的用户 //(因为该将关联在一起的用户和一同删除,所以必须通过查询一同查询, //若不查询直接删除的话,只会删除学生信息,而不会删除对应的用户) st=(Students) bd.findOne(Students.class,st.getSid()); 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 List<Classes> getClist() { return clist; } public void setClist(List<Classes> clist) { this.clist = clist; } public void setSlist(List<Students> slist) { this.slist = slist; } }

Dao层

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 { @Override public List findAll(String hql) { List list=null; Session session =HibernateSessionFactory.getSession(); Transaction tx=null; try { //开启事务 tx=session.beginTransaction(); //执行命令 list=session.createQuery(hql).list(); //提交事务 tx.commit(); } catch (Exception e) { e.printStackTrace(); //事务回滚 tx.rollback(); }finally{ //关闭事务 HibernateSessionFactory.closeSession(); } return list; } @Override public void add(Students st) { Session session =HibernateSessionFactory.getSession(); Transaction tx=null; try { //开启事务 tx=session.beginTransaction(); //执行命令 session.save(st); //提交事务 tx.commit(); } catch (Exception e) { e.printStackTrace(); //事务回滚 tx.rollback(); }finally{ //关闭事务 HibernateSessionFactory.closeSession(); } } @Override public Object findOne(Class<?> clazz, int sid) { Students st=null; //构造Session对象来存放工厂 Session session=HibernateSessionFactory.getSession(); //创建事务 Transaction tx=null; try { //开启事务 tx=session.beginTransaction(); //执行命令 st = (Students) session.get(clazz, sid); //提交事务 tx.commit(); } catch (Exception e) { e.printStackTrace(); //事务回滚 tx.rollback(); }finally{ //关闭事务 HibernateSessionFactory.closeSession(); } return st; } @Override public void update(Students st) { //创建Session对象 Session session=HibernateSessionFactory.getSession(); //创建事务对象 Transaction tx=null; try { //开启事务 tx=session.beginTransaction(); //执行命令 session.update(st); //提交事务 tx.commit(); } catch (Exception e) { e.printStackTrace(); //数据回滚 tx.rollback(); }finally{ //关闭事务 HibernateSessionFactory.closeSession(); } } @Override public void del(Students st) { 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(); } } }

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="8"><s:a href="students_toAdd">添加</s:a></td> </tr> <tr> <th>编号</th><th>姓名</th><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:date format="yyyy-MM-dd" name="sdate" /></td> <td><s:property value="cid" /></td> <td><s:property value="userinfo.username" /></td> <td><s:property value="userinfo.password" /></td> <td> <a href="students_toUpdate?st.sid=${sid}">修改</a> <s:a href="students_del?st.sid=%{sid }" οnclick="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> <h2>添加</h2> <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 name="st.cid" list="clist" listKey="cid" listValue="cname" label="班级" ></s:select> <s:textfield name="st.userinfo.username" label="用户名" ></s:textfield> <s:password name="st.userinfo.password" label="密码"></s:password> <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> <h2>修改</h2> <s:form action="students_update" > <s:hidden name="st.sid"></s:hidden> <s:hidden name="st.userinfo.userid"></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 name="st.cid" list="clist" listKey="cid" listValue="cname" label="班级" ></s:select> <s:textfield name="st.userinfo.username" label="用户名" ></s:textfield> <s:password name="st.userinfo.password" label="密码" showPassword="true"></s:password> <s:submit value="修改"></s:submit> </s:form> </body> </html>
转载请注明原文地址: https://www.6miu.com/read-13057.html

最新回复(0)