本範例實作說明:
本篇主要使用 Spring 及 Hibernate,做一個基本測試專案,
Spring 使用 Spring Annotation bean。
Hibernate 使用 Annotation 。
本範例使用到 PostgreSQL 及 log4j
一、範例開發準備工具
作業系統: Windows 7
開發工具: Eclipse Java EE IDE for Web Developers Juno Service Release2
JAVA JDK : JDK1.7.0_60
資料庫 : PostgreSQL 9.3
其它相關: Maven 4.0
Hibernate Version 4.3.7.Final
Spring Framework 3.2.2.RELEASE
二、新增Maven範例專案
範例專案名稱:SpringHibernateAnnotationHelloWorldExample
圖1 開啟Eclipse -> File -> New -> Maven Project
(如果沒看到Maven Project ,Eclipse -> File -> New -> Other.. ->)
圖2 選擇專案存放位置 use default Workspase location-> Next
選擇存放在預設的工作資料夾下(就是你開Eclipse時,選擇Workspase下)
圖3 使用 Maven 範本
本例選用:
Group id : org.apache.maven.archetypes
Artifact id : maven-archetype-quickstart
Version : RELEASE
-> Next
註:
Group id 為公司名稱 or 群組分類名稱
Artifact Id 為專案標識符,就是專案名稱
圖4 範例專案
Group id : SpringHibernateAnnotationHelloWorldExample
Artifact id : SpringHibernateAnnotationHelloWorldExample
Version : 0.0.1-SNAPSHOT
Package : com.levin
-> Finish
圖5 新增專案後,基本預設資料
三、使用相關jar檔
主要:
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>3.2.2.RELEASE</spring.version> <hibernate.version>4.3.7.Final</hibernate.version> <jdk.version>1.7</jdk.version> <junit.version>4.11</junit.version> </properties> <dependencies> <!-- Spring 3 dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <!-- Hibernate framework --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <!-- postgresql database driver --> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>9.3-1100-jdbc41</version> </dependency> <!-- Junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> </dependencies>
圖6 開啟 pom.xml
pom.xml內容:
<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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>SpringHibernateAnnotationHelloWorldExample</groupId> <artifactId>SpringHibernateAnnotationHelloWorldExample</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>SpringHibernateAnnotationHelloWorldExample</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>3.2.2.RELEASE</spring.version> <hibernate.version>4.3.7.Final</hibernate.version> <jdk.version>1.7</jdk.version> <junit.version>4.11</junit.version> </properties> <dependencies> <!-- Spring 3 dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <!-- Hibernate framework --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <!-- postgresql database driver --> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>9.3-1100-jdbc41</version> </dependency> <!-- Junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>SpringHibernateAnnotationHelloWorldExample</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-eclipse-plugin</artifactId> <version>2.9</version> <configuration> <downloadSources>true</downloadSources> <downloadJavadocs>false</downloadJavadocs> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.0</version> <configuration> <source>${jdk.version}</source> <target>${jdk.version}</target> </configuration> </plugin> </plugins> </build> </project>
四、相關resources
建立resources 路徑
src/main/resources
圖7 建立相關 resources
將 resources 加入到 source folders on build path。
在專案按右鍵 -> Properties
進入Properties介面 -> Java Build Path
-> Source -> Add Folder..
->進入 Source Folder Selection介面
-> 選擇 打勾 resources
-> OK -> OK
圖8 建立設定檔
hibernate.cfg.xml
log4j.properties
五、建立 hibernate.cfg.xml
路徑: src/main/resources
檔名:hibernate.cfg.xml
說明:資料庫設定檔,相關hibernate 主要設定,資料庫連線資訊等。
本例資料庫名稱:hibernateTest
hibernate.cfg.xml內容:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!--使用資料庫 相關設定 --> <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property> <property name="hibernate.connection.driver_class">org.postgresql.Driver</property> <!--連線資料 (url)、帳號(username)及密碼(password) --> <property name="hibernate.connection.url">jdbc:postgresql://127.0.0.1:5433/hibernateTest</property> <property name="hibernate.connection.username">postgres</property> <property name="hibernate.connection.password">postgres</property> <!-- hibernate 相關效能設定 --> <property name="hibernate.bytecode.use_reflection_optimizer">false</property> <property name="connection_pool_size">1</property> <!-- validate | update | create | create-drop 如果沒要用 set value="none". --> <!-- validate 程式執行驗證資料對應表相關資料。 update 如果table已存在,就更新,不存在則新增 create 每次執行就自動刪除所有對應的table,再新增所有對應的table create-drop 新增所有對應的table , 程式關閉前刪除所有對應的table --> <property name="hbm2ddl.auto">create</property> <!-- 是否顯示所有執行的sql --> <property name="show_sql">true</property> <!-- 對應資料表 --> <mapping class="com.levin.model.Message"></mapping> </session-factory> </hibernate-configuration>
六、建立 log4j.properties
路徑: src/main/resources
檔名:log4j.properties
說明:log4j 設定檔 ,記錄資訊用的,可不建此檔。
log4j.properties內容:
# Root logger option log4j.rootLogger=INFO, stdout # Direct log messages to stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n # Hibernate logging options (INFO only shows startup messages) log4j.logger.org.hibernate=INFO # Log JDBC bind parameter runtime arguments log4j.logger.org.hibernate.type=trace
七、建立 Message.java
路徑: src/main/java/com/levin/model
檔名:Message.java
說明:資料模型,裝table資料及存取資料。
圖9
Message.java 程式內容:
package com.levin.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; /** * Model class for Message.java */ @Entity @Table(name = "MESSAGE") public class Message implements java.io.Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue @Column(name = "MESSAGE_ID") private Integer messageId; @Column(name = "MESSAGE_CODE") private String messageCode; @Column(name = "MESSAGE_NAME") private String messageName; public Message() { } public Message(String messageCode, String messageName) { this.messageCode = messageCode; this.messageName = messageName; } public Integer getMessageId() { return messageId; } public void setMessageId(Integer messageId) { this.messageId = messageId; } public String getMessageCode() { return messageCode; } public void setMessageCode(String messageCode) { this.messageCode = messageCode; } public String getMessageName() { return messageName; } public void setMessageName(String messageName) { this.messageName = messageName; } }
八、建立service 程式
1、路徑: src/main/java/com/levin/service
圖10 IMessageService.java 及 MessageService.java
2、建立 Service Interface
路徑: src/main/java/com/levin/service
名稱:IMessageService.java
IMessageService.java 程式內容:
package com.levin.service; public interface IMessageService { public void insertMessage(String code,String name); }
3、建立 Service 實作
路徑: src/main/java/com/levin/service/impl
名稱:MessageService.java
MessageService.java 程式內容:
package com.levin.service.impl; import org.hibernate.Session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.levin.model.Message; import com.levin.service.IMessageService; import com.levin.util.HibernateUtil; @Component public class MessageService implements IMessageService { @Autowired private Message message; public void insertMessage(String code, String name) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); message.setMessageCode(code); message.setMessageName(name); session.save(message); session.getTransaction().commit(); } }
注意:
@Component Spring 元件宣告
@Autowired 自動生成初值宣告
九、建立 Hibernate 資料交易控管 SessionFactory
路徑: src/main/java/com/levin/util
名稱:HibernateUtil.java
圖11
HibernateUtil.java 程式內容:
package com.levin.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new AnnotationConfiguration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static void shutdown() { // Close caches and connection pools getSessionFactory().close(); } }
十、建立主執行程式
路徑: src/main/java/com/levin/core
名稱:Application.java
圖12
Application.java 程式內容:
package com.levin.core; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import com.levin.model.Message; import com.levin.service.IMessageService; import com.levin.service.impl.MessageService; /** * Hibernate Hello world! */ @Configuration @ComponentScan("com.levin.service.impl") public class Application { @Bean Message mockMessage() { return new Message(); } public static void main(String[] args) { System.out.println("Maven + Srping + Hibernate + PostgreSQL Hello World! "); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Application.class); IMessageService messageService = context.getBean(MessageService.class); messageService.insertMessage("1546", "Hello World"); } }
注意:
@ComponentScan("com.levin") 為Spring 元件掃描宣告
com.levin 是指定package 以下掃描元件。
@Bean 為Spring Bean宣告
十一、執行測試
圖13 在專案按右鍵 -> Run As -> Java Application
圖14 Console 執行結果
圖15 資料庫檢查
十二、其它參考
Struts + Spring + Hibernate 目錄
Spring Hello World Example 專案
Hibernate Hello World Example 專案 之 XML Mapping
Spring Hibernate Hello World Example 專案 之 XML Mapping
其它文章
沒有留言:
張貼留言