⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 businessservice.java

📁 hibernate的经典练习
💻 JAVA
字号:
package com.ghy.test8;

import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import java.util.*;

public class BusinessService {
	public static SessionFactory sessionFactory;
	static {
		try {
			// Create a configuration based on the properties file we've put
			Configuration config = new Configuration();
			config.addClass(Student.class);
			// Get the session factory we can use for persistence
			sessionFactory = config.buildSessionFactory();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void saveStudent() throws Exception {
		// Ask for a session using the JDBC information we've configured
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		try {
			// Create some data and persist it
			tx = session.beginTransaction();
			Address add = new Address();
			add.setHome("吉林,长春");
			add.setCode("130011");
			MidStudent mistudent = new MidStudent("高洪宇01", add);
			mistudent.setType("高中生");
			add.setStudent(mistudent);
			session.save(mistudent);

			Academician acatudent = new Academician("高洪宇02", add);
			acatudent.setAcademic("大学本科");
			add.setStudent(acatudent);
			session.save(acatudent);
			tx.commit();
		} catch (Exception e) {
			if (tx != null) {
				// Something went wrong; discard all partial changes
				tx.rollback();
			}
			e.printStackTrace();
		} finally {
			// No matter what, close the session
			session.close();
		}
	}

	public void searchStudent() throws Exception {
		// Ask for a session using the JDBC information we've configured
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		try {
			// Create some data and persist it
			tx = session.beginTransaction();
			Query query = session.createQuery("from Student");
			Iterator i = query.iterate();
			while (i.hasNext()) {
				Student student = (Student) i.next();

				System.out.println("学生==" + student.getId()
						+ student.getStudentNumber()
						+ student.getAddress().getHome()
						+ student.getAddress().getCode());
			}
			tx.commit();
			;
		} catch (Exception e) {
			if (tx != null) {
				// Something went wrong; discard all partial changes
				tx.rollback();
			}
			e.printStackTrace();
		} finally {
			// No matter what, close the session
			session.close();
		}
	}

	public void test() throws Exception {
		try {
//			 saveStudent();
			 searchStudent();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String args[]) throws Exception {
		new BusinessService().test();
		sessionFactory.close();
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -