Newer
Older
CosmosServer / src / test / java / hibernateTest / models / NativeApiIllustrationTest.java
/*
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
 * indicated by the @author tags or express copyright attribution
 * statements applied by the authors.  All third-party contributions are
 * distributed under license by Red Hat Inc.
 *
 * This copyrighted material is made available to anyone wishing to use, modify,
 * copy, or redistribute it subject to the terms and conditions of the GNU
 * Lesser General Public License, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this distribution; if not, write to:
 * Free Software Foundation, Inc.
 * 51 Franklin Street, Fifth Floor
 * Boston, MA  02110-1301  USA
 */
package hibernateTest.models;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import com.sun.org.apache.xerces.internal.util.SynchronizedSymbolTable;
import hibernateTest.entities.Event;
import hibernateTest.entities.Group;
import hibernateTest.entities.Request;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import junit.framework.TestCase;

/**
 * Illustrates use of Hibernate native APIs.
 *
 * @author Steve Ebersole
 */
public class NativeApiIllustrationTest {
	private SessionFactory sessionFactory;

	public void setUp() {
		// A SessionFactory is set up once for an application!
		final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
				.configure() // configures settings from hibernate.cfg.xml
				.build();
		try {
			sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
		}
		catch (Exception e) {
			// The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
			// so destroy it manually.
			StandardServiceRegistryBuilder.destroy( registry );
		}
	}

	public void tearDown() {
		try {
			if ( sessionFactory != null ) {
				sessionFactory.close();
			}
		} catch (Exception e) {
            System.out.println("Exception!");
		}
	}

	public void testBasicUsage() {
		int location = 001;//YOLPのコード。警告を減らすために使用。
		/*データの保存(データベースに投入)*/
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.save( new Event( "Our very first event!", new Date() ) );
		session.save( new Event( "A follow up event", new Date() ) );
		session.save( new Group("111", "http://test1", "family", "011" ) );
		session.save( new Group("222", "http://test2", "friend", "022" ) );
		Group newGroup = new Group("333", "http://test3", "school", "033" );
		session.save(newGroup); //インスタンスを引数に渡すこともできます
		session.save( new Request("001", "http://test01", "1999.01.01", "011", "cookie", "1999.04.10", location));
		session.save( new Request("002", "http://test02", "1999.02.02", "033", "milk", "1999.04.10", location));
		session.save( new Request("003", "http://test03", "1999.03.03", "033", "ice", "1999.04.10", location));
		session.getTransaction().commit();
		session.close();

		/*データ(レコード)の取得し削除。*/
		//注意: この例ではデータを取得する際、ID(主キー)を指定しているため、複数のデータが返されることを想定していません。
		session = sessionFactory.openSession();
		session.beginTransaction();
		//load()メソッドを用いて取得する方法。
		Request deleteRequest = (Request) session.load(Request.class, "002");
		//データの削除
		if(deleteRequest != null){
			session.delete(deleteRequest);
		}
		session.getTransaction().commit();
		session.close();

		/*データを取得し更新*/
		session = sessionFactory.openSession();
		session.beginTransaction();
//		//createCriteria()を用いて取得する方法。ただし非推奨。
//		//このメソッドはID以外にも、任意のカラムを指定することができます。(今回はproductが"ice"のものを取り出す)
//		//http://a4dosanddos.hatenablog.com/entry/2015/03/21/135421
//		Criteria criteria = session.createCriteria(Request.class).add(Restrictions.eq("product", "ice"));
//		Request editRequest = (Request) criteria.uniqueResult();
//		//データの更新
//		if(editRequest != null) {
//			editRequest.setProduct("Chocolate ice !!");
//			session.update(editRequest);
//		}

		//createCriteria()を用いない方法
		List requestList = session.createQuery( "from Request" ).list();
		for ( Request request : (List<Request>) requestList ) {
			if(request.getProduct() == "ice"){
				request.setProduct("Chocolate ice !!");
				session.update(request);
				break;
			}
		}

		session.getTransaction().commit();
		session.close();

		/*リレーション*/
		/*リクエストの追加*/
		session = sessionFactory.openSession();
		session.beginTransaction();
		Group editGroup = session.load(Group.class, "111");
		if(editGroup != null){
			//リクエストはsession.save()で保存する必要がありません。
			//後のテスト用に3つのリクエストを追加しています。
			Request aditionalrequest1 = new Request("004", "http://test04", "1999.01.01", "011", "Chocolate cookie", "1999.04.10", location);
			Request aditionalrequest2 = new Request("005", "http://test05", "1999.01.01", "011", "Banana cookie", "1999.04.10", location);
			Request aditionalrequest3 = new Request("006", "http://test06", "1999.01.01", "011", "Milk cookie", "1999.04.10", location);
			editGroup.addRequests(aditionalrequest1);
			editGroup.addRequests(aditionalrequest2);
			editGroup.addRequests(aditionalrequest3);
			session.update(editGroup);
		}
		session.getTransaction().commit();
		session.close();

		session = sessionFactory.openSession();
		session.beginTransaction();
		editGroup = session.load(Group.class, "222");
		if(editGroup != null){
			//リクエストはsession.save()で保存する必要がありません。
			Request aditionalrequest1 = new Request("007", "http://test07", "1999.01.01", "022", "Green Tee", "1999.04.10", location);
			Request aditionalrequest2 = new Request("008", "http://test08", "1999.01.01", "022", "Apple Tee", "1999.04.10", location);
			editGroup.addRequests(aditionalrequest1);
			editGroup.addRequests(aditionalrequest2);
			session.update(editGroup);
		}
		session.getTransaction().commit();
		session.close();

		/*リレーションを持ったリクエストの削除 (RIDを指定してリクエストを取得し、その後削除)*/
		session = sessionFactory.openSession();
		session.beginTransaction();
		deleteRequest = (Request) session.load(Request.class, "005");//Banana cookie
		//データの削除
		if(deleteRequest != null){
			session.delete(deleteRequest);
		}
		session.getTransaction().commit();
		session.close();


		/*全件取得と出力*/
		session = sessionFactory.openSession();
		session.beginTransaction();
		//queryStringには警告が出ます。
		List result = session.createQuery( "from Event" ).list();
		System.out.println("イベントテーブル");
		for ( Event event : (List<Event>) result ) {
			System.out.println( "Event (" + event.getDate() + ") : " + event.getTitle() );
		}
		List groupResult = session.createQuery( "from Group" ).list();
		System.out.println("グループテーブル");
		for ( Group group : (List<Group>) groupResult ) {
			System.out.println( "Group (" + group.getgId() + ") : " + group.getUri() + ": " + group.getName());
		}
		List requestResult = session.createQuery( "from Request" ).list();
		System.out.println("リクエストテーブル");
		for ( Request request : (List<Request>) requestResult ) {
			System.out.println( "Request (" + request.getrId() + ") : " + request.getUri() + ": " + request.getProduct());
		}

		/*リレーションを持たせた分の出力*/
		//Setは要素の順番に意味がないため、出力の順番はrId順ではありません。
		Group outGroup = session.load(Group.class, "111");
		List<Request> list = outGroup.getRequestsList();//Listとして取り出す。
		System.out.println("グループID111のリクエスト一覧");
		for ( Request request : (List<Request>) list ) {
			System.out.println( "rId: " + request.getrId() + " " + request.getUri() + " " + request.getProduct());
		}
		outGroup = session.load(Group.class, "222");
		Set<Request> set = outGroup.getRequests();//Setのまま取り出す。
		System.out.println("グループID222のリクエスト一覧");
		for ( Request request : (Set<Request>) set ) {
			System.out.println( "rId: " + request.getrId() + " " + request.getUri() + " " + request.getProduct());
		}

		session.getTransaction().commit();
		session.close();
	}
}