使用Hibernate进行父子表的CRUD *** 作

使用Hibernate进行父子表的CRUD *** 作,第1张

使用Hibernate进行父子表的CRUD *** 作
  • Student.java
  • Student.hbm.xml
  • Course.java
  • Course.hbm.xml
  • HibernateUtil.java
  • StudentDAO.java
  • CourseDAO.java
  • hibernate.cfg.xml
  • Test.java
  • 测试结果截图(部分)

要求
1)目的:真正学会使用Hibernate来进行增加、查询、更新、删除 *** 作
2)内容:在数据库中建立父子表,分别能对父子表进行增加、查询、更新、删除 *** 作,一定要实现分页功能。

1、 新建一个名为test10的数据库,并新建表student_table、course_table。其中student_table为父表,course_table为子表。



2、 创建Student类、Course类,以及对应的xml文件

Student.java

位置: com.bnuz.domain

package com.bnuz.domain;

public class Student {
	private Integer id;
	private String name;
	private String academy;
	
	public Student() {
		// TODO Auto-generated constructor stub
	}
	// getter / setter 略...
}

Student.hbm.xml

位置: com.bnuz.domain

<?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 package="com.bnuz.domain">
	<class name="Student" table="student_table">
		<id name="id" type="java.lang.Integer">
			<generator class="identity" />
		</id>
		<property name="name" />
		<property name="academy" />
	</class>
</hibernate-mapping>
Course.java

位置:com.bnuz.domain

package com.bnuz.domain;

public class Course {

	private Integer courseNo;
	private String courseName;
	private Student student;

	public Course() {
		// TODO Auto-generated constructor stub
	}
	// getter /setter 略...
}

Course.hbm.xml

位置:com.bnuz.domain

<?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 package="com.bnuz.domain">
	<class name="Course" table="course_table">
		<id name="courseNo" column="course_no">
			<generator class="identity" />
		</id>
		<property name="courseName" />

		<many-to-one name="student" class="Student"
			column="student_id"/>
	</class>
</hibernate-mapping>

3、新建HibernateUtil类

HibernateUtil.java

位置:com.bnuz.hibernate

package com.bnuz.hibernate;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class HibernateUtil {
	public static final SessionFactory sessionFactory;
	static {
		try {
			Configuration configuration = new Configuration().configure();
			sessionFactory = configuration.buildSessionFactory();
		} catch (Throwable ex) {
			System.err.println("初始化sessionFactory失败." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}
	public static final ThreadLocal<Session> session = new ThreadLocal<Session>();

	public static Session currentSession() throws HibernateException {
		Session s = session.get();
		if (s == null) {
			s = sessionFactory.openSession();
			session.set(s);
		}
		return s;
	}

	public static void closeSession() throws HibernateException {
		Session s = session.get();
		if (s != null)
			s.close();
		session.set(null);
	}
}

4、 创建StudentDAO类,CourseDAO类。编写增删改查及分页方法。。
位置:com.bnuz.dao

StudentDAO.java
package com.bnuz.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.bnuz.domain.Student;
import com.bnuz.hibernate.HibernateUtil;

public class StudentDAO {
	/**
	 * 新增学生
	 * 
	 * @param student
	 */
	public static void addStudent(Student student) {
		Session session = HibernateUtil.currentSession();
		Transaction transaction = session.beginTransaction();
		session.save(student);
		transaction.commit();
		HibernateUtil.closeSession();
	}

	/**
	 * 根据学生id删除某个学生
	 * 
	 * @param id
	 */
	public static void delStudent(int id) {
		Session session = HibernateUtil.currentSession();
		Transaction transaction = session.beginTransaction();
		session.createQuery("delete Course where student=" + id).executeUpdate();
		session.createQuery("delete Student where id=" + id).executeUpdate();
		transaction.commit();
		HibernateUtil.closeSession();
	}

	/**
	 * 修改某个学生的信息
	 * 
	 * @param student
	 */
	public static void updateStudent(Student student) {
		Session session = HibernateUtil.currentSession();
		Transaction transaction = session.beginTransaction();
		session.update(student);
		transaction.commit();
		HibernateUtil.closeSession();
	}

	/**
	 * 根据学生id查询某个学生的信息
	 * 
	 * @param id
	 */
	public static void findStudent(int id) {
		Session session = HibernateUtil.currentSession();
		Transaction transaction = session.beginTransaction();
		Student student = (Student) session.get(Student.class, id);
		System.out.println("name:" + student.getName() + " academy:" + student.getAcademy());
		transaction.commit();
		HibernateUtil.closeSession();
	}

	/**
	 * 分页查询
	 * 
	 * @param pageNo   页码
	 * @param pageSize 每页的数据长度
	 */
	public static void PagingQueryStudent(int pageNo, int pageSize) {
		Session session = HibernateUtil.currentSession();
		Transaction transaction = session.beginTransaction();
		Query query = session.createQuery("from Student");
		query.setMaxResults(pageSize);
		query.setFirstResult((pageNo - 1) * pageSize);
		List<Student> list = query.list();
		System.out.println("--第" + pageNo + "页,每页至多有" + pageSize + "条数据----");
		for (Student student : list) {
			System.out.println(student.getId() + " " + student.getName() + " " + student.getAcademy());
		}
		transaction.commit();
		HibernateUtil.closeSession();
	}
}

CourseDAO.java
package com.bnuz.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.bnuz.domain.Course;
import com.bnuz.hibernate.HibernateUtil;

public class CourseDAO {
	/**
	 * 新增一个课程
	 * 
	 * @param course
	 */
	public static void addCourse(Course course) {
		Session session = HibernateUtil.currentSession();
		Transaction transaction = session.beginTransaction();
		session.save(course);
		transaction.commit();
		HibernateUtil.closeSession();
	}

	/**
	 * 根据课程id删除某个课程信息
	 * 
	 * @param courseNo
	 */
	public static void delCourse(int courseNo) {
		Session session = HibernateUtil.currentSession();
		Transaction transaction = session.beginTransaction();
		session.createQuery("delete Course where courseNo=" + courseNo).executeUpdate();
		transaction.commit();
		HibernateUtil.closeSession();
	}

	/**
	 * 修改某个课程信息
	 * 
	 * @param course
	 */
	public static void updateCourse(Course course) {
		Session session = HibernateUtil.currentSession();
		Transaction transaction = session.beginTransaction();
		session.update(course);
		transaction.commit();
		HibernateUtil.closeSession();
	}

	/**
	 * 根据课程id查询
	 * 
	 * @param courseNo
	 */
	public static void findCourse(int courseNo) {
		Session session = HibernateUtil.currentSession();
		Transaction transaction = session.beginTransaction();
		Course course = (Course) session.get(Course.class, courseNo);
		System.out.println("id为" + course.getStudent().getId() + "学生" + course.getStudent().getName() + "选修了课程:"
				+ course.getCourseName());
		transaction.commit();
		HibernateUtil.closeSession();
	}

	/**
	 * 分页查询
	 * 
	 * @param pageNo   页码
	 * @param pageSize 每页的数据长度
	 */
	public static void PagingQueryCourse(int pageNo, int pageSize) {
		Session session = HibernateUtil.currentSession();
		Transaction transaction = session.beginTransaction();
		Query query = session.createQuery("from Course");
		query.setMaxResults(pageSize);
		query.setFirstResult((pageNo - 1) * pageSize);
		List<Course> list = query.list();
		System.out.println("--第" + pageNo + "页,每页至多有" + pageSize + "条数据---");
		for (Course course : list) {
			System.out.println(course.getCourseNo() + " " + course.getCourseName() + " " + course.getStudent().getId());
		}
		transaction.commit();
		HibernateUtil.closeSession();
	}
}

5、配置hibernate.cfg.xml

hibernate.cfg.xml

位置:src

<?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>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test10?serverTimezone=GMT%2B8</property>
        <property name="connection.username">root</property>
        <property name="connection.password">4580796</property>   
        <property name="hibernate.c3p0.max_size">20</property>
        <property name="hibernate.c3p0.min_size">1</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hbm2ddl.auto">update</property>
        <property name="hibernate.format_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="show_sql">true</property>
        <mapping resource="com/bnuz/domain/Student.hbm.xml"/>
        <mapping resource="com/bnuz/domain/Course.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

6、编写测试类Test,测试所有方法

Test.java
import com.bnuz.dao.CourseDAO;
import com.bnuz.dao.StudentDAO;
import com.bnuz.domain.Course;
import com.bnuz.domain.Student;

public class Test {

	public static void main(String[] args) {
		Test test = new Test();
		/* test.testUpdateCourse(); */

	}
		
	private void testAddCourse() {
		Course course = new Course();
		course.setCourseName("C");
		Student student = new Student();
		student.setId(2);
		course.setStudent(student);
		CourseDAO.addCourse(course);
	}
	
	private void testDelCourse() {
		CourseDAO.delCourse(1);
	}
	
	private void testUpdateCourse() {
		Course course = new Course();
		course.setCourseNo(1);
		course.setCourseName("JAVA快乐入门教程");
		Student student = new Student();
		student.setId(2);
		course.setStudent(student);
		CourseDAO.updateCourse(course);
	}
	
	private void testFindCourse() {
		CourseDAO.findCourse(1);
	}
	
	private void testPagingQueryCourse() {
		CourseDAO.PagingQueryCourse(1, 4);
	}
	
	private void testPagingQueryStudent() {
		//StudentDAO.PagingQueryStudent(1, 3);
		StudentDAO.PagingQueryStudent(2, 3);
	}
	private void testFindStudent() {
		StudentDAO.findStudent(1);
	}
	
	private void testDelStudent() {
		StudentDAO.delStudent(1);
	}

	private void testAddStudent() {
		Student student = new Student();
		student.setName("yeye");
		student.setAcademy("信息技术学院");
		StudentDAO.addStudent(student);
	}
	private void testUpdateStudent() {
		Student student = new Student();
		student.setId(1);
		student.setName("hey");
		student.setAcademy("信息技术学院");
		StudentDAO.updateStudent(student);
	}
}

测试结果截图(部分)



…………

(;´д`)ゞ菜鸟一枚,,水水博客,如有问题,欢迎指教!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/795566.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-06
下一篇 2022-05-06

发表评论

登录后才能评论

评论列表(0条)

保存