Hibernate Transaction handle example

In Hibernate, the transaction management is quite standard, just remember any exceptions thrown by Hibernate are FATAL, you have to roll back the transaction and close the current session immediately. Here’s a Hibernate transaction template : Session session = null; Transaction tx = null; try{ session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); tx.setTimeout(5); //doSomething(session); tx.commit(); }catch(RuntimeException …

Read more

How to know from where a Class was loaded in Java

Here’s a tip to demonstrate how to know from where a Java Class was loaded in Java. Java Example Here’s an example to load a Java class called “Address “, package in “com.mkyong.io“, and print out the location from where this class was loaded. import java.net.URL; import java.security.CodeSource; import java.security.ProtectionDomain; public class App{ public static …

Read more

Hibernate – Many-to-Many example (XML Mapping)

Many-to-many relationships occur when each record in an entity may have many linked records in another entity and vice-versa. In this tutorial, we show you how to work with many-to-many table relationship in Hibernate, via XML mapping file (hbm). Note For many to many with extra columns in join table, please refer to this tutorial. …

Read more

How to prevent others steal your web image (hotlinking)

My website’s images are kept directly link (hotlinking) by other websites, it’s a thief behavior and eating my bandwidth, why don’t they copy to their own server and display it? I decided to take action to stop this happened again, this so called “hotlinking” can be stopped by “.htaccess” access control. Case Study 1. Hotlinking …

Read more

Different between cascade and inverse

Many Hibernate developers are confuse about the cascade option and inverse keyword. In some ways..they really look quite similar at the beginning, both are related with relationship. Cascade vs inverse However, there is no relationship between cascade and inverse, both are totally different notions. 1. inverse This is used to decide which side is the …

Read more

Different between session.get() and session.load()

Often times, you will notice Hibernate developers mix use of session.get() and session load(), do you wonder what’s the different and when you should use either of it? Different between session.get() and session.load() Actually, both functions are use to retrieve an object with different mechanism, of course. 1. session.load() It will always return a “proxy” …

Read more

Hibernate – One-to-One example (XML Mapping)

A one-to-one relationships occurs when one entity is related to exactly one occurrence in another entity. In this tutorial, we show you how to work with one-to-one table relationship in Hibernate, via XML mapping file (hbm). Tools and technologies used in this tutorials : Hibernate 3.6.3.Final MySQL 5.1.15 Maven 3.0.3 Eclipse 3.6 Project Structure See …

Read more

Hibernate – Cascade example (save, update, delete and delete-orphan)

Cascade is a convenient feature to save the lines of code needed to manage the state of the other side manually. The “Cascade” keyword is often appear on the collection mapping to manage the state of the collection automatically. In this tutorials, this one-to-many example will be used to demonstrate the cascade effect. Cascade save …

Read more

Hibernate – One-to-Many example (XML Mapping)

A one-to-many relationship occurs when one entity is related to many occurrences in another entity. In this tutorial, we show you how to works with one-to-many table relationship in Hibernate, via XML mapping file (hbm). Tools and technologies used in this tutorials : Hibernate 3.6.3.Final MySQL 5.1.15 Maven 3.0.3 Eclipse 3.6 Project Structure Project structure …

Read more

inverse = “true” example and explanation

Always put inverse=”true” in your collection variable ? There are many Hibernate articles try to explain the “inverse” with many Hibernate “official” jargon, which is very hard to understand (at least to me). In few articles, they even suggested that just forget about what is “inverse”, and always put inverse=”true” in the collection variable. This …

Read more

How to define one-to-one relationship in MySQL

One-to-one relationships occur when there is exactly one record in the first table that corresponds to exactly one record in the related table. MySQL does not contains any “ready” options to define the one-to-one relationship, but, if you want to enforce it, you can add a foreign key from one primary key to the other …

Read more

Hibernate – dynamic-update attribute example

What is dynamic-update The dynamic-update attribute tells Hibernate whether to include unmodified properties in the SQL UPDATE statement. Dynamic-update example 1. dynamic-update=false The default value of dynamic-update is false, which means include unmodified properties in the Hibernate’s SQL update statement. For example, get an object and try modify its value and update it. Query q …

Read more

Hibernate – dynamic-insert attribute example

What is dynamic-insert The dynamic-insert attribute tells Hibernate whether to include null properties in the SQL INSERT statement. Let explore some examples to understand more clear about it. Dynamic-insert example 1. dynamic-insert=false The default value of dynamic-insert is false, which means include null properties in the Hibernate’s SQL INSERT statement. For example, try set some …

Read more

How to read an image from file or URL

The “javax.imageio” package is used to deal with the Java image stuff. Here’s two “ImageIO” code snippet to read an image file. 1. Read from local file File sourceimage = new File("c:\\mypic.jpg"); Image image = ImageIO.read(sourceimage); 2. Read from URL URL url = new URL("https://mkyong.com/image/mypic.jpg"); Image image = ImageIO.read(url); ImageIO Example In this example, you …

Read more

How to decompress serialized object from a Gzip file

In last section, you learn about how to compress a serialized object into a file, now you learn how to decompress it from a Gzip file. FileInputStream fin = new FileInputStream("c:\\address.gz"); GZIPInputStream gis = new GZIPInputStream(fin); ObjectInputStream ois = new ObjectInputStream(gis); address = (Address) ois.readObject(); GZIP example In this example, you will decompress a compressed …

Read more

How to compress serialized object into file

In last section, you learn about how to write or serialized an object into a file. In this example , you can do more than just serialized it , you also can compress the serialized object to reduce the file size. The idea is very simple, just using the “GZIPOutputStream” for the data compression. FileOutputStream …

Read more

What is the different between Set and List

Set and List explanation Set – Stored elements in unordered or shuffles way, and does not allow duplicate values. List – Stored elements in ordered way, and allow duplicate values. Set and List Example import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class SetAndListExample { public static void main( String[] args ) { System.out.println("List …

Read more

How to find files with the file extension in Java

This article shows how to Java 8 Files.walk to walk a file tree and stream operation filter to find files that match a specific file extension from a folder and its subfolders. // find files matched `png` file extension from folder C:\\test try (Stream<Path> walk = Files.walk(Paths.get("C:\\test"))) { result = walk .filter(p -> !Files.isDirectory(p)) // …

Read more

Java Properties file examples

Normally, Java properties file is used to store project configuration data or settings. In this tutorial, we will show you how to read and write to/from a .properties file. Properties prop = new Properties(); // set key and value prop.setProperty("db.url", "localhost"); prop.setProperty("db.user", "mkyong"); prop.setProperty("db.password", "password"); // save a properties file prop.store(outputStream, ""); // load a …

Read more

How to get a Java Class Object

As far as i know, there are 4 ways to get the Java Class object. 1. “.class” Class cls = Address.class; 2. object.getClass() Address address = new Address(); Class cls = address.getClass(); 3. Class.forName() Class cls = Class.forName("com.mkyong.io.Address"); 4. ClassLoader.loadClass() ClassLoader cl = ClassLoader.getSystemClassLoader(); Class cls = cl.loadClass("com.mkyong.io.Address");

How to make a Java exe file or executable JAR file

In this tutorial, we will show you how to create a executable JAR – When you double click on it, it runs the defined main class in manifest file. 1. AWT Example Create a simple AWT Java application, just display label and print out some funny characters ~ AwtExample.java package com.mkyong.awt; import java.awt.Frame; import java.awt.Label; …

Read more

How to compare dates in Java

This article shows few examples to compare two dates in Java. Updated with Java 8 examples. 1. Compare two date 1.1 Date.compareTo 1.2 Date.before(), Date.after() and Date.equals() 1.3 Check if a date is within a certain range 2. Compare two calendar 3. Compare two date and time (Java 8) 3.1 Compare two LocalDate 3.2 Compare …

Read more

Jar manifest error – java.io.IOException: invalid header field

Often times, this error is causing by the mismatch order between “m” and “f” Jar options. For example, jar -cvfm manifest.txt example.jar com/mkyong/awt/*.class The above command will causing the following error : java.io.IOException: invalid header field at java.util.jar.Attributes.read(Attributes.java:406) at java.util.jar.Manifest.read(Manifest.java:199) at java.util.jar.Manifest.<init>(Manifest.java:69) at sun.tools.jar.Main.run(Main.java:150) at sun.tools.jar.Main.main(Main.java:1044) Did you spot the error? The “m” and “manifest” …

Read more

Java StringTokenizer examples

In Java, we use StringTokenizer to split a string into multiple tokens. Note The StringTokenizer is a legacy class, try the split method of String, read this How to split a string in Java. 1. StringTokenizer examples 1.1 By default, the StringTokenizer uses default delimiters: space, tab, newline, carriage-return, and form-feed characters to split a …

Read more

How to read and write an image in Java

In Java, we can use the javax.imageio.ImageIO class to read and write an image. 1. Read an image Read an image from a file. BufferedImage image = ImageIO.read(new File("c:\\test\\image.png")); Read an image from an URL. BufferedImage image = ImageIO.read(new URL("https://example.com/image.png")); 2. Write or save an image Write or save an image in different image formats. …

Read more

The Java Archive Tool (JAR) Examples

Here’s the project structure. /workspace/test/classes/com/mkyong/awt/AwtExample.class /workspace/test/classes/com/mkyong/awt/AwtExample2.class /workspace/test/classes/com/mkyong/awt/AwtExample3.class /workspace/test/classes/manifest.txt P.S Assume you are in “/workspace/test/classes/“ 1. Create a jar file -c create new archive -v generate verbose output on standard output -f specify archive file name 1.1 Create a Jar file which include AwtExample.class only. jar -cvf test.jar com/mkyong/awt/AwtExample.class 1.2 Create a Jar file which include …

Read more

How to list out all system drives in your system

File.listRoots() will list out all the available file system roots / drives in your current system. Example package com.mkyong.io; import java.io.File; public class App{ public static void main (String args[]) { File[] rootDrive = File.listRoots(); for(File sysDrive : rootDrive){ System.out.println("Drive : " + sysDrive); } } } Output Drive : A:\ Drive : C:\ Drive …

Read more

Java – What is serialVersionUID

In Java, serialVersionUID is something like version control, assure both serialized and deserialized objects are using the compatible class. For example, if an object saved into a file (Serialization) with serialVersionUID=1L, when we convert the file back to an object (Derialization), we must use the same serialVersionUID=1L, otherwise an InvalidClassException is thrown. Terminal Exception in …

Read more

Java – How to generate serialVersionUID

This article shows you a few ways to generate the serialVersionUID for serialization class. 1. serialver JDK has a built-in command serialver to generate a serialVersionUID automatically. In this example, we use serialver to generate a serialVersionUID for an Address class. Terminal $ serialver Address Address: static final long serialVersionUID = -687991492884005033L; 2. Eclispe IDE …

Read more

How to load classes which are not in your classpath

In certain scenario, you may need to load some classes which are not in your classpath. Java Example Assume folder “c:\\other_classes\\” is not in your project classpath, here’s an example to show how to load a Java class from this folder. The code and comments are self-explanatory. import java.io.File; import java.net.URL; import java.net.URLClassLoader; import java.security.CodeSource; …

Read more

How to add a manifest into a Jar file

In Java, you can use manifest file to define application’s entry point, adding classpath or package version for a JAR file. In this short tutorial , we will show you how to add a custom manifest file into a Jar file. 1. Project Structure Assume this is your project folder structure /workspace/test/classes/com/mkyong/awt/AwtExample.class /workspace/test/classes/manifest.txt 2. Jar …

Read more

Constant value should always come first in comparison

Normal practice Constant value comes second in comparison. private static final String COMPARE_VALUE = "VALUE123"; public boolean compareIt(String input){ if(input.equals(COMPARE_VALUE)){ return true; }else{ return false; } } Problem This is fine to compare a constant value with the above method, however it will potentially causing a NullPointerException, if user pass a “null” value for the …

Read more

How to run a Java application with no main method

Java application usually required a main() method as entry point to run it. Here’s an example by using static initializer to run a Java application even without the main() method. P.S The static initializer is called while the Java class is loaded. This is for fun only, do not use this example in real environment …

Read more