Users  

   

Hobi  

   

Statistik  

Visitors
232
Articles
59
Articles View Hits
394897
   

User Online  

We have 34 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 #25 Gabrielle 2017-03-19 22:45
Some genuinely good content on this internet site, thanks for contribution.

Also visit my web site wedding speech: http://www.arthood.com/blogs/2103/2053/planning-your-wedding-on-a-tight-budget
Quote
 
 
0 #24 Dian 2017-03-18 21:26
Thank you for the auspicious writeup. It in fact was a amusement account it.
Look advanced to far added agreeable from you!
However, how can we communicate?

Review my site ... theme weddings: http://www.thesnug.com/mistakes-women-make-while-choosing-a-wedding-dress-2099679395.html
Quote
 
 
0 #23 Princess 2017-03-18 04:32
If some one wishes to be updated with most recent
technologies afterward he must be visit this site and be up to date everyday.


My page: buy wholesale flowers: http://www.beadandcord.com/clipper/arnold.ledoux/diy-clothes-58418/279745.html
Quote
 
 
0 #22 Sean 2017-03-17 17:46
Some truly excellent posts on this site, thanks for contribution.

Stop by my site ... colorful bouquet wire: http://www.arthood.com/blogs/2103/2053/planning-your-wedding-on-a-tight-budget
Quote
 
 
0 #21 Joseph 2017-03-16 22:15
My brother recommended I might like this blog. He was
entirely right. This post actually made my day. You cann't imagine simply how much time I had spent for this info!
Thanks!

Here is my weblog: wedding stationery: http://www.thesnug.com/mistakes-women-make-while-choosing-a-wedding-dress-2099679395.html
Quote
 
 
0 #20 Kandi 2017-03-15 05:53
Thanks, I've recently been looking for information about this topic for
a while and yours is the greatest I have found out till now.
But, what in regards to the conclusion? Are you positive concerning the supply?


Take a look at my blog post :: wedding planning budget: http://artjournalist.com/myblog/tips-for-wedding-abroad/
Quote
 
 
0 #19 Oren 2017-03-15 05:28
In combating QR codes, you'll find three major reasons being presented to
offer the theory these two-dimensional barcodes just aren't clicking with Americans:.
And thanks to some retrofit technology that's in route, it's effectively yesterday.
Allowing consumers to find the charity, or even having a revolving set of charities,
results in like a marketing incentive.

my weblog of science and technology (odtufutbolokulu.com: http://odtufutbolokulu.com/arsivler/5697)
Quote
 
 
0 #18 Kristy 2017-03-15 02:41
Hey there! I could have sworn I've been to this website
before but after reading through some of the post I realized it's new
to me. Anyways, I'm definitely delighted I found it and I'll be bookmarking
and checking back often!

Also visit my homepage; way certain design: http://artjournalist.com/myblog/tips-for-wedding-abroad/
Quote
 
 
0 #17 Krystal 2017-03-03 06:24
It's especially hard if you feel like you are the only teacher inside your school
to use fitting technologies in your planning and classroom delivery.
And thanks to some retrofit technology that's on the way,
it's effectively yesterday. Silicon is easily the most common of such materials accustomed to generate electrical current when it is subjected
to sunlight.

Here is my web-site ... web site design (http://www.contactkeepergloves.com/it/data-room-providers/key-advantages-of-working-with-a-virtual-data-room-2: http://www.contactkeepergloves.com/it/data-room-providers/key-advantages-of-working-with-a-virtual-data-room-2/)
Quote
 
 
0 #16 Mohammad 2017-03-01 11:48
This device also governs the flow of power from your photovoltaic array towards the grid and vice-versa.

Make any final announcements (for example, another webinar in the series).
Roughly equal amounts in the three primary colors give rise towards the perception of white.


Here is my homepage - Eniva Vibe (http://edendrivingschoolfootscray.com.au/: http://edendrivingschoolfootscray.com.au/selecting-the-top-virtual-data-room-to-your-5/)
Quote
 

Add comment


Security code
Refresh

   

Indeks  

   
© ALLROUNDER