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




package com.baidu.doublemany2many;

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 test() {
		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);
		
		
		role.getUsers().add(user);
		role.getUsers().add(user2);
		
		role2.getUsers().add(user);
		role2.getUsers().add(user2);
		
		//执行保存操作
		session.save(user);
		session.save(user2);
		session.save(role);
		session.save(role2);
	}

}


运行的SQL

Hibernate: 
    insert 
    into
        USER
        (U_NAME) 
    values
        (?)
Hibernate: 
    insert 
    into
        USER
        (U_NAME) 
    values
        (?)
Hibernate: 
    insert 
    into
        ROLE
        (R_NAME) 
    values
        (?)
Hibernate: 
    insert 
    into
        ROLE
        (R_NAME) 
    values
        (?)
Hibernate: 
    insert 
    into
        T_USER_ROLE
        (U_ID, R_ID) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        T_USER_ROLE
        (U_ID, R_ID) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        T_USER_ROLE
        (U_ID, R_ID) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        T_USER_ROLE
        (U_ID, R_ID) 
    values
        (?, ?)






你可能感兴趣的:(Hibernate)