まえがき
STS3のMavenプロジェクト使って、Hibernate4.3経由でMySQLのテーブルデータを表示したいと思います。
手順は下記の通りとなります。
表示するデータは、前回のブログで作成したテーブルを使用します。
データを作成していない方は下記リンクを参考にして下さいね! pom2019.hatenablog.com
Mavenプロジェクトの作成
- STS3を立ち上げ、「ファイル>Mavenプロジェクト」をクリックします。
- 次へをクリックします。
- カタログから「すべてのカタログ」を選択、アーティファクトIdが「maven-archetype-archetype」を選択し、次へをクリックします。
- グループIdとアーティファクトIdを入力し、完了をクリックします。
- Mavenプロジェクトが作成されました。 ※プロジェクト作成後、ビルドパスを変更しました。ビルドパスの変更については、下記ページに書いているのでよかったら参考にして下さい。 https://pom2019.hatenablog.com/entry/20190525/145359pom2019.hatenablog.com
必要ファイルの作成
- pom.xmlにHibernate 4.3とMySQL Connector/J 8.0のdependencyを追加し、Mavenを更新します。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.pom2019</groupId> <artifactId>HibernateTest</artifactId> <version>0.0.1-SNAPSHOT</version> <name>Archetype - HibernateTest</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.0.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.16</version> </dependency> </dependencies> </project>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://127.0.0.1:3306/TESTDB?useUnicode=true&characterEncoding=UTF-8</property> <property name="connection.username">test</property> <property name="connection.password">****</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> </session-factory> </hibernate-configuration>
※パスワードは「****」としていますが、それぞれの環境のパスワードを入力して下さい。
- メイン文を含むクラスを作成します。
package com.pom2019; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; public class App { public static void main(String[] args) { // configures settings from hibernate.cfg.xml Configuration configuration = new Configuration().configure(); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()); SessionFactory sf = configuration.buildSessionFactory(builder.build()); Session ss = sf.openSession(); @SuppressWarnings("unchecked") List<Object[]> result = ss.createSQLQuery("SELECT * FROM HouseholdAppliances").list(); for (Object[] r : result) { for (Object o : r) { System.out.print(o + "\t"); } System.out.println(); } if (sf != null) { sf.close(); } } }
実行結果
6 22, 2019 2:59:55 午後 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit> INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final} 6 22, 2019 2:59:55 午後 org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {4.3.0.Final} 6 22, 2019 2:59:55 午後 org.hibernate.cfg.Environment <clinit> INFO: HHH000206: hibernate.properties not found 6 22, 2019 2:59:55 午後 org.hibernate.cfg.Environment buildBytecodeProvider INFO: HHH000021: Bytecode provider name : javassist 6 22, 2019 2:59:55 午後 org.hibernate.cfg.Configuration configure INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml 6 22, 2019 2:59:55 午後 org.hibernate.cfg.Configuration getConfigurationInputStream INFO: HHH000040: Configuration resource: /hibernate.cfg.xml 6 22, 2019 2:59:55 午後 org.hibernate.cfg.Configuration doConfigure INFO: HHH000041: Configured SessionFactory: null 6 22, 2019 2:59:55 午後 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!) 6 22, 2019 2:59:55 午後 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://127.0.0.1:3306/TESTDB?useUnicode=true&characterEncoding=UTF-8] 6 22, 2019 2:59:55 午後 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH000046: Connection properties: {user=test, password=****} 6 22, 2019 2:59:55 午後 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH000006: Autocommit mode: false 6 22, 2019 2:59:55 午後 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure INFO: HHH000115: Hibernate connection pool size: 1 (min=1) 6 22, 2019 2:59:56 午後 org.hibernate.dialect.Dialect <init> INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect 6 22, 2019 2:59:56 午後 org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService INFO: HHH000399: Using default transaction strategy (direct JDBC transactions) 6 22, 2019 2:59:56 午後 org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init> INFO: HHH000397: Using ASTQueryTranslatorFactory 6 22, 2019 2:59:56 午後 org.hibernate.tool.hbm2ddl.SchemaExport execute INFO: HHH000227: Running hbm2ddl schema export 6 22, 2019 2:59:56 午後 org.hibernate.tool.hbm2ddl.SchemaExport execute INFO: HHH000230: Schema export complete Hibernate: SELECT * FROM HouseholdAppliances 1 冷蔵庫 2008-12-01 2 電子レンジ 2015-08-01 3 オーブントースター 2015-08-01 4 クーラー 2011-06-01 5 洗濯機 2012-04-01
あとがき
家電テーブルの内容が無事表示されました!
ここでは、SQLを直接実行する(ss.createSQLQuery)ことでデータを表示させていますが、エンティティを設定をすれば、HQLで実行させる(ss.createQuery)ことができます。
HQLとはHibernate Query Languageの略で、SQLをオブジェクト指向風にラッピングした言語のことです。
今回、MySQLのバージョンになぜ8.0.16を使用したかについては、下記リンクに書いているのでよかったら参考にして下さいね! pom2019.hatenablog.com
最後までお読み頂きありがとうございました。