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





package com.baidu.one2one.primary;

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 TestPCprimary {
	
	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 testSave() {
		Person person = new Person();
		person.setPersonName("Person-1");
		person.setAge(25);
		
		Card card = new Card();
		card.setCardName("Ope Card");
		
		
		//设定关联关系
		card.setPerson(person);
		person.setCard(card);
		
		//save 操作
		//先插入那个都不会有多余的Update
		session.save(card);
		session.save(person);
	}

}








你可能感兴趣的:(Hibernate)