diff --git a/src/main/java/com/example/cosmos_serversb/models/Groups.java b/src/main/java/com/example/cosmos_serversb/models/Groups.java index 9c4e589..8ad43dc 100644 --- a/src/main/java/com/example/cosmos_serversb/models/Groups.java +++ b/src/main/java/com/example/cosmos_serversb/models/Groups.java @@ -4,13 +4,44 @@ import javax.inject.Singleton; import com.example.cosmos_serversb.entities.*; - +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; @Singleton public class Groups { private static Groups theInstance = null; private static ArrayList groups = new ArrayList<>(); + private static SessionFactory sessionFactory; + + public static 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 static void tearDown() { + try { + if ( sessionFactory != null ) { + sessionFactory.close(); + } + } catch (Exception e) { + System.out.println("Exception!"); + } + } + private Groups(){ } @@ -29,18 +60,37 @@ public static Group createGroup(String name, String uId){ //先にGidとuriの発行を行う Group testGroup = new Group("123456789", "http://test.com", name, uId); - groups.add(testGroup); + Session session = sessionFactory.openSession(); + session.beginTransaction(); + session.save(testGroup); + session.getTransaction().commit(); + session.close(); + + Session output = sessionFactory.openSession(); + output.beginTransaction(); + //hibernateテスト用出力 + List groupResult = output.createQuery( "from Group" ).list(); + for ( Group group : (List) groupResult ) { + System.out.println( "Group (" + group.getgId() + ") : " + group.getUri() + ": " + group.getName()); + } + output.getTransaction().commit(); + output.close(); return testGroup; } public static Group getGroupByGid(String gId){ Group editGroup; - for (int i = 0; i < groups.size(); i++) { - editGroup = groups.get(i); + Session session = sessionFactory.openSession(); + session.beginTransaction(); + List groupResult = session.createQuery( "from Group" ).list(); + for ( Group group : (List) groupResult ) { + editGroup = group; if (editGroup.getgId().equals(gId)) { return editGroup; } } + session.getTransaction().commit(); + session.close(); return null; }