Hibernate 双向 1 对 1 对象关系映射 —外键关联 下 ,测试 crud






package com.baidu.one2one.foreign;

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 TestPC {

	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();
		
		System.out.println("init....");
	}
	@After
	public void destroy(){
		transaction.commit();
		session.close();
		sessionFactory.close();

		System.out.println("destory....");
	}
	
	@Test
	public void testGet2() {
		//在查询  没有外键  的实体对象时,使用左外连接查询,一并查询出其关联的对象
		//并已经进行初始化
		Person person = (Person) session.get(Person.class, 1);
		System.out.println(person.getPersonName());
		System.out.println(person.getCard().getCardName());
		
	}
	
	@Test
	public void testGet() {
		//1.默认情况下对关联属性使用懒加载
		Card card = (Card) session.get(Card.class, 1);
		System.out.println(card.getCardName());
		
		//2. 所以会出现懒加载异常的问题
//		session.close();
//		Person person = card.getPerson();
//		System.out.println(person.getClass());
//		System.out.println(person.getPersonName());
		
		/**
		 * 3. 查询Person 对象的连接条件应该是person0_.PERSON_ID=card1_.PERS_ID 
		 * 	      而不应该是 person0_.PERSON_ID=card1_.CARD_ID 
		 *
		 * 如何解决:
		 *	         在Person 即配置one-to-one 的一端添加属性:property-ref="person"
		 *	   
		 */
		
		Person person = card.getPerson();
		System.out.println(person.getPersonName());
	
	}
	

	@Test
	public void testSave() {
		Person person = new Person();
		person.setPersonName("Person-3");
		person.setAge(25);
		
		Card card = new Card();
		card.setCardName("Operat Card");
		
		
		//设定关联关系
		card.setPerson(person);
		person.setCard(card);
		
		//save 操作
		//建议先保存没有外键列的那个对象,这样会减少UPDATE语句
		session.save(card);
		session.save(person);
	}

}


你可能感兴趣的:(Hibernate)