Tuesday, March 22, 2011

hibernate - cascade definition


1. No save-update cascade

In previous section, if you want to save the ‘Stock’ and its referenced ‘StockDailyRecord’ into database, you need to save both individually.




Stock stock = new Stock();
StockDailyRecord stockDailyRecords = new StockDailyRecord();
//set the stock and stockDailyRecords  data
 
stockDailyRecords.setStock(stock);        
stock.getStockDailyRecords().add(stockDailyRecords);
 
session.save(stock);
session.save(stockDailyRecords);
Output
Hibernate: 
    insert into mkyong.stock (STOCK_CODE, STOCK_NAME) 
    values (?, ?)
 
Hibernate: 
    insert into mkyong.stock_daily_record
    (STOCK_ID, PRICE_OPEN, PRICE_CLOSE, PRICE_CHANGE, VOLUME, DATE) 
    values (?, ?, ?, ?, ?, ?)

2. With save-update cascade

The cascade=”save-update” is declared in ‘stockDailyRecords’ to enable the save-update cascade effect.

 name="stockDailyRecords" cascade="save-update" table="stock_daily_record"...>
      >
             name="STOCK_ID" not-null="true" />
      >
       class="com.mkyong.common.StockDailyRecord" />
>
Stock stock = new Stock();
StockDailyRecord stockDailyRecords = new StockDailyRecord();
//set the stock and stockDailyRecords  data
 
stockDailyRecords.setStock(stock);        
stock.getStockDailyRecords().add(stockDailyRecords);
 
session.save(stock);
Output
Hibernate: 
    insert into mkyong.stock (STOCK_CODE, STOCK_NAME) 
    values (?, ?)
 
Hibernate: 
    insert into mkyong.stock_daily_record
    (STOCK_ID, PRICE_OPEN, PRICE_CLOSE, PRICE_CHANGE, VOLUME, DATE) 
    values (?, ?, ?, ?, ?, ?)
The code session.save(stockDailyRecords); is no longer required, when you save the ‘Stock’, it will “cascade” the save operation to it’s referenced ‘stockDailyRecords’ and save both into database automatically.

Cascade delete example

In this example, if a ‘Stock’ is deleted, all its referenced ‘stockDailyRecords’ should be deleted from database as well.

1. No delete cascade

You need to loop all the ‘stockDailyRecords’ and delete it one by one.
Query q = session.createQuery("from Stock where stockCode = :stockCode ");
q.setParameter("stockCode", "4715");
Stock stock = (Stock)q.list().get(0);
 
for (StockDailyRecord sdr : stock.getStockDailyRecords()){
         session.delete(sdr);
}
 session.delete(stock);
Output
Hibernate: 
    delete from mkyong.stock_daily_record 
    where DAILY_RECORD_ID=?
 
Hibernate: 
    delete from mkyong.stock 
    where STOCK_ID=?

2. With delete cascade

The cascade=”delete” is declared in ‘stockDailyRecords’ to enable the delete cascade effect. When you delete the ‘Stock’, all its reference ‘stockDailyRecords’ will be deleted automatically.

 name="stockDailyRecords" cascade="delete" table="stock_daily_record" ...>
      >
             name="STOCK_ID" not-null="true" />
      >
       class="com.mkyong.common.StockDailyRecord" />
>
Query q = session.createQuery("from Stock where stockCode = :stockCode ");
q.setParameter("stockCode", "4715");
Stock stock = (Stock)q.list().get(0);
session.delete(stock);
Output
Hibernate: 
    delete from mkyong.stock_daily_record 
    where DAILY_RECORD_ID=?
 
Hibernate: 
    delete from mkyong.stock 
    where STOCK_ID=?

Cascade delete-orphan example

In above cascade delete option, if you delete a Stock , all its referenced ‘stockDailyRecords’ will be deleted from database as well. How about if you just want to delete two referenced ‘stockDailyRecords’ records? This is called orphan delete, see example…

1. No delete-orphan cascade

You need to delete the ‘stockDailyRecords’ one by one.
StockDailyRecord sdr1 = (StockDailyRecord)session.get(StockDailyRecord.class, 
                                            new Integer(56));
StockDailyRecord sdr2 = (StockDailyRecord)session.get(StockDailyRecord.class, 
                                            new Integer(57));
 
session.delete(sdr1);
session.delete(sdr2);
Output
Hibernate: 
    delete from mkyong.stock_daily_record 
    where DAILY_RECORD_ID=?
Hibernate: 
    delete from mkyong.stock_daily_record 
    where DAILY_RECORD_ID=?

2. With delete-orphan cascade

The cascade=”delete-orphan” is declared in ‘stockDailyRecords’ to enable the delete orphan cascade effect. When you save or update the Stock, it will remove those ‘stockDailyRecords’ which already mark as removed.

 name="stockDailyRecords" cascade="delete-orphan" table="stock_daily_record" >
      >
             name="STOCK_ID" not-null="true" />
      >
       class="com.mkyong.common.StockDailyRecord" />
>
StockDailyRecord sdr1 = (StockDailyRecord)session.get(StockDailyRecord.class, 
                                       new Integer(56));
StockDailyRecord sdr2 = (StockDailyRecord)session.get(StockDailyRecord.class, 
                                       new Integer(57));
 
Stock stock = (Stock)session.get(Stock.class, new Integer(2));
stock.getStockDailyRecords().remove(sdr1);
stock.getStockDailyRecords().remove(sdr2);
 
session.saveOrUpdate(stock);
Output
Hibernate: 
    delete from mkyong.stock_daily_record 
    where DAILY_RECORD_ID=?
Hibernate: 
    delete from mkyong.stock_daily_record 
    where DAILY_RECORD_ID=?
In short, delete-orphan allow parent table to delete few records (delete orphan) in its child table.

How to enable cascade ?

The cascade is supported in both XML mapping file and annotation.

1. XML mapping file

In XML mapping file, declared the cascade keyword in your relationship variable.

 name="stockDailyRecords" cascade="save-update, delete" 
        table="stock_daily_record" ...>
      >
             name="STOCK_ID" not-null="true" />
      >
       class="com.mkyong.common.StockDailyRecord" />
>

2. Annotation

In annotation, declared the CascadeType.SAVE_UPDATE (save, update) and CascadeType.REMOVE (delete) in @Cascade annotation.
//Stock.java
        @OneToMany(mappedBy = "stock")
        @Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE})
	public Set<StockDailyRecord> getStockDailyRecords() {
		return this.stockDailyRecords;
	}

hibernate - defining many to one relationship


@Entity
@Table(name="PERSON")
public class Person {
   
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name="personId")
  private int id;
   
  @ManyToOne
  @JoinColumn(name="addressId")     // inverse = false
  private Address address;
}

Sunday, March 20, 2011

Validator API (Methods)

validate

void validate(Object value)
              throws Validator.InvalidValueException
Checks the given value against this validator. If the value is valid the method does nothing. If the value is invalid, an Validator.InvalidValueException is thrown.

Parameters:
value - the value to check
Throws:
Validator.InvalidValueException - if the value is invalid

isValid

boolean isValid(Object value)
Tests if the given value is valid. This method must be symmetric with validate(Object) so that validate(Object) throws an error iff this method returns false.

Parameters:
value - the value to check
Returns:
true if the value is valid, false otherwise.

Friday, March 18, 2011

chmod Command


chmod a+r fileread is added for all
chmod a-x fileexecute permission is removed for all
chmod a+rw filechange the permissions of the file file to read and write for all.
chmod +rwx fileOn some UNIX platforms such as BSD, this will restore the permission of the file file to default: -rwxr-xr-x.
chmod u=rw,go= fileread and write is set for the owner, all permissions are cleared for the group and others
chmod -R u+w,go-w docschange the permissions of the directory docs and all its contents to add write access for the user, and deny write access for everybody else.
chmod fileremoves all privileges for all
chmod 777 filechange the permissions of the file file to read, write, and execute for all.
chmod 664 filesets read and write and no execution access for the owner and group, and read, no write, no execute for all others.
chmod 0755 fileequivalent to u=rwx (4+2+1),go=rx (4+1 & 4+1). The 0 specifies no special modes.
chmod 4755 filethe 4 specifies set user ID and the rest is equivalent to u=rwx (4+2+1),go=rx (4+1 & 4+1).
chmod -R u+rwX,g-rwx,o-rwx directoryset a directory tree to rwx for owner directories, rw for owner files, --- for group and others.
chmod -R a-x+X directoryremove the execute permission on all files in a directory tree, while allowing for directory browsing.

Tuesday, March 8, 2011

Java Date Pattern - Converting Array to List Object - Converting Date to String vise versa

Java Date Pattern


Date and Time Pattern
Result
"yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy" Wed, Jul 4, '01

"h:mm a"
12:08 PM
"hh 'o''clock' a, zzzz"12 o'clock PM, Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa"02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z"Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ"010704120856-0700

Converting Array to List Object
List list = Arrays.asList(array);



Converting Date to String
new SimpleDateFormat("format").format(dateToString);

Monday, March 7, 2011

Installing Git

mkdir ~/.ssh
cd ~/.ssh
ssh-keygen -t rsa -b 2048
(Enter a passphrase!)
chmod 700 ~/.ssh
chmod 600 ~/.ssh/*

git config --global user.name "Tekkub"
git config --global user.email "tekkub@gmail.com"

To make eclipse use git:

save as ~/.m2/settings.xml


  
    
      com.dynamicobjx.repository.internal
      dynobjx_dev
      il0vejava
      664
      775
    
  




Help > Install new software > add site :

http://download.eclipse.org/egit/updates

mysql:
create user 'test'@'localhost' identified by '3006jollibee';
grant all privileges on *.* to 'test'@'localhost';

Installing Roo

It's very easy to get started with Roo. Just follow the steps on this page and you'll have a running environment in minutes. DOWNLOAD!
Free Spring Roo Download
Download
Roo requires you to download and install:

Java 6 JDK
Apache Maven
To obtain Roo, you can either download its standalone command-line shell version or use the
version built into SpringSource Tool Suite. You can also download both and use them together if
you prefer:

Spring Roo
SpringSource Tool Suite
Install
If you downloaded the standalone Spring Roo, simply unzip it to a location of your choice. Then:

Windows users: add %ROO_HOME%\bin to your path
*nix users: create a symbolic link to $ROO_HOME/bin/roo.sh (eg sudo ln -s ~/spring-roo-1.x.x/bin/roo.sh /usr/bin/roo)

Sunday, March 6, 2011

list of dependency in maven


javax.servlet
servlet-api
2.5
provided


Sevlet Mapping


registrationServlet
com.dynamicobjx.{YOUR_NAME}.RegistrationServlet


registrationServlet
/register





org.apache.maven.plugins
maven-compiler-plugin

1.5
1.5






mysql
mysql-connector-java
5.1.15

creating a maven project with vaadin

mvn archetype:generate -DarchetypeGroupId=com.vaadin -DarchetypeArtifactId=vaadin-archetype-clean -DarchetypeVersion=LATEST -DgroupId=com.dynamicobjx -DartifactId=VaadinHelloWorld -Dversion=1.0 -Dpackaging=war

making a user a sudo user

echo 'loginname ALL=(ALL) ALL' >> /etc/sudoers

Where 'loginname' is your user account.
Use 'ALL=(ALL) NOPASSWD:ALL' if you don't want to be prompted a password.
If you are prompted for a password with 'sudo' it is the user password, not root.

Installing BoardCom Wireless

1. Install b43-fwcutter. This is the software package that does the extraction of the firmware from the proprietary driver.
Code:

su
yum install b43-fwcutter

2. Determine which native driver is being used by the wireless card (b43 or b43legacy). The kernel is generally good about detecting a Broadcom wireless card and loading the correct driver module for it. The following terminal command will list the loaded kernel modules in alphabetical order. Look for b43 or b43legacy.
Code:

lsmod | sort

3. Do this step only if you need to install version 4 firmware for the b43 driver module. Copy and execute the following command lines one after the other in a Fedora terminal.
Code:

wget http://downloads.openwrt.org/sources/broadcom-wl-4.150.10.5.tar.bz2
tar xjf broadcom-wl-4.150.10.5.tar.bz2
cd broadcom-wl-4.150.10.5/driver
su
b43-fwcutter -w /lib/firmware wl_apsta_mimo.o

4. Do this step only if you need to install version 3 firmware for the b43legacy module.
Code:

wget http://downloads.openwrt.org/sources/wl_apsta-3.130.20.0.o
su
b43-fwcutter -w /lib/firmware wl_apsta-3.130.20.0.o

5. Now reboot or restart NetworkManager and look in the NetworkManager panel applet icon for available networks (left-click the icon).

Some things to try if it doesn't work

1. Check the firmware files. There should be about three dozen .fw files in /lib/firmware/b43 (or /lib/firmware/b43legacy). If they're not there, then review the steps and re-install the firmware.
Code:

ls /lib/firmware/b43

2. Check the loaded kernel modules again. The b43 or b43legacy module should be loaded, and potentially conflicting modules such as wl or ndiswrapper should not be loaded.
Code:

lsmod | sort

3. If a conflicting module is being loaded from a previous driver effort, then either undo the steps from that previous effort, or blacklist the unwanted module. Example...
Code:

su
echo "blacklist ndiswrapper" >> /etc/modprobe.d/blacklist.conf

Wednesday, March 2, 2011

Configuring Hibernate with MySql

Requirement for:
Hibernate 3.6.1
hibernate-commons-annotations.jar
ejb3-persistence.jar
hibernate-annotations.jar

import all the jar file to your project by:
*Right Click your project.
*Build Path->Configuration Build Path
*Add External Jar then go to the location of all the jar you need to import then select it and ok.
*then Okey.

List of all the jar you need to import:
#hibernate3.jar
#ejb*-persistence.jar
#jta-*.jar
#javassist-*.jar
#antlr-*.jar
#common-collections.*.jar
#dom4j-*.jar
#slf4j-api-*.jar
#hibernate-jpa-*-api*.Final.jar
#mysql-connector-java-*-bin.jar

Create a Student that will be used for connecting to MySQL using Hibernate:


package hibernate; //the package where you class belong

/* all this class is located inside ejb*-persistence.jar */
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity //use to define a table that will use the class name as it entity name
public class Student {
//member variable definition
private String userId;
private String password;

@Id //use to define a primary key if your PK is generated (example: autoincrement) you can use @GeneratedValue Annotation
@Column //use to define a column uses PropertyName as column name (in here column name is userid
public String getUserId() //retrieve value for userid
{
return userId;
}
public void setUserId(String userId)//set value for userid
{
this.userId = userId;
}

@Column
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
//there are many other annotation you can use, you see them go to ejb3-persistance.jar then javax.persistence
}
Now let's create the hibernate.cfg.xmlfile. It must be located on the root file of your classes folder.






com.mysql.jdbc.Driver
jdbc:mysql://localhost/yourdatabasename
your_mysql_user_name
your_mysql_user_for_that_username
10
org.hibernate.dialect.MySQLDialect
true
create



Create a class that will use the Student class:

use the classes: org.hibernate.Session, org.hibernate.SessionFactory, org.hibernate.cfg.Configuration.

To insert data to a table:


SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
//get the configuration of the hibernate.cfg.xml
Session session = sessionFactory.openSessionFactory();
session.beginTransaction();
Student student = new Student();
student.setUserId("001");
student.setPassword("dynamicobjx");
session.save(student);
session.getTransaction().commit();
session.close();

Installing Spring in Eclipse

1. In Eclipse IDE, click "Help->Install New Software.." to access the plugin installation dialog box.
2. Spring IDE update site. Type "http://springide.org/updatesite" to access the Spring IDE plugins update via internet.
3. Select the Spring IDE features.
4. Restart you Eclipse IDE for the Spring IDE features to take effect.
5. Done