Archive

Archive for November, 2013

Hibernate One To One Annotation Mapping [ Part 3 ]

November 28, 2013 Leave a comment

Berikut ini contoh asosiasi One To One mapping dengan strategy shared primary key

1. Table

Table manager

Table Manager

Table Manager

Table company_department

Table Company_Department

Table Company_Department

 

2. Entity Class

Department class

package pojo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

@Entity
@Table(name="company_department")
public class Department {
@Id
@GeneratedValue(generator="gen")
@GenericGenerator(name="gen", strategy="foreign",parameters=@Parameter(name="property", value="manager"))
@Column(name="id")
private int idDepartment;
@Column(name="department_name")
private String departmentName;
@Column(name="location")
private String location;
@OneToOne
@PrimaryKeyJoinColumn
private Manager manager;

public int getIdDepartment() {
return idDepartment;
}

public void setIdDepartment(int idDepartment) {
this.idDepartment = idDepartment;
}

public String getDepartmentName() {
return departmentName;
}

public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}

public String getLocation() {
return location;
}

public void setLocation(String location) {
this.location = location;
}

public Manager getManager() {
return manager;
}

public void setManager(Manager manager) {
this.manager = manager;
}

}

Manager class

package pojo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name="manager")
public class Manager {

@Id
@Column(name="id_manager")
@GeneratedValue
private int idManager;
@Column(name="manager_name")
private String managerName;
@Column(name="phone_number")
private String phoneNumber;

@OneToOne(mappedBy="manager")
private Department department;

public int getIdManager() {
return idManager;
}

public void setIdManager(int idManager) {
this.idManager = idManager;
}

public String getManagerName() {
return managerName;
}

public void setManagerName(String managerName) {
this.managerName = managerName;
}

public String getPhoneNumber() {
return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}

public Department getDepartment() {
return department;
}

public void setDepartment(Department department) {
this.department = department;
}

}

3. Hibernate Configuration File

<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/jointrain?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.show_sql">true</property>
<mapping/>
<mapping/>
</session-factory>
</hibernate-configuration>

4. Hibernate Utility Class

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

public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {
try {
return new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {

System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

5. Main Class

package onetoonec;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import pojo.Department;
import pojo.Manager;

/**
*
* @author Kukuh Utama
*/
public class OneToOneC {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
Department department = new Department();
department.setDepartmentName("IT Touchpoint");
department.setLocation("Grha XL Lt.8");

Manager manager = new Manager();
manager.setManagerName("Aerlangga H");
manager.setPhoneNumber("021 322384");

manager.setDepartment(department);
department.setManager(manager);

session.save(manager);
session.save(department);
session.getTransaction().commit();
session.close();
}
}

6. Project Structure

Project Structure

Project Structure

Semoga bermanfaat.

Referensi : dari berbagai sumber.

Advertisements

Hibernate One To One Annotation Mapping [ Part 2 ]

November 27, 2013 Leave a comment

Berikut ini contoh asosiasi One To One mapping dengan strategy join table.

1. Table

Table husband

Table Husband

Table Husband

Table wife

Table Wife

Table Wife

Table husband_wife

Table Husband_Wife

Table Husband_Wife

2. Entity Class

Husband class

package pojo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name="husband")
public class Husband {

@Id
@GeneratedValue
@Column(name="id")
private int Id;

@Column(name="name_husband")
private String husbandName;

@OneToOne
@JoinTable(name="husband_wife", joinColumns=@JoinColumn(name="husband_id"), inverseJoinColumns=@JoinColumn(name="wife_id"))
private Wife wife;

public int getId() {
return Id;
}

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

public String getHusbandName() {
return husbandName;
}

public void setHusbandName(String husbandName) {
this.husbandName = husbandName;
}

public Wife getWife() {
return wife;
}

public void setWife(Wife wife) {
this.wife = wife;
}
}

Wife class

package pojo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name="wife")
public class Wife {
@Id
@GeneratedValue
@Column(name="id")
private int Id;

@Column(name="name_wife")
private String wifeName;

@OneToOne(mappedBy="wife")
private Husband husband;

public int getId() {
return Id;
}

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

public String getWifeName() {
return wifeName;
}

public void setWifeName(String wifeName) {
this.wifeName = wifeName;
}

public Husband getHusband() {
return husband;
}

public void setHusband(Husband husband) {
this.husband = husband;
}
}

3. Hibernate Configuration File

<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/jointrain?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.show_sql">true</property>
<mapping></mapping>
<mapping></mapping>
</session-factory>
</hibernate-configuration>

4. Hibernate Utility Class

package onetooneb;

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);
}
}

static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

5. Main Class

package onetooneb;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import pojo.Husband;
import pojo.Wife;

/**
*
* @author Kukuh Utama
* Using foreign join table
*/
public class OneToOneB {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
Wife wife = new Wife();
wife.setWifeName("Finita Ari");

Husband husband = new Husband();
husband.setHusbandName("Herling S");

wife.setHusband(husband);
husband.setWife(wife);
session.save(husband);
session.save(wife);

session.getTransaction().commit();
session.close();
}
}

6. Project Structure

Project Structure

Project Structure

7. Output Console

Output Console

Output Console


Semoga bermanfaat.

Referensi : dari berbagai sumber.

Hibernate One To One Annotation Mapping [ Part 1 ]

November 26, 2013 Leave a comment

Berikut ini contoh asosiasi One To One mapping dengan strategy foreign key association

1. Table

Table baccount

Account Table

Account Table

Table bcustomer

Customer Table

Customer Table

2. Entity Class

BAccount class.

package pojo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;


@Entity
@Table(name="baccount")
public class BAccount {

private int id;
private String accountNumber;
private BCustomer bCustomer;

@Id
@Column(name="Id")
@GeneratedValue
public int getId() {
return id;
}

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

@Column(name="account_number")
public String getAccountNumber() {
return accountNumber;
}

public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}

@OneToOne(mappedBy="bAccount")
public BCustomer getbCustomer() {
return bCustomer;
}

public void setbCustomer(BCustomer bCustomer) {
this.bCustomer = bCustomer;
}
}

BCustomer class.


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


@Entity
@Table(name="bcustomer")
public class BCustomer implements Serializable {

@Id
@Column(name="Id")
@GeneratedValue
private int Id;
@Column(name="first_name")
private String firstName;
@Column(name="last_name")
private String lastName;

@OneToOne
@JoinColumn(name="id_account")
private BAccount bAccount;

public int getId() {
return Id;
}

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

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public BAccount getbAccount() {
return bAccount;
}

public void setbAccount(BAccount bAccount) {
this.bAccount = bAccount;
}
}

3. Hibernate Configuration File

<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306     /jointrain?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.show_sql">true </property>
<mapping class="pojo.BAccount"/>
<mapping class="pojo.BCustomer"/>
</session-factory>
</hibernate-configuration>

4. Hibernate Utility Class

package onetoonea;

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);
}
}

static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

5. Main Class

package onetoonea;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import pojo.BAccount;
import pojo.BCustomer;


public class OneToOneA {
public static void main(String[] args) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
BAccount bAccount = new BAccount();
bAccount.setAccountNumber("12345A");


BCustomer bCustomer = new BCustomer();
bCustomer.setFirstName("Kukuh");
bCustomer.setLastName("Utama");


bAccount.setbCustomer(bCustomer);
bCustomer.setbAccount(bAccount);


session.save(bAccount);
session.save(bCustomer);
session.getTransaction().commit();
session.close();
}
}

6. Project Structure

Project Structure

Project Structure

7. Output Console

Output Console

Output Console

Semoga bermanfaat.

Referensi : dari berbagai sumber.

Check Dan Uncheck Checkbox Dengan Javascript

November 24, 2013 Leave a comment

Berikut ini trivia untuk melakukan check dan uncheck checkbox dengan menggunakan javascript.

Javascript code :

<script language="javascript">
function checkAll(checktoggle){
var checkboxes = new Array();
checkboxes = document["input_form"].getElementsByTagName('input')
for (var i=0; i<checkboxes.length; i++)  {
if (checkboxes[i].type == 'checkbox'){
checkboxes[i].checked = checktoggle;
}
}
}
</script>

form code (html) :

<form name="input_form" action="" method="">
<input type="checkbox" value="car"> I have car </br>
<input type="checkbox" value="motor"> I have motor</br>
<input type="checkbox" value="bycle" > I have bycle </br>
<input type="button" value="Check all" onclick="checkAll(true)">
<input type="button" value="Uncheck all" onclick="checkAll(false)">
</form>

Semoga bermanfaat. 🙂

Validasi Form Dengan Javascript

November 17, 2013 Leave a comment

Berikut ini trivia untuk validasi form. Dimana input field form tidak boleh kosong, email field valid, dsb.

Javascript form validation code :

<script language="javascript">

function isNumericKey(evt){
var charCode = (evt.which)? evt.which : evt.keyCode;
if(charCode > 31 && (charCode <48 || charCode >57))
return false;

return true;
}

function formValidation(){

document.getElementById("errorMessage").value="";
var name = document.forms["logIn"]["name"].value;
var email = document.forms["logIn"]["email"].value;
var pnumber= document.forms["logIn"]["pnumber"].value;
var password = document.forms["logIn"]["password"].value;
var rpassword = document.forms["logIn"]["rpassword"].value;

if(name == null || name==""){
document.getElementById("errorMessage").value= document.getElementById("errorMessage").value + "\n Please enter Name";
return false;}

if(pnumber == null || pnumber=="") {
document.getElementById("errorMessage").value= document.getElementById("errorMessage").value + "\n Please enter Phone Number";
return false; }

if(email == null || email==""){
document.getElementById("errorMessage").value= document.getElementById("errorMessage").value + "\n Please enter Email";
return false; }

if(email != ""){
bool = emailValidation(email);
return bool; }

if(password  == null || password ==""){
document.getElementById("errorMessage").value= document.getElementById("errorMessage").value + "\n Please enter Password";
return false;}

if(rpassword  == null || rpassword ==""){
document.getElementById("errorMessage").value= document.getElementById("errorMessage").value + "\n Please enter Re-password";
return false; }

if( password != rpassword){
document.getElementById("errorMessage").value= document.getElementById("errorMessage").value + "\n Password mismatch";
return false; }

return true;
}

function emailValidation(emailIn){

email = emailIn;
var atpos = email.indexOf("@");
var dotpost = email.lastIndexOf(".");
if( atpos <1 ||  dotpos < atpos+2  || dotpos+2 >= email.length)
document.getElementById("errorMessage").value= document.getElementById("errorMessage").value + "\n Invalid Email";
return false;

}
</script>

contoh html code:


<form name="logIn" method="post" onsubmit="return formValidation()">
<label for="lbl_name"> Name </lable>
<input type="text" name="name" id="name"> </br>
<label for="lbl_pnumber">Phone Number </lable>
<input type="text" name="pnumber" id="pnumber" onkeypress="return isNumericKey(event)"> </br>
<label for="lbl_email"> Email </lable>
<input type="text" name="email" id="email"> </br>
<label for="lbl_password"> Password </lable>
<input type="text" name="password" id="password"> </br>
<label for="lbl_rpassword">Re-type Password </lable>
<input type="text" name="rpassword" id="rpassword"></br>
<input type="submit" name="submit" value="Submit"> </br>
<textarea row="10" cols="50" id="errorMessage" disabled="true" style="color:red">
</textarea>
</form>

Semoga bermanfaat.

Membatasi Input Field Hanya Numeric Dengan Javascript

November 16, 2013 Leave a comment

Berikut ini trivia untuk membatasi input field hanya dapat menerima input berupa numeric.

Javascript code:

<script language="javascript">
        function isNumericKey(evt){
                  var charCode = (evt.which)? evt.which : evt.keyCode;
                  if(charCode > 31 && (charCode <48 || charCode >57) )
                       return false; 

                   return true;
         }
</script>

Input field.

<label for="lbl_email"> Nomer HP </lable>

<input type="text" name="nohp" id="nohp" onkeypress="return isNumericKey(event)">

Referensi
Semoga bermanfaat.

Email Validasi Dengan Javascript

November 16, 2013 Leave a comment

Berikut ini trivia untuk validasi input untuk email menggunakan javascript.

Javascript validation code:

<script language="javascript">
function emailValidation(){
var email = document.getElementById("email").value;
var atpos = email.indexOf("@");
var dotpost = email.lastIndexOf(".");
if( atpos <1 ||  dotpos < atpos+2  || dotpos+2 >= email.length)
alert("Invalid Email Address");
return false;
}
</script>


Form input (.html)

<form method="post" action="" onsubmit="return emailValidation()">
<label for="lbl_email"> Email :</lable> <input type="text" name="email" id="email">
<input type="submit" value="Submit">
</form>

Semoga bermanfaat.