Users  

   

Hobi  

   

Statistik  

Visitors
215
Articles
59
Articles View Hits
384909
   

User Online  

We have 36 guests and no members online

   

Contoh Penggunaan Framework Java Spring Hibernate

Details

Seperti biasa, masih mengenai java, tutorial kali ini tentang framework di java, spring dan hibernate.

Disini saya akan membagikan sedikit contoh penerapan keduanya. Disini saya memang bukan master spring maupun hibernate, namun contoh ini merupakan dasar apabila anda ingin menggunakan keduanya. Jadi tinggal anda kembangkan saja dari dasar contoh ini.

Penerapan pada contoh ini adalah memasukan data ke dalam database yg memakai MySQL server dan memakai swing untuk memasukannya. Saya menggunakan IDE NetBeans 6.7.1 untuk membuatnya. Karena kata sebagian para ahli java, IDE ini yang paling gampang digunakan untuk para pemula, karena penggunaannya yang relatif simple.

Kumpulkan semua library yang akan digunakan (tentu saja, hehe..). Untuk connect ke database MySQL saya menggunakan mysql-connector-java-5.0.6-bin.jar. Dan pada project tambahkan library Hibernate dan Spring.

Tidak panjang lebar, langsung ke code-nya saja..

 

Buat file ApplicationContextProvider.java karena memakai Spring

 

01 package com.contoh.provider;
02 import org.springframework.context.ApplicationContext;
03 import org.springframework.context.support.ClassPathXmlApplicationContext;
04 public class ApplicationContextProvider {
05      private ApplicationContext applicationContext;
06      private static ApplicationContextProvider provider;
07      private ApplicationContextProvider() throws ExceptionInInitializerError {
08           try {
09                this.applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
10           } catch (Throwable ex) {
11                System.err.println("Initial ApplicationContext creation failed -- " + ex);
12                throw new ExceptionInInitializerError(ex);
13           }
14      }
15      public synchronized static ApplicationContextProvider getInstance() throws ExceptionInInitializerError {
16      ApplicationContextProvider tempProvider = null;
17      if (provider == null) {
18           provider = new ApplicationContextProvider();
19           tempProvider = provider;
20      } else if (provider.getApplicationContext() == null) {
21           provider = new ApplicationContextProvider();
22           tempProvider = provider;
23      } else {
24           tempProvider = provider;
25      }
26      return tempProvider;
27 }
28 /* getter - setter.. */

 

Buat class model Peminjam.java dan Peminjaman.java ini juga disebut pojo. Class ini digunakan untuk memodelkan rancangan tabel di database. Karena menggunakan Hibernate, kita tidak perlu membuat tabel di database dan relasinya, kita bisa membuatnya melalui class dengan memakai anotasi (@). Di MySQL cukup dengan membuat database kosong saja dengan nama contoh_db misalnya yang saya gunakan disini.

 

01 package com.contoh.model;
02 import java.io.Serializable;
03 import javax.persistence.Column;
04 import javax.persistence.Entity;
05 import javax.persistence.Id;
06 import javax.persistence.Table;
07  
08 @Entity
09 @Table(name = "peminjam")
10 public class Peminjam implements Serializable {
11      @Id
12      @Column(name = "idpeminjam", length = 3, nullable = false, unique = true)
13      private String idPeminjam;
14      @Column(name = "nama", length = 20, nullable = false)
15      private String nama;
16      @Column(name = "alamat", length = 30, nullable = false)
17      private String alamat;
18      @Column(name = "telepon", length = 20, nullable = false)
19      private String telepon;
20      /*constructor - getter - setter*/

 

01 package com.contoh.model;
02 import java.io.Serializable;
03 import java.sql.Date;
04 import javax.persistence.Column;
05 import javax.persistence.Entity;
06 import javax.persistence.Id;
07 import javax.persistence.JoinColumn;
08 import javax.persistence.ManyToOne;
09 import javax.persistence.Table;
10  
11 @Entity
12 @Table(name = "Peminjaman")
13 public class Peminjaman implements Serializable {
14  
15     @Id
16     @Column(name = "kodepeminjaman", length = 5, nullable = false, unique = true)
17     private String kodePeminjaman;
18     @ManyToOne
19     @JoinColumn(name = "idpeminjam", nullable = false)
20     private Peminjam idPeminjam;
21     @Column(name = "tgl_pjm")
22     private Date tglPinjam;

 

Buat class interface DAO.. dari kedua class model diatas..

 

1 package com.contoh.dao.iface;
2 import com.contoh.model.Peminjam;
3 import org.springframework.dao.DataAccessException;
4 public interface PeminjamDAOInterface {
5      public void insert(Peminjam peminjam) throws DataAccessException;
6 }

 

1 package com.contoh.dao.iface;
2 public interface PeminjamanDAOInterface {
3      public void insert(Peminjaman peminjaman) throws DataAccessException;
4 }

 

Buat class DAO yang mengimplementasi interface DAO diatas..

 

01 package com.contoh.dao.impl;
02 import com.contoh.dao.iface.PeminjamDAOInterface;
03 import com.contoh.model.Peminjam;
04 import org.hibernate.SessionFactory;
05 import org.springframework.beans.factory.annotation.Autowired;
06 import org.springframework.dao.DataAccessException;
07 import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
08  
09 public class PeminjamDAO extends HibernateDaoSupport implements PeminjamDAOInterface {
10  
11      @Autowired
12      public void setSuperSessionFactory(SessionFactory sessionFactory) {
13           super.setSessionFactory(sessionFactory);
14      }
15  
16      public void insert(Peminjam peminjam) throws DataAccessException {
17           getHibernateTemplate().save(peminjam);
18      }
19 }

 

01 @Repository
02 public class PeminjamanDAO extends HibernateDaoSupport implements PeminjamanDAOInterface {
03  
04      @Autowired
05      public void setSuperSessionFactory(SessionFactory sessionFactory) {
06           super.setSessionFactory(sessionFactory);
07      }
08  
09      public void insert(Peminjaman peminjaman) throws DataAccessException {
10           getHibernateTemplate().save(peminjaman);
11      }
12 }

 

Bikin file xml dengan nama applicationContext.xml

 

11 <context:component-scan base-package="com.contoh.dao.impl"/>
12 <tx:annotation-driven transaction-manager="transactionManager"/>
13      <bean id="propertyConfigurer"
14           class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
15           p:location="classpath:jdbc.properties"/>
16      <bean id="dataSource"
17           class="org.springframework.jdbc.datasource.DriverManagerDataSource"
18           p:driverClassName="${jdbc.driver}"
19           p:url="${jdbc.url}"
20           p:username="${jdbc.username}"
21           p:password="${jdbc.password}"/>
22      <bean id="sessionFactory"  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
23           <property name="dataSource" ref="dataSource"/>
24           <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
25      </bean>
26      <bean id="transactionManager"
27           class="org.springframework.orm.hibernate3.HibernateTransactionManager"
28           p:sessionFactory-ref="sessionFactory"/>
29      <bean id="peminjamDAO"
30           class="com.contoh.dao.impl.PeminjamDAO"
31           p:sessionFactory-ref="sessionFactory" />
32      <bean id="peminjamanDAO"
33           class="com.contoh.dao.impl.PeminjamanDAO"
34           p:sessionFactory-ref="sessionFactory" />
35 </beans>

 

Bikin file xml untuk konfigurasi hibernate dengan nama hibernate.cfg.xml

 

01 <?xml version="1.0" encoding="UTF-8"?>
02 <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
04 <hibernate-configuration>
05      <session-factory>
06           <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
07           <property name="hibernate.hbm2ddl.auto">update</property>
08           <mapping class="com.contoh.model.Peminjam"/>
09           <mapping class="com.contoh.model.Peminjaman"/>
10      </session-factory>
11 </hibernate-configuration>

 

Buat file properties dengan nama jdbc.properties

 

1 jdbc.driver=com.mysql.jdbc.Driver
2 jdbc.url=jdbc:mysql://localhost:3306/contoh_db
3 jdbc.username=root --> tergantung username di MySQL anda
4 jdbc.password=admin --> tergantung password yg anda gunakan

 

Ketiga file diatas saya letakkan di default package, jika anda akan meletakkannya di package lain, jangan ubah settingan di file-file xml-nya..

 

Buat GUI dengan swing dengan tampilan seperti dibawah ini..untuk mencoba memasukkan data ke dalam database contoh_db

 

 

kemudian isikan code berikut pada button insertPeminjamButtonActionPerformed

 

01 if (JOptionPane.showConfirmDialog(this, "Yakin simpan data?", "KONFIRMASI", JOptionPane.YES_NO_OPTION) == 0) {
02      try {
03           Peminjam peminjam = new Peminjam();
04           peminjam.setIdPeminjam(idPeminjamTextField.getText());
05           peminjam.setNama(namaTextField.getText());
06           peminjam.setAlamat(alamatTextField.getText());
07           peminjam.setTelepon(teleponTextField.getText());
08           ApplicationContext ac = ApplicationContextProvider.getInstance().getApplicationContext();
09  
10      PeminjamDAOInterface odao = (PeminjamDAOInterface) ac.getBean("peminjamDAO",               PeminjamDAOInterface.class);
11      odao.insert(peminjam);
12      JOptionPane.showMessageDialog(this, "Data telah tersimpan");
13      } catch (DataAccessException ex) {
14              JOptionPane.showMessageDialog(this, "Gagal Simpan Data!");
15              JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
16      }
17 }

 

Dan isikan juga pada button insertPeminjamanButtonActionPerformed

 

01 if (JOptionPane.showConfirmDialog(this, "Yakin simpan data?", "KONFIRMASI", JOptionPane.YES_NO_OPTION) == 0) {
02      try {
03           Peminjam p = new Peminjam();
04           p.setIdPeminjam(idPeminjam2TextField.getText());
05           Date tglPinjam = Date.valueOf(tanggalTextField.getText());
06           Peminjaman peminjaman = new Peminjaman();
07           peminjaman.setKodePeminjaman(kodePeminjamanTextField.getText());
08           peminjaman.setIdPeminjam(p);
09           peminjaman.setTglPinjam(tglPinjam);
10           ApplicationContext ac = ApplicationContextProvider.getInstance().getApplicationContext();
11           PeminjamanDAOInterface odao = (PeminjamanDAOInterface) ac.getBean("peminjamanDAO", PeminjamanDAOInterface.class);
12           odao.insert(peminjaman);
13           JOptionPane.showMessageDialog(this, "Data telah tersimpan");
14      } catch (DataAccessException ex) {
15           JOptionPane.showMessageDialog(this, "Gagal Simpan Data!");
16           JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
17      }
18 }

 

Buat koneksi ke database melalui NetBeans, untuk memudahkan melihat isi data atau buka MySQL Query Browser. Kemudian jalankan project ini, setelah keluar inputan swing seperti dibawah ini masukan data peminjam ke textfield yang ada pada sebelah kiri, karena hanya akan mencoba memasukan data ke tabel Peminjam, kemudian klik button Insert Peminjam

 

 

Setelah data berhasil masuk ke tabel maka keluar tampilan seperti dibawah ini, masukan beberapa data peminjam untuk mencoba primary key-nya juga.

 

 

Selanjutnya masukan data peminjaman dengan memasukan ID Peminjam yang sudah berhasil masuk ke tabel tadi (diingat-ingat..hehe..). Klik button Insert Peminjaman

 

 

Yap, akan keluar pesan seperti dibawah ini jika data telah berhasil disimpan ke dalam tabel.

 

 

Eureka..!

 

Buka MySQL Query Browser atau melalui NetBeans untuk melihat isi tabel, dan secara ajaib, database yang  tadi kosong dan tidak berisi tabel, setelah program ini dijalankan tabel-tabel tersebut beserta relasinya telah dibuatkan oleh Hibernate..

How Amazing about that..! hehe.. :D

sumber : http://ivano46.wordpress.com/

Comments   

 
0 #14 Bud 2017-02-23 09:52
I know this web site gives quality dependent articles or reviews and
additional material, is there any other website which presents these
stuff in quality?

my web blog - why christmas: http://blogozine.net/cynthiagonzalez/2016/11/30/smart-things-to-do-during-christmas/
Quote
 
 
0 #13 Scot 2017-02-22 21:01
Good web site! I really love how it is simple on my
eyes and the data are well written. I'm wondering how I could be notified
whenever a new post has been made. I have subscribed to your feed which must do the
trick! Have a great day!

Feel free to surf to my webpage steamboat springs: https://thingr.com/jewellmitchell/items/73091/tips-for-buying-baby-clothes
Quote
 
 
0 #12 Janna 2017-02-22 08:55
What i don't realize is actually how you're not actually
much more well-preferred than you may be right now. You are very intelligent.
You understand therefore considerably in the case of this topic,
produced me in my opinion believe it from a lot of numerous angles.
Its like men and women aren't involved unless it is one
thing to accomplish with Girl gaga! Your own stuffs nice.
Always care for it up!

Also visit my blog; theirs sale: https://thingr.com/jewellmitchell/items/73091/tips-for-buying-baby-clothes
Quote
 
 
0 #11 Karina 2017-02-21 17:49
This article will help the internet viewers for creating new webpage or even a blog from start to
end.

Here is my blog travel (Leonora: https://www.tripoto.com/trip/why-should-you-travel-to-asia-if-you-have-a-tight-travel-budget-582eb0aa524ba)
Quote
 
 
0 #10 Wendell 2017-02-21 12:27
Hi! This is my 1st comment here so I just wanted to give a quick shout out and tell you I truly enjoy reading
your posts. Can you recommend any other blogs/websites/ forums that cover
the same topics? Thanks a lot!

Also visit my site travel (Jeanne: https://www.lomography.com/homes/paulinemarshall/notes/1917067-enjoying-your-time-in-rome)
Quote
 
 
0 #9 Deneen 2017-02-21 04:52
Do you have a spam problem on this website; I also am a blogger, and I was curious
about your situation; we have created some nice methods and we are looking
to trade methods with others, be sure to shoot me an e-mail
if interested.

Feel free to surf to my blog - travel (Arielle: https://pharmahub.org/members/2470/blog/2016/11/why-should-you-pack-your-bags-immediately-and-travel-to-a-new-place)
Quote
 
 
0 #8 Winfred 2017-02-21 00:52
Yes! Finally something about travel (Trinidad: http://www.equilibriarte.net/profile/fannierobinson/blog/36827).
Quote
 
 
0 #7 Ellie 2017-02-18 11:43
I enjoy looking through an article that will make men and women think.
Also, many thanks for allowing for me to
comment!

My blog post ... travel (Joanne: http://kicksair.com/pages/85104463-tips-to-be-adventurous)
Quote
 
 
0 #6 Valerie 2017-02-18 07:51
This design is spectacular! You obviously know how to
keep a reader entertained. Between your wit and your videos, I was almost moved
to start my own blog (well, almost...HaHa!) Great job.
I really loved what you had to say, and more than that, how you presented it.
Too cool!

Here is my weblog: travel (Jerri: https://www.givology.org/~VirginiaJohnson/blog/294101/)
Quote
 
 
0 #5 Pearl 2017-02-17 21:37
What a information of un-ambiguity and preserveness of precious
experience concerning unpredicted feelings.

Feel free to surf to my website travel [Harley: http://www.ocfoodies.com/profiles/blogs/fun-reasons-that-will-motivate-you-to-travel-more-often]
Quote
 

Add comment


Security code
Refresh

   

Indeks  

   
© ALLROUNDER