[Jiemamy-notify] commit [2099] JDBCとJPAによるDBアクセスコードを書いてみた。

アーカイブの一覧に戻る

svnno****@sourc***** svnno****@sourc*****
2008年 11月 6日 (木) 21:19:07 JST


Revision: 2099
          http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=jiemamy&view=rev&rev=2099
Author:   daisuke_m
Date:     2008-11-06 21:19:06 +0900 (Thu, 06 Nov 2008)

Log Message:
-----------
JDBCとJPAによるDBアクセスコードを書いてみた。

Modified Paths:
--------------
    sandbox/openJPAsample/.classpath
    sandbox/openJPAsample/pom.xml

Added Paths:
-----------
    sandbox/openJPAsample/src/main/java/META-INF/
    sandbox/openJPAsample/src/main/java/META-INF/persistence.xml
    sandbox/openJPAsample/src/main/java/org/jiemamy/sandbox/openjpa/entity/
    sandbox/openJPAsample/src/main/java/org/jiemamy/sandbox/openjpa/entity/Department.java
    sandbox/openJPAsample/src/main/java/org/jiemamy/sandbox/openjpa/entity/Employee.java
    sandbox/openJPAsample/src/test/java/org/jiemamy/sandbox/openjpa/JdbcAccessTest.java
    sandbox/openJPAsample/src/test/java/org/jiemamy/sandbox/openjpa/JpaAccessTest.java
    sandbox/openJPAsample/src/test/resources/
    sandbox/openJPAsample/src/test/resources/database/
    sandbox/openJPAsample/src/test/resources/database/demo.sql
    sandbox/openJPAsample/src/test/resources/database/testdb.data.db
    sandbox/openJPAsample/src/test/resources/database/testdb.index.db

Removed Paths:
-------------
    sandbox/openJPAsample/src/main/java/org/jiemamy/sandbox/openjpa/App.java
    sandbox/openJPAsample/src/test/java/org/jiemamy/sandbox/openjpa/AppTest.java


-------------- next part --------------
Modified: sandbox/openJPAsample/.classpath
===================================================================
--- sandbox/openJPAsample/.classpath	2008-11-06 09:59:46 UTC (rev 2098)
+++ sandbox/openJPAsample/.classpath	2008-11-06 12:19:06 UTC (rev 2099)
@@ -1,7 +1,7 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <classpath>
-	<classpathentry including="**/*.java" kind="src" path="src/main/java"/>
-	<classpathentry including="**/*.java" kind="src" output="target/test-classes" path="src/test/java"/>
+	<classpathentry kind="src" path="src/main/java"/>
+	<classpathentry kind="src" output="target/test-classes" path="src/test/java"/>
 	<classpathentry kind="con" path="org.devzuz.q.maven.jdt.core.mavenClasspathContainer"/>
 	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
 	<classpathentry kind="output" path="target/classes"/>

Modified: sandbox/openJPAsample/pom.xml
===================================================================
--- sandbox/openJPAsample/pom.xml	2008-11-06 09:59:46 UTC (rev 2098)
+++ sandbox/openJPAsample/pom.xml	2008-11-06 12:19:06 UTC (rev 2099)
@@ -5,6 +5,18 @@
   <name>openJPAsample</name>
   <version>1.0-SNAPSHOT</version>
   <url>http://maven.apache.org</url>
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-compiler-plugin</artifactId>
+        <configuration>
+          <source>1.5</source>
+          <target>1.5</target>
+        </configuration>
+      </plugin>
+    </plugins>
+  </build>
   <dependencies>
     <dependency>
       <groupId>junit</groupId>
@@ -12,15 +24,15 @@
       <version>4.3.1</version>
       <scope>test</scope>
     </dependency>
+    <dependency>
+      <groupId>org.apache.openjpa</groupId>
+      <artifactId>openjpa-persistence-jdbc</artifactId>
+      <version>1.2.0</version>
+    </dependency>
     <dependency>
-      <groupId>org.apache.openjpa</groupId>
-      <artifactId>openjpa-kernel</artifactId>
-      <version>1.2.0</version>
-    </dependency>
-    <dependency>
       <groupId>com.h2database</groupId>
       <artifactId>h2</artifactId>
       <version>1.1.102</version>
     </dependency>
   </dependencies>
-</project>
\ No newline at end of file
+</project>

Added: sandbox/openJPAsample/src/main/java/META-INF/persistence.xml
===================================================================
--- sandbox/openJPAsample/src/main/java/META-INF/persistence.xml	                        (rev 0)
+++ sandbox/openJPAsample/src/main/java/META-INF/persistence.xml	2008-11-06 12:19:06 UTC (rev 2099)
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements.  See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership.  The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License.  You may obtain a copy of the License at
+ 
+ http://www.apache.org/licenses/LICENSE-2.0
+ 
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied.  See the License for the
+ specific language governing permissions and limitations
+ under the License.   
+-->
+<persistence xmlns="http://java.sun.com/xml/ns/persistence"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    version="1.0">
+
+    <persistence-unit name="jiemamy" transaction-type="RESOURCE_LOCAL">
+        <!-- We must enumerate each entity in the persistence unit -->
+        <class>org.jiemamy.sandbox.openjpa.entity.Employee</class>
+        <class>org.jiemamy.sandbox.openjpa.entity.Department</class>
+
+        <properties>
+            <property name="openjpa.ConnectionDriverName" value="org.h2.Driver"/>
+            <property name="openjpa.ConnectionURL" value="jdbc:h2:./src/test/resources/database/testdb"/>
+            <property name="openjpa.ConnectionUserName" value="sa"/>
+            <property name="openjpa.ConnectionPassword" value=""/>
+            <property name="openjpa.Log" value="DefaultLevel=WARN,SQL=TRACE" />
+            
+            <!-- 
+            <property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/>
+            <property name="openjpa.jdbc.DBDictionary" value="org.apache.openjpa.jdbc.sql.H2Dictionary"/>
+             -->
+        </properties>
+    </persistence-unit>
+
+</persistence>


Property changes on: sandbox/openJPAsample/src/main/java/META-INF/persistence.xml
___________________________________________________________________
Name: svn:mime-type
   + text/plain

Deleted: sandbox/openJPAsample/src/main/java/org/jiemamy/sandbox/openjpa/App.java
===================================================================
--- sandbox/openJPAsample/src/main/java/org/jiemamy/sandbox/openjpa/App.java	2008-11-06 09:59:46 UTC (rev 2098)
+++ sandbox/openJPAsample/src/main/java/org/jiemamy/sandbox/openjpa/App.java	2008-11-06 12:19:06 UTC (rev 2099)
@@ -1,19 +0,0 @@
-package org.jiemamy.sandbox.openjpa;
-
-
-/**
- * Hello world!
- */
-public class App {
-	
-	public static void main(String[] args) throws Exception {
-		new App().run();
-	}
-
-	/**
-	 * 
-	 */
-	private void run() throws Exception {
-		System.out.println("Hello World!");
-	}
-}

Added: sandbox/openJPAsample/src/main/java/org/jiemamy/sandbox/openjpa/entity/Department.java
===================================================================
--- sandbox/openJPAsample/src/main/java/org/jiemamy/sandbox/openjpa/entity/Department.java	                        (rev 0)
+++ sandbox/openJPAsample/src/main/java/org/jiemamy/sandbox/openjpa/entity/Department.java	2008-11-06 12:19:06 UTC (rev 2099)
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2007-2008 MIYAMOTO Daisuke, jiemamy.org and the Others.
+ * Created on 2008/11/06
+ *
+ * This file is part of Jiemamy.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language
+ * governing permissions and limitations under the License.
+ */
+package org.jiemamy.sandbox.openjpa.entity;
+
+import java.util.List;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+import javax.persistence.Table;
+import javax.persistence.Version;
+
+import org.apache.commons.lang.builder.ToStringBuilder;
+
+/**
+ * TODO for daisuke
+ * @author daisuke
+ */
+ @ Entity
+ @ Table(name = "DEPT")
+public class Department {
+	
+	@Id
+	public int id;
+	
+	@Column(name = "DEPT_NO")
+	public int deptNo;
+	
+	@Column(name = "DEPT_NAME")
+	public String deptName;
+	
+	@Column(name = "LOC")
+	public String loc;
+	
+	@Version
+	public int versionNo;
+	
+	@OneToMany(mappedBy = "dept")
+	public List<Employee> emps;
+	
+
+	@Override
+	public String toString() {
+		return ToStringBuilder.reflectionToString(this);
+	}
+	
+}


Property changes on: sandbox/openJPAsample/src/main/java/org/jiemamy/sandbox/openjpa/entity/Department.java
___________________________________________________________________
Name: svn:mime-type
   + text/plain

Added: sandbox/openJPAsample/src/main/java/org/jiemamy/sandbox/openjpa/entity/Employee.java
===================================================================
--- sandbox/openJPAsample/src/main/java/org/jiemamy/sandbox/openjpa/entity/Employee.java	                        (rev 0)
+++ sandbox/openJPAsample/src/main/java/org/jiemamy/sandbox/openjpa/entity/Employee.java	2008-11-06 12:19:06 UTC (rev 2099)
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2007-2008 MIYAMOTO Daisuke, jiemamy.org and the Others.
+ * Created on 2008/11/06
+ *
+ * This file is part of Jiemamy.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language
+ * governing permissions and limitations under the License.
+ */
+package org.jiemamy.sandbox.openjpa.entity;
+
+import java.sql.Date;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.Table;
+import javax.persistence.Temporal;
+import javax.persistence.TemporalType;
+import javax.persistence.Version;
+
+import org.apache.commons.lang.builder.ToStringBuilder;
+
+/**
+ * TODO for daisuke
+ * @author daisuke
+ */
+ @ Entity
+ @ Table(name = "Emp")
+public class Employee {
+	
+	@Id
+	@GeneratedValue(strategy = GenerationType.IDENTITY)
+	public int id;
+	
+	@Column(name = "EMP_NO")
+	public int empNo;
+	
+	@Column(name = "EMP_NAME")
+	public String empName;
+	
+	@Column(name = "MGR_ID")
+	public int mgrId;
+	
+	@Temporal(TemporalType.DATE)
+	public Date hireDate;
+	
+	public double sal;
+	
+	@Column(name = "DEPT_ID")
+	public int deptId;
+	
+	@Version
+	public int versionNo;
+	
+	@ManyToOne
+	@JoinColumn(name = "DEPT_ID")
+	public Department dept;
+	
+
+	@Override
+	public String toString() {
+		return ToStringBuilder.reflectionToString(this);
+	}
+}


Property changes on: sandbox/openJPAsample/src/main/java/org/jiemamy/sandbox/openjpa/entity/Employee.java
___________________________________________________________________
Name: svn:mime-type
   + text/plain

Deleted: sandbox/openJPAsample/src/test/java/org/jiemamy/sandbox/openjpa/AppTest.java
===================================================================
--- sandbox/openJPAsample/src/test/java/org/jiemamy/sandbox/openjpa/AppTest.java	2008-11-06 09:59:46 UTC (rev 2098)
+++ sandbox/openJPAsample/src/test/java/org/jiemamy/sandbox/openjpa/AppTest.java	2008-11-06 12:19:06 UTC (rev 2099)
@@ -1,34 +0,0 @@
-package org.jiemamy.sandbox.openjpa;
-
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestSuite;
-
-/**
- * Unit test for simple App.
- */
-public class AppTest extends TestCase {
-	
-	/**
-	 * Create the test case
-	 *
-	 * @param testName name of the test case
-	 */
-	public AppTest(String testName) {
-		super(testName);
-	}
-	
-	/**
-	 * @return the suite of tests being tested
-	 */
-	public static Test suite() {
-		return new TestSuite(AppTest.class);
-	}
-	
-	/**
-	 * Rigourous Test :-)
-	 */
-	public void testApp() {
-		assertTrue(true);
-	}
-}

Copied: sandbox/openJPAsample/src/test/java/org/jiemamy/sandbox/openjpa/JdbcAccessTest.java (from rev 2097, sandbox/openJPAsample/src/main/java/org/jiemamy/sandbox/openjpa/App.java)
===================================================================
--- sandbox/openJPAsample/src/test/java/org/jiemamy/sandbox/openjpa/JdbcAccessTest.java	                        (rev 0)
+++ sandbox/openJPAsample/src/test/java/org/jiemamy/sandbox/openjpa/JdbcAccessTest.java	2008-11-06 12:19:06 UTC (rev 2099)
@@ -0,0 +1,61 @@
+package org.jiemamy.sandbox.openjpa;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.Statement;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * Hello world!
+ */
+public class JdbcAccessTest {
+	
+	/**
+	 * @throws java.lang.Exception
+	 */
+	@Before
+	public void setUp() throws Exception {
+	}
+	
+	/**
+	 * @throws java.lang.Exception
+	 */
+	@After
+	public void tearDown() throws Exception {
+	}
+	
+	/**
+	 * test
+	 * @throws Exception
+	 */
+	@Test
+	public void test01_jdbcAccess() throws Exception {
+		Class.forName("org.h2.Driver");
+		Connection conn = null;
+		Statement stmt = null;
+		ResultSet rs = null;
+		
+		try {
+			conn = DriverManager.getConnection("jdbc:h2:./src/test/resources/database/testdb", "sa", "");
+			stmt = conn.createStatement();
+			rs = stmt.executeQuery("SELECT A.*, B.* FROM EMP A INNER JOIN DEPT B WHERE A.DEPT_ID = B.ID;");
+			while (rs.next()) {
+				System.out.printf("%s %s\n", rs.getString("EMP_NAME"), rs.getString("DEPT_NAME"));
+			}
+		} finally {
+			if (rs != null) {
+				rs.close();
+			}
+			if (stmt != null) {
+				stmt.close();
+			}
+			if (conn != null) {
+				conn.close();
+			}
+		}
+	}
+}


Property changes on: sandbox/openJPAsample/src/test/java/org/jiemamy/sandbox/openjpa/JdbcAccessTest.java
___________________________________________________________________
Name: svn:mime-type
   + text/plain

Added: sandbox/openJPAsample/src/test/java/org/jiemamy/sandbox/openjpa/JpaAccessTest.java
===================================================================
--- sandbox/openJPAsample/src/test/java/org/jiemamy/sandbox/openjpa/JpaAccessTest.java	                        (rev 0)
+++ sandbox/openJPAsample/src/test/java/org/jiemamy/sandbox/openjpa/JpaAccessTest.java	2008-11-06 12:19:06 UTC (rev 2099)
@@ -0,0 +1,72 @@
+package org.jiemamy.sandbox.openjpa;
+
+import java.util.List;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.EntityTransaction;
+import javax.persistence.Persistence;
+import javax.persistence.Query;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import org.jiemamy.sandbox.openjpa.entity.Employee;
+
+/**
+ * Hello world!
+ */
+public class JpaAccessTest {
+	
+	/**
+	 * @throws java.lang.Exception
+	 */
+	@Before
+	public void setUp() throws Exception {
+	}
+	
+	/**
+	 * @throws java.lang.Exception
+	 */
+	@After
+	public void tearDown() throws Exception {
+	}
+	
+	/**
+	 * test
+	 * @throws Exception
+	 */
+	@Test
+	@SuppressWarnings("unchecked")
+	public void test01_jpaAccess() throws Exception {
+		EntityManager em = null;
+		EntityTransaction tx = null;
+		EntityManagerFactory factory = null;
+		
+		try {
+			factory = Persistence.createEntityManagerFactory("jiemamy");
+			em = factory.createEntityManager();
+			
+			tx = em.getTransaction();
+			tx.begin();
+			
+			Query query = em.createQuery("select e from Employee e, Department d where e.deptId = d.id");
+			List<Employee> results = query.getResultList();
+			
+			for (Employee emp : results) {
+				System.out.printf("%s %s\n", emp.empName, emp.dept.deptName);
+			}
+		} finally {
+			if (tx != null) {
+				tx.rollback();
+			}
+			if (em != null) {
+				em.close();
+			}
+			if (factory != null) {
+				factory.close();
+			}
+		}
+	}
+}


Property changes on: sandbox/openJPAsample/src/test/java/org/jiemamy/sandbox/openjpa/JpaAccessTest.java
___________________________________________________________________
Name: svn:mime-type
   + text/plain

Added: sandbox/openJPAsample/src/test/resources/database/demo.sql
===================================================================
--- sandbox/openJPAsample/src/test/resources/database/demo.sql	                        (rev 0)
+++ sandbox/openJPAsample/src/test/resources/database/demo.sql	2008-11-06 12:19:06 UTC (rev 2099)
@@ -0,0 +1,39 @@
+CREATE TABLE DEPT(
+	ID IDENTITY NOT NULL PRIMARY KEY,
+	DEPT_NO INTEGER NOT NULL,
+	DEPT_NAME VARCHAR(20),
+	LOC VARCHAR(20),
+	VERSION_NO INTEGER
+);
+
+CREATE TABLE EMP(
+	ID IDENTITY NOT NULL PRIMARY KEY,
+	EMP_NO INTEGER NOT NULL,
+	EMP_NAME VARCHAR(20),
+	MGR_ID INTEGER,
+	HIREDATE DATE,
+	SAL NUMERIC(7,2),
+	DEPT_ID INTEGER,
+	VERSION_NO INTEGER
+);
+
+INSERT INTO DEPT VALUES(1,10,'ACCOUNTING','NEW YORK',1);
+INSERT INTO DEPT VALUES(2,20,'RESEARCH','DALLAS',1);
+INSERT INTO DEPT VALUES(3,30,'SALES','CHICAGO',1);
+INSERT INTO DEPT VALUES(4,40,'OPERATIONS','BOSTON',1);
+
+INSERT INTO EMP VALUES(1,7369,'SMITH',13,'1980-12-17',800,2,1);
+INSERT INTO EMP VALUES(2,7499,'ALLEN',6,'1981-02-20',1600,3,1);
+INSERT INTO EMP VALUES(3,7521,'WARD',6,'1981-02-22',1250,3,1);
+INSERT INTO EMP VALUES(4,7566,'JONES',9,'1981-04-02',2975,2,1);
+INSERT INTO EMP VALUES(5,7654,'MARTIN',6,'1981-09-28',1250,3,1);
+INSERT INTO EMP VALUES(6,7698,'BLAKE',9,'1981-05-01',2850,3,1);
+INSERT INTO EMP VALUES(7,7782,'CLARK',9,'1981-06-09',2450,1,1);
+INSERT INTO EMP VALUES(8,7788,'SCOTT',4,'1982-12-09',3000.0,2,1);
+INSERT INTO EMP VALUES(9,7839,'KING',NULL,'1981-11-17',5000,1,1);
+INSERT INTO EMP VALUES(10,7844,'TURNER',6,'1981-09-08',1500,3,1);
+INSERT INTO EMP VALUES(11,7876,'ADAMS',8,'1983-01-12',1100,2,1);
+INSERT INTO EMP VALUES(12,7900,'JAMES',6,'1981-12-03',950,3,1);
+INSERT INTO EMP VALUES(13,7902,'FORD',4,'1981-12-03',3000,2,1);
+INSERT INTO EMP VALUES(14,7934,'MILLER',7,'1982-01-23',1300,1,1);
+

Added: sandbox/openJPAsample/src/test/resources/database/testdb.data.db
===================================================================
(Binary files differ)


Property changes on: sandbox/openJPAsample/src/test/resources/database/testdb.data.db
___________________________________________________________________
Name: svn:mime-type
   + application/octet-stream

Added: sandbox/openJPAsample/src/test/resources/database/testdb.index.db
===================================================================
(Binary files differ)


Property changes on: sandbox/openJPAsample/src/test/resources/database/testdb.index.db
___________________________________________________________________
Name: svn:mime-type
   + application/octet-stream


Jiemamy-notify メーリングリストの案内
アーカイブの一覧に戻る