Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Sunday, July 25, 2010

CRUD using Hibernate Annotations with Netbean 6.0


In this article we will discuss about the basic make the process of Create, Read, Update and Delete using Hibernate as the Framework and Netbean as its IDE, Hibernate configuration usually always never loose with Spring configuration, but on this occasion I will elaborate on Hibernate without Spring, with the aim if you want to create desktop applications the Spring configuration is not required.

Before we start it's good to know a class-library will be need it takes to build applications using Hibernate Annotations, as follows:


Now how do I enter all libraries into the project properties that we will create? Enough that we follow these steps: from the Toolbar select Tools then clicked, will popup dropdown menu, then select Libraries then will come out the window box with title "Library Manager", then press the "New Library", then come out again the window box with the title "New Library", fill in the word "Hibernate” in the Library Name text box, continue to select the "Class Libraries" dropdown box Type Library, then press OK, then select Hibernate library jar file that has been listed above to the folder which we have previously determined by press the button "Add Jar / Folder" on the tab "Classpath", after the files sent it will displayed like this:

After that, press "OK" button, now the discussion will be continued by creating a new project in the IDE Netbean. After creating a new project, whether web or desktop project, the project window will as follows:

After creating a project, first enter the hibernate libraries by right click on the library folder, then click "Add Library" and will come out a window with the title "Add Library", forwarded by selecting the necessary library which is selected, then "Add Library", then the Library folder in the project will display the entire library jar file that will required in the application to be built.

After all required libraries are prepared in the library folder, now it's time to discuss making CRUD using Hibernate, before you start coding with java class we need to know beforehand the basic configuration that must be met, so that Hibernate can work properly, this configuration involves an xml file that will be placed in the root folder of the folder "Source Packages", these files must be named "hibernate.cfg.xml" and the contents of the file will be as follows:


<?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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/latih</property>
<property name="connection.username">root</property>
<property name="connection.password">admin</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">none</property>

<mapping class="xxx.TabelSiswa"/>
</session-factory>
</hibernate-configuration>

From the source xml above configuration, there are several properties that must exist to build hibernate based application framework, the following list and description for more details can be viewed on the link http://www.hibernate.org/hib_docs/reference/en/html/session-configuration.html:

- connection.driver.class, This property is used as a determinant of what database driver will be used to connect to database.

- connection.url, This property is used to determine the url destination of database to be used as a connection to the database.

- connection.username, property user name that is used to access databases.

- connection.password, property password that is used to access databases.

- connection.pool.size, property that is used as maximum limit how many connections may used to connect to the database.

- dialect, property that determines what types dialect that will be used, adjusted to the type of database used.

- current_session_context_class, property that is used to treat the session context, the choice is jta | thread | managed | custom.Class.

- cache.provider_class, property to specify a custom class that will be used to CacheProvide.

- show_sql, property to show that the execution of SQL commands the choice can be true or false.

- hbm2ddl.auto, property for automatic validation or export a database schema to the SessionFactory when made, and create-drop properties directly in the schema will drop when the SessionFactory is closed. When the properties set to none means not to do anything against the database schema.

While for a line of code <mapping class="xxx.TabelSiswa"/> is command for mapping an Annotation Model classes so that it can be read by hibernate.cfg.xml file, the amount of mapping will be more or less depending on the number of class models are made to support your application.

When finished with the configuration now the time to make a model class that represents a table in a database. As an example we will create a class "TabelSiswa" which will be stored in the package "xxx", the code as follow:

package xxx;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "tbl_siswa")
public class TabelSiswa implements Serializable{
@Id
@GeneratedValue
private int id;

@Column(name="no_induk", nullable=false,length=10)
private String nomorInduk;

@Column(name="nama", nullable=false,length=30)
private String nama;

@Column(name="alamat", nullable=false,length=45)
private String alamat;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getNomorInduk() {
return nomorInduk;
}

public void setNomorInduk(String nomorInduk) {
this.nomorInduk = nomorInduk;
}

public String getNama() {
return nama;
}

public void setNama(String nama) {
this.nama = nama;
}

public String getAlamat() {
return alamat;
}

public void setAlamat(String alamat) {
this.alamat = alamat;
}
}

The above code represents a table in a MySQL database called "tbl_siswa" with field names specified in the @ Column properties above, from source code "TabelSiswa" above we can see some syntax code that begins with "@" sign, which is called Annotations briefly will be explained the meaning of each following the above commands, but for more details can be viewed on the following link http://www.hibernate.org/hib_docs/annotations/reference/en/html/entity.html:

- @Entity, serves to define a model class is an bean associated with the POJO persistence.

- @Table, serves to connect an Entity classes on a table in a database schema.

- @Id, serves to define the propery of the entity bean fields that will serve as the primary key.

- @GeneratedValue, serves to define generator type that is used to obtain the value of identifier @Id.

- @Column, serves as the property of field mapping a field in the table in the database.

Then create a java class file that called HibernateUtility.java used as a Session Factory, which connects a process which was generated programmatic transaction with hibernate configuration system that has been predetermined. The source code of HibernateUtility would this as follow:

package xxx;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {
private static final SessionFactory sessionFactory;

static{
try{
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}catch(Throwable th){
System.err.println("Initial SessionFactory creation failed"+th);
throw new ExceptionInInitializerError(th);
}
}

public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}

When finished making HibernateUtility.java now begin discussing the process of Create, Read, Update and Delete, which will be stored in the package "xxx.client", here is source code "CreateData.java" which contains examples of commands to enter data:

package xxx.client;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import xxx.HibernateUtil;
import xxx.TabelSiswa;

public class CreateData {
public static void main(String[] args) throws Exception {
SessionFactory sessFact = HibernateUtil.getSessionFactory();
Session sess = sessFact.getCurrentSession();
Transaction tr = sess.beginTransaction();
TabelSiswa stu = new TabelSiswa();
stu.setNama("Yudhi");
stu.setNomorInduk("100");
stu.setAlamat("Jl. Sukajadi No. 10");
sess.save(stu);
tr.commit();
System.out.println("Successfully inserted");
sessFact.close();
}
}

Discussing what is written on the source code in the first row to third in the method "main" written to initialize Hibernate Session and Transaction, then proceed with initialization "TabelSiswa" that connects directly to the table "tabel_siswa" in the database, with the amount of variables to the method "set" and then inserted into the method "save" that are under the initialization Session, it has been a process of "insert into" on the table in database. Then close the command with "commit" to the execution of insert data to table and "close" to terminate the Session initialization.

Followed by "ReadData.java" source code:


package xxx.client;

import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import xxx.HibernateUtil;
import xxx.TabelSiswa;

public class ReadData {
public static void main(String[] args) throws Exception {
SessionFactory sessFact = HibernateUtil.getSessionFactory();
Session sess = sessFact.getCurrentSession();
Transaction tr = sess.beginTransaction();
Query query = sess.createQuery("from TabelSiswa");
List result = query.list();
Iterator it = result.iterator();
System.out.println("id sname sroll scourse");
while(it.hasNext()){
TabelSiswa st = (TabelSiswa)it.next();
System.out.print(st.getId());
System.out.print(" "+st.getNomorInduk());
System.out.print(" "+st.getNama());
System.out.print(" "+st.getAlamat());
System.out.println();
}
sessFact.close();
}
}

Slightly different from the source code before, the above command is to display data from tables or the same with the command "select" in the query, but if you use Hibernate enough with the "createQuery" command and specify the name of instant mapping table, it’s enough to retrieve the data, the need to take data can be changed based on the 'where clause' as required. It also required List and Iterator class to parse the class that will encapsulate the smallest object.


Followed by "UpdateData.java" source code:

package xxx.client;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import xxx.HibernateUtil;
import xxx.TabelSiswa;

public class UpdateData {
public static void main(String[] args) throws Exception{
SessionFactory sessFact = HibernateUtil.getSessionFactory();
Session sess = sessFact.getCurrentSession();
Transaction tr = sess.beginTransaction();
TabelSiswa st = (TabelSiswa)sess.load(TabelSiswa.class,4);
st.setAlamat("Jl. Lodaya No. 125");
tr.commit();
System.out.println("Update Successfully");
sessFact.close();
}
}

For the source code UpdateData processes that occurred not far different from what happened in the process CreateData, little things that differentiate only on the line "TabelSiswa st = (TabelSiswa) sess.load (TabelSiswa.class, 4);" that is used to retrieve data that will edited into the database with the entity model "TabelSiswa" and make any changes, after which it did commit. And the last is deleting process in "DeleteData.java" file, source code as follows:

package xxx.client;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import xxx.HibernateUtil;
import xxx.TabelSiswa;

public class DeleteData {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub

SessionFactory sessFact = HibernateUtil.getSessionFactory();
Session sess = sessFact.getCurrentSession();
Transaction tr = sess.beginTransaction();
TabelSiswa st = (TabelSiswa)sess.load(TabelSiswa.class,4);
sess.delete(st);
System.out.println("Deleted Successfully");
tr.commit();
sessFact.close();

}
}

DeleteData source code process that occurs is not much different from what happens in UpdateData process, little things that differentiate only on the line "sess.delete(st);" that is used to retrieve data to be deleted from the database with the entity model "TabelSiswa" after that do commit.

Ok good luck! Maybe for this time this is trick that can be shared with the reader hope it useful, if there is a shortage or entries which can improve please feel free to give comment.

Here's a list of links that can be used to download the required jar files:

- http://antlr.org/

- http://www.java2s.com/Code/Jar/Spring-Related/cglib-nodep-2.1_3.jar.htm

- http://sourceforge.net/project/showfiles.php?group_id=56933

- http://sourceforge.net/project/showfiles.php?group_id=40712

- http://commons.apache.org/downloads/

- http://www.dom4j.org/download.html

- http://sourceforge.net/project/showfiles.php?group_id=93232

- http://logging.apache.org/log4j/1.2/download.html


Read More...

Thursday, March 19, 2009

Hibernate Criteria Query - MySQL Command Syntax Dictionary


For some viewer already know about Java Platform may already familiar with Hibernate, and so for viewer already familiar with Hibernate probably already know with “Criteria Query” term. In this time I’ll try to discuss equality function between Criteria Query and MySQL, with purpose to help other in order to learn about Hibernate and how the function similarity between Criteria Query and basic standard command in MySQL query syntax.

And now we can start to discuss those thing, first we take a table for example in MySQL and going to convert into a class model with java platform and follow by term of Hibernate. In this case we going to use Hibernate Annotation so we not need xml file for field class mapping to field table in a database. For simple case we try to create a table and called it with name “karyawan” and so we create java class model with a same name.


Nama FieldType FieldPrimary Key
idInteger / NumericYes
namaVarchar(30)
tgl_masukDate
upahDecimal(20,10)

With this command we can create this table on MySQL:

CREATE TABLE `karyawan` (                                  
`id` int(11) NOT NULL auto_increment,
`nama` varchar(30) default NULL,
`tgl_masuk` date NOT NULL default '1970-01-01',
`upah` decimal(20,10) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC

Then create model class “Karyawan” made by these syntax show below:

@Entity
@Table(name="karyawan")
public class Karyawan implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;

@Column(name="nama")
private String nama;

@Temporal(TemporalType.DATE)
@Column(name="tgl_masuk",nullable=false,columnDefinition="date")
private Date tglMasuk;

@Column(name="upah")
@Type(type="big_decimal")
private BigDecimal upah;

public Karyawan() {}

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getNama() {
return nama;
}

public void setNama(String nama) {
this.nama = nama;
}

public Date getTglMasuk() {
return tglMasuk;
}

public void setTglMasuk(Date tglMasuk) {
this.tglMasuk = tglMasuk;
}

public BigDecimal getUpah() {
return upah;
}

public void setUpah(BigDecimal upah) {
this.upah = upah;
}
}

By assuming that you already know about Hibernate by this reference article “Proses CRUD Dengan Hibernate Annotations Menggunakan Netbean 6.0”, then we can strait to discuss how to use Criteria Query, we can use these class “Criteria” from “org.hibernate.Criteria” or “DetachedCriteria” from “org.hibernate.criterion.DetachedCriteria” and followed by these class “Expression” from “org.hibernate.criterion.Expression” or “Restriction” from “org.hibernate.criterion.Restriction”, and than with assumption we going to call all data in the table “Karyawan” then we can use this SQL command like shown below:

select * from Karyawan;

whereas used Criteria Query even though “Criteria” or “DetachedCriteria” will produce command line syntax like shown below:

getSession().createCriteria(Karyawan.class).list();

The table shown below are equality command between Criteria Query and MySQL command:

MySQLHibernate Criteria Query
select * from Karyawan where id = 1;getSession().createCriteria(Karyawan.class) .add(Expression.eq(“id”, Long.valueOf(1)))
.list();
select * from Karyawan where id != 1;getSession().createCriteria(Karyawan.class) .add(Expression.ne(“id”, Long.valueOf(1)))
.list();
select * from Karyawan where id <> 1;getSession().createCriteria(Karyawan.class) .add(Expression.ne(“id”, Long.valueOf(1)))
.list();
select * from Karyawan where nama = “sesuatu”;getSession().createCriteria(Karyawan.class)
.add(Expression.eq(“nama”, “sesuatu”))
.list();
select * from Karyawan where tgl_masuk = “1900-01-01”;getSession().createCriteria(Karyawan.class)
.add(Expression.eq(“tglMasuk”, new java
.util.Date(java.sql.Date
.valueOf("1900-01-01"))))
.list();
select * from Karyawan where upah = 10000;getSession().createCriteria(Karyawan.class)
.add(Expression.eq(“upah”, BigDecimal
.valueOf(10000)))
.list();
select * from Karyawan where id > 10;getSession().createCriteria(Karyawan.class)
.add(Expression.gt(“id”, Long.valueOf(10)))
.list();
select * from Karyawan where id < 10 and id > 30;getSession().createCriteria(Karyawan.class)
.add(Expression.lt(“id”, Long.valueOf(10)))
.add(Expression.gt(“id”, Long.valueOf(30)))
.list();
select * from Karyawan where id < 10 or id > 30;getSession().createCriteria(Karyawan.class)
.add(Expression.or(Expression.lt(“id”, Long.valueOf(10)), Expression.gt(“id”, Long.valueOf(30))))
.list();
select * from Karyawan where id <= 10;getSession().createCriteria(Karyawan.class)
.add(Expression.le(“id”, Long.valueOf(10)))
.list();
select * from Karyawan where id >= 10;getSession().createCriteria(Karyawan.class)
.add(Expression.ge(“id”, Long.valueOf(10)))
.list();
select * from Karyawan where nama like ‘sesu%’;getSession().createCriteria(Karyawan.class)
.add(Expression.like(“nama”, “sesu”, MatchMode.END))
.list();
select * from Karyawan where nama like ‘%sua%’;getSession().createCriteria(Karyawan.class)
.add(Expression.like(“nama”, “sua”, MatchMode.ANYWHERE))
.list();
select * from Karyawan where nama like ‘%atu’;getSession().createCriteria(Karyawan.class)
.add(Expression.like(“nama”, “atu”, MatchMode.START))
.list();
select * from Karyawan where nama like ‘sesuatu’;getSession().createCriteria(Karyawan.class)
.add(Expression.like(“nama”, “sesuatu”, MatchMode.EXACT))
.list();
select * from Karyawan where id between 0 and 100;getSession().createCriteria(Karyawan.class)
.add(Expression.between(“id”, Long.valueOf(0), Long.valueOf(100)))
.list();
select * from Karyawan where nama = ‘’;getSession().createCriteria(Karyawan.class)
.add(Expression.isEmpty(“nama”))
.list();
select * from Karyawan where nama <> ‘’;getSession().createCriteria(Karyawan.class)
.add(Expression.isNotEmpty(“nama”))
.list();
select * from Karyawan where nama is null;getSession().createCriteria(Karyawan.class)
.add(Expression.isNull(“nama”))
.list();
select * from Karyawan where nama is not null;getSession().createCriteria(Karyawan.class)
.add(Expression.isNotNull(“nama”))
.list();
select * from Karyawan where id in (1,3,5,7);List<Long> idlist = new ArrayList<Long>();
idlist.add(1);
idlist.add(3);
idlist.add(5);
idlist.add(7);
getSession().createCriteria(Karyawan.class)
.add(Expression.in(“id”, idlist))
.list();
select * from Karyawan where id not in (1,3,5,7);List<Long> idlist = new ArrayList<Long>();
idlist.add(1);
idlist.add(3);
idlist.add(5);
idlist.add(7);
getSession().createCriteria(Karyawan.class)
.add(Expression.not(Expression.in(“id”, idlist)))
.list();
select * from Karyawan where id > 1 order by id ASC;getSession().createCriteria(Karyawan.class)
.addOrder(Order.asc(“id”))
.add(Expression.ge(“id”, Long.valueOf(1)))
.list();
select * from Karyawan where id > 1 order by id DESC;getSession().createCriteria(Karyawan.class)
.addOrder(Order.desc(“id”))
.add(Expression.ge(“id”, Long.valueOf(1)))
.list();

For additional note, these “Expression.not” or “Restriction.not” command cannot used for MySQL query command like this “Select * from Karyawan where id <> 1” or “Select * from Karyawan where id != 1” though in syntax show where condition “not equal” cause by this command in Criteria Query already represent by “Expression.ne” or “Restriction.ne”. As reference for correct syntax, if Hibernate command we created as part of web-app using Spring Framework, then all example show above must written in Class DAO Implementation, but if isn’t than it necessary to write in Object Class. Like sample below:

@SuppressWarnings("unchecked")
public List<Karyawan> loadContohSatu() {
List<Long> idlist = new ArrayList<Long>();
idlist.add(1);
idlist.add(3);
idlist.add(5);
idlist.add(7);

return getSession().createCriteria(Karyawan.class)
    .add(Expression.not(Expression.in(“id”, idlist))).list();
}

@SuppressWarnings("unchecked")
public List<Karyawan> loadContohDua() {
return getSession getSession().createCriteria(Karyawan.class)
    .addOrder(Order.asc(“id”))
    .add(Expression.ge(“id”, Long.valueOf(1))).list();
}

Perhaps for this moment this knowledge that I can share to all reader, if in this article contain some mistake, please don’t mind to correct me if I done some wrong or give me some advise and comment.


Read More...

Wednesday, November 5, 2008

ASCII code manipulate with Java Runtime

The idea of this article beginning when the company I worked now need some utility command to build connectivity between the application which is build in java platform connect to hardware. To gain connectivity to hardware tools we need command line in ASCII code as like this “alt+27, alt+112, alt+48, alt+62, alt+76, alt+80, alt+84, alt+49”, if we use this line syntax using command prompt M$ DOS, before the main command first we must write command “echo” + space followed by these ASCII code, after hit the enter button then command running and hopefully the hardware can response to that command line.

By using this ASCII code list as reference, than we get ASCII code that needed to accessing this hardware:



Be sides of ASCII code that often use in daily programming like in table above, there is another ASCII code is rare used in daily programming, this reference table below is shown ASCII code that represent symbol and line character:

After knowing ASCII code for hardware specification, and now time to figure out how to connect ASCII code to command line in Java, that is using Runtime command from “java.lang.Runtime”, with complete command write like this “Runtime.getRuntime().exec(‘this ASCII code written to be execute’);” with return value class Process from “java.lang.Process” than initialize into “p” object, from that object we can got this command “p.waitFor();” with aiming the system will wait until this command to hardware is come to end, as the following source code as an example how to use ASCII code to Runtime command. But don’t forget to write this line “cmd /c” before “echo” syntax if you try to execute it on windows, to call DOS command prompt.

StringBuffer strNew = new StringBuffer();
strNew.append(new Character((char)27));
strNew.append(new Character((char)112));
strNew.append(new Character((char)48));
strNew.append(new Character((char)62));
strNew.append(new Character((char)76));
strNew.append(new Character((char)80));
strNew.append(new Character((char)84));
strNew.append(new Character((char)49));

Process p = Runtime.getRuntime().exec("cmd /c echo "+strNew.toString());
p.waitFor();
Perhaps for this moment this knowledge that I can share to all reader, if in this article contain some mistake, please don’t mind to correct me if I done some wrong or give me some advise and comment.

Read More...

Monday, October 27, 2008

“Non-terminating decimal expansion” How could this occurred?

For some people already familiar with Java might used to hear or experience this event. With slightly experiment, I’ll try to calculate some numeric variable using BigDecimal as java type variable, if we’ll do some process with addition, alleviation, mulitiplication and division by using BigDecimal command method we can use these syntax “add()”, “substract()”, “multiply()” and “divide()” to complete, all these process could worked like expected, but these process could produce some error if we do some process with alleviation using command syntax “divide” which is produce return value with fraction or value with decimal place, and an error view that produce by these process if we used command syntax “printStackTrace” could be like this.

java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
at java.math.BigDecimal.divide(BigDecimal.java:1514)





at java.lang.Thread.run(Thread.java:619)


Necessary to know if we used some framework in our project, any framework, than content of some dot in error view above will figure printStackTrace message relate on that framework. This thing could occurred in alleviation processed. We can use this calculate process syntax bellow as example source code:

public class SuatuClass {
static BigDecimal bilAwal = BigDecimal.valueOf(10);
static BigDecimal bilAkhir = BigDecimal.valueOf(15);
static BigDecimal hasilBagi = BigDecimal.valueOf(0);

public static void main(String[] args) {
divideOperation();
}

public static void divideOperation() {
hasilBagi = bilAwal.divide(bilAkhir);

System.out.println("Print Hasil Akhir "+ hasilBagi);
}
}

And now we’ll try focus our attention to a line of this source code “bilAwal.divide(bilAkhir);” if return value from calculation is a fraction than it’ll produce error view like printStackTrace above, and now, how to breaking the ice? “Gampang.. Ketik reg spasi manjur kirim ke……” Hehe.. Just kidding (Indonesian joke style), if we want result value produce by this process is an integer than a line of source code should change into like this “bilAwal.divide(bilAkhir ,RoundingMode.HALF_UP);” property HALF_UP will produce value which rounded up if fraction value behind decimal point is greater than 0.5, for better explanation we can see a table to figure some property and utility in a class RoundingMode below:


For a better clear view about utility and property of RoundingMode can see on this link: http://java.sun.com/j2se/1.5.0/docs/api/java/math/RoundingMode.html.

If we still want a fraction value behind decimal point than a command line syntax that shows above need some change to fulfill requirement with divide command like shown below “bilAwal.divide(bilAkhir, 3, RoundingMode.HALF_UP);” numeric value which place in the middle of three parameter has a function to determine amount of number behind a decimal point should place on result value, source code shown above if we like to place three digit number as fraction behind decimal point.

For a better clear view about utility and property of BigDecimal can see on this link: http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html.

Perhaps for this moment this knowledge that I can share to all reader, if in this article contain some mistake, please don’t mind to correct me if I done some wrong or give me some advise and comment.


Read More...