2015年2月12日 星期四

Spring Hibernate Hello World Example 專案 之 Annotation

Spring Hibernate Hello World Example 專案 之 Annotation



本範例實作說明:
本篇主要使用 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






















其它文章

沒有留言:

張貼留言

標籤

Oracle (150) Oracle DB (144) Oracle_DB (143) Oracle SQL (135) JAVA (84) css-基本類 (65) MySQL (59) CSS Selector (58) jQuery (49) JavaScript-基本類 (39) Spring Boot (38) JavaScript (37) JavaScript HTML DOM (37) JavaScript-HTML_DOM (36) CSS3 (30) JAVA-基本類 (28) jQuery UI (27) Apache (23) Oracle GROUP BY (20) datepicker (20) Android (18) Oracle Date (17) c (17) JAVA-lang套件 (16) Linux (16) Oracle Sub Query (16) Spring-基本類 (16) jQuery-基本類 (16) MySQL-進階系列教學 (15) Android基本類 (14) Grails (14) Oracle join (14) SQLite (13) Spring (13) WIN7-基本類 (13) grails-基本類 (13) linux cent os (13) CKEditor (12) JAVA-流程控制類 (12) JAVA_Spring (12) PHP (11) Spring MVC (11) MySQL-基本系列教學 (10) Notepad (10) Notepad++ (10) SQLite for java (10) Windows (10) c/c++ (10) eclipse (9) jQuery-Selector (9) sqldeveloper (9) DB_Toad (8) JAVA_IDE_Eclipse (8) JavaScript-String類 (8) MySQL DB Toad (8) MySQL-DATE相關 (8) MySQL-函式相關 (8) Spring Bean (8) Android Studio (7) HTML5 (7) Hibernate (7) JAVA-OCWCD (7) JavaScript-陣列類 (7) Docker (6) JAVA-程式分享 (6) JAVA.util套件 (6) JavaScript-數學類 (6) MinGw (6) MySQL-其它類 (6) Servlet (6) centos (6) Apache_Tomcat (5) Apache套件_POI (5) CSS (5) JavaScript-Date物件 (5) JavaScript-其它類 (5) PostgreSQL (5) httpd (5) log4j (5) 基本資訊 (5) 開發工具 (5) CSS Properties (4) Dev-C++ (4) IntelliJ IDEA (4) Oracle DDL (4) Sublime (4) TortoiseSVN (4) apache_Maven (4) Android NDK (3) Eclipse IDE for C/C++ (3) Hibernate-基本類 (3) JAVA-問題 (3) JAVA-綀習分享 (3) JVM (3) Linux 指令 (3) Proxy Server (3) Spring Mobile (3) Spring web (3) Squid (3) VirtualBox (3) maven (3) zk (3) 生活其它 (3) Bootstrap (2) Filter (2) JAVA_IO (2) JAVA_其它_itext套件 (2) JBoss-問題 (2) JSP (2) Jboss (2) Listener (2) MySQL-語法快速查詢 (2) Spring AOP (2) Spring Batch (2) Spring Boot Actuator (2) Spring i18n (2) Subversive (2) Tomcat 8 (2) UML (2) WebJars (2) WinMerge (2) c++ (2) c語言綀習題 (2) jQuery Mobile (2) jQuery-事件處理 (2) jQuery-套件類 (2) putty (2) svn (2) weblogic (2) Apache_JMeter (1) Apache套件_BeanUtils (1) Apache套件_StringUtils (1) Base64 (1) Google API (1) HTML5-基本類 (1) Heap (1) JAVA 7 (1) JAVA SE 、JAVA EE、JAVA ME (1) JAVA 日期 (1) JAVA-OCJP (1) JAVA-WEB (1) JAVA_IDE (1) JAVA其它 (1) JBoss Server (1) JDK (1) JMX (1) JRE (1) Java RMI (1) Java String (1) Joda Time (1) Linux_其它 (1) MySQL教學 (1) Oracle_VirtualBox (1) SQL Server (1) SWT (1) Session (1) Stack (1) Struts 2 (1) Tool (1) ZK Studio (1) csv (1) grails-其它類 (1) jQuery-進階 (1) java mail (1) java web (1) java8 (1) jsoup (1) mockmvc (1) modules (1) tomcat (1) win10 (1) 其它類 (1) 圖片工具 (1) 模擬器 (1) 讀書分享 (1) 開發資訊 (1)

精選文章

初學 Java 的 HelloWorld 程式

撰寫一個JAVA程式 public class HelloWorld{ public static void main(String[ ] args){ System.out.println("我第一支Java程式!!"); } } ...