Hibernate 单向 多 对 多 对象关系映射 ,测试 crud











package com.baidu.many2many;

import java.util.Set;

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 TestRU {
	
	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 testMany2ManyGet() {
		User user = (User) session.get(User.class, 1);
		System.out.println(user.getuName());
		
		
		//需要连接中间表
		Set roles = user.getRoles();
		System.out.println(roles.size());
		
	}

	@Test
	public void testMany2ManySave() {
		User user = new User();
		user.setuName("User_A");
		User user2 = new User();
		user2.setuName("User_B");
		
		Role role = new Role();
		role.setrName("Manager_A");
		Role role2 = new Role();
		role2.setrName("Manager_B");
		
		//设置关联关系
		user.getRoles().add(role);
		user.getRoles().add(role2);
		
		user2.getRoles().add(role);
		user2.getRoles().add(role2);
		
		//执行保存操作
		session.save(user);
		session.save(user2);
		session.save(role);
		session.save(role2);
		
	}
}


你可能感兴趣的:(Hibernate)