Hibernate 继承关系 对象关系映射--subclass ,测试 crud



package com.baidu.subclass;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class TestSubclassPerson {

	private SessionFactory sessionFactory;
	private Session session;
	private Transaction transaction;
	
	@Before
	public void init(){
		Configuration configuration = new Configuration().configure();
		
		ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
											.applySettings(configuration.getProperties())
											.buildServiceRegistry();
		
		sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		
		session = sessionFactory.openSession();
		transaction = session.beginTransaction();
		
		
	}
	@After
	public void destroy(){
		transaction.commit();
		session.close();
		sessionFactory.close();
		
	}
	/**
	 * 查询:
	 * 1. 查询父类记录,只需要查询一张数据表
	 * 2. 对于子类记录,也只需要查询一张数据表
	 * 
	 * subclass继承关系的缺点:
	 * 	1. 使用了辨别者列
	 *  2. 子类特有的字段不能使用非空约束
	 *  3. 若继承层次较深,则数据表的字段也会较多。 
	 * 
	 */
	
	@Test
	public void testGet() {
		List<Person> persons = session.createQuery("FROM Person").list();
		System.out.println(persons.size());
		
		List<Student> students = session.createQuery("FROM Student").list();
		System.out.println(students.size());
		
	}
	
	/**
	 * 插入操作:
	 * 	1. 对于子对象只需把记录插入到一张数据表中
	 * 	2. 辨别者列有 Hibernate 自动维护。
	 */
	
	@Test
	public void testSave() {
		Person person = new Person();
		person.setAge(15);
		person.setName("Person-AA");
		
		Student student = new Student();
		student.setAge(10);
		student.setName("Student-BB");
		student.setSchool("Student_school");
		
		session.save(student);
		session.save(person);
		
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值