Hibernate 一对多 保存和修改数据

时间:2021-04-02 23:05:28

Student和Sclass表,Student外键cid是Sclass的cid

create table sclass(
cid varchar(8) primary key,
cname varchar(10)
)go
create table Student (
sid int primary key,
sname varchar(10),
sno varchar(10),
sex varchar(2),
email varchar(8),
cid varchar(8)
foreign key (cid) references sclass(cid)
)

自动生成的OMR映射文件(Myeclise逆向工程自动生成映射文件的详细步骤见上一篇Hibernate简单使用)

Sclass.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.rong.bean.Sclass" table="sclass" schema="dbo" catalog="XFL_XNH">
<id name="cid" type="string">
<column name="cid" length="8" />
<generator class="assigned" />
</id>
<property name="cname" type="string">
<column name="cname" length="10" />
</property>
<set name="students" inverse="true">
<key>
<column name="cid" length="8" />
</key>
<one-to-many class="org.rong.bean.Student" />
</set>
</class>
</hibernate-mapping>

Student.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.rong.bean.Student" table="Student" schema="dbo" catalog="XFL_XNH">
<id name="sid" type="integer">
<column name="sid" />
<generator class="assigned" />
</id>
<many-to-one name="sclass" class="org.rong.bean.Sclass" fetch="select">
<column name="cid" length="8" />
</many-to-one>
<property name="sname" type="string">
<column name="sname" length="10" />
</property>
<property name="sno" type="string">
<column name="sno" length="10" />
</property>
<property name="sex" type="string">
<column name="sex" length="2" />
</property>
<property name="email" type="string">
<column name="email" length="8" />
</property>
</class>
</hibernate-mapping>

HibernateSessionFactory.java为Myeclipse自动生成的SessionFactory。

package org.rong.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder; /**
* 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 final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory; private static Configuration configuration = new Configuration();
private static ServiceRegistry serviceRegistry; static {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} 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();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} 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 hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
} }

创建操作类

package org.rong.test;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.rong.bean.Sclass;
import org.rong.bean.Student;
import org.rong.util.HibernateSessionFactory; public class Operate {
private Session session=null; public Operate() {
session=HibernateSessionFactory.getSession();
// Transaction tran=session.beginTransaction();
// Configuration config=new Configuration().configure();
// SessionFactory facetory=config.buildSessionFactory();
// this.session=facetory.openSession();
}
public Object get(Class clazz,String id){
Transaction tran=this.session.beginTransaction();
Object obj=this.session.get(clazz, id);
tran.commit();
return obj;
}
public void insert(Object obj){
Transaction tran=this.session.beginTransaction();
this.session.save(obj);
tran.commit();
}
public void update(Object obj){
Transaction tran=this.session.beginTransaction();
this.session.update(obj);
tran.commit();
}
public void delete(Object obj){
Transaction tran=this.session.beginTransaction();
this.session.delete(obj);
tran.commit();
}
public List<Student> findAllStudent(){
Transaction tran=this.session.beginTransaction();
Query query=session.createQuery("from Student ");
// query.setFirstResult(1);
List<Student> students=(List<Student>)query.list();
tran.commit();
return students;
}
public List<Sclass> findAllSclass(){
Transaction tran=this.session.beginTransaction();
Query query=session.createQuery("from Student ");
// query.setFirstResult(1);
List<Sclass> sclasses=(List<Sclass>)query.list();
tran.commit();
return sclasses;
}
}

测试类

package org.rong.test;

import java.util.List;

import org.rong.bean.Sclass;
import org.rong.bean.Student; public class StudentTest { /**
* @param args
*/
public static void main(String[] args) {
// Configuration config=new Configuration().configure();
// SessionFactory facetory=config.buildSessionFactory();
// Session session=facetory.openSession();
// Session session=HibernateSessionFactory.getSession();
// Transaction tran=session.beginTransaction();
// Student stu=new Student();
// stu.setId("015");
// stu.setSname("dsfhdjdfu");
// stu.setSno("03130498");
// stu.setSex("男");
// stu.setEmail("dfdw@163.com");
// session.save(stu);
// Query query=session.createQuery("from Student");
// List<Student> students=(List<Student>)query.list();
// for(Student st:students){
// System.out.println("s:"+st.getId()+st.getSname()+st.getEmail());
// }
// Sclass sc=new Sclass();
// sc.setClassname("一班");
// session.save(sc);
Operate op=new Operate(); // Sclass sc=new Sclass();
// sc.setCid("1");
// sc.setCname("一班");
// op.insert(sc);
Sclass sclass=(Sclass) op.get(Sclass.class,"1");
Student stu=new Student();
stu.setSid(1);
stu.setSname("王府大55");
stu.setSex("男");
stu.setEmail("z@3.com");
stu.setSclass(sclass);
op.update(stu);
List<Student> students=op.findAllStudent();
for(Student stu1:students){
System.out.println(stu1.getSclass().getCid()+stu1.getSname());
}
} }