Stanislav Zorjan - Stasha - Full Stack Software Engineer and Game Development Hobbyist - Prague


1. Java - Primitives
2. Java - Strings
3. Java - Arrays
4. Java - Date
5. Java - Generics
6. Java - Collections
7. Java - Localization
8. Java - Formatting
9. Java - Regular Expressions
10. Java - System
11. Java - Serialization
12. Java - Multithreading
13. Java - IO/File
14. Java - Networking
15. Java - ORM - JPA
      a) Simple User entity class

 

 

package jpa;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/** ****************************************************************************
 * JAVA PERSISTENCE API EXAMPLE
 * 
 * JPA Reference: http://www.objectdb.com/api/java/jpa/annotations/class
 * JPA Performance Benchmark: http://www.jpab.org/All/All/All.html 
 * JPA Cheat sheet: http://refcardz.dzone.com/refcardz/getting-started-with-jpa
 * 
 * 
 * @author stanislav.zorjan
 */
public class Main {
    
    private EntityManagerFactory ef = Persistence.createEntityManagerFactory("javaOzonePU");
    private EntityManager em = ef.createEntityManager();
    private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    
    
    /** ************************************************************************
     * main point
     * @param args 
     */
    public static void main(String args[]){
	Main m = new Main();
    }

    /** ************************************************************************
     * Default constructor
     */
    public Main() {
	inputAddUser();
	//inputFindUser();
	
	//getAllUsers();
	//findUserByFirstName("Stanislav");
	//findUserByLastName("Zorjan");
	//findUserByAddress("Matije");
	//updateUserFirstName(3, "Stanislavski");
	//deleteUserByID(1);
    }
    
    
    /** ************************************************************************
     * Method getting input data from console
     */
    private void inputAddUser(){
	try {
	    System.out.println("Please enter first name:");
	    String firstName = br.readLine();
	    System.out.println("Please enter last name");
	    String lastName = br.readLine();
	    System.out.println("Please enter address");
	    String address = br.readLine();
	    
	    insertUser(firstName, lastName, address);
	    
	    System.out.println("Do you want to add another user? y/n");
	    
	    if(br.readLine().toLowerCase().equals("y")){
		inputAddUser();
	    }else{
		em.close();
		ef.close();
	    }
	    
	} catch (IOException ex) {
	    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
	}
    }
    
    /** ************************************************************************
     * Method for finding users
     */
    private void inputFindUser(){
	System.out.println("Find user by:\n1. ID\n2. First Name\n3. Last Name\nEnter number 1-3");
	try {
	    Integer choice = Integer.parseInt(br.readLine());
	    
	    switch(choice){
		case 0:
		    getAllUsers();
		    break;
		case 1:
		    System.out.println("Enter ID of the user:");
		    Integer id = Integer.parseInt(br.readLine());
		    findUserByID(id);
		    break;
		case 2:
		    System.out.println("Enter Name of the user:");
		    String firstName = br.readLine();
		    findUserByFirstName(firstName);
		    break;
		case 3:
		    System.out.println("Enter Name of the user:");
		    String lastName = br.readLine();
		    findUserByFirstName(lastName);
		    break;
	    }
	    
	} catch (IOException ex) {
	    System.out.println("Please enter a number between 1-3");
	    inputFindUser();
	} finally{
	    try {
		System.out.println("\nDo you want to find another user? y/n");
		if(br.readLine().toLowerCase().equals("y")){
		    inputFindUser();
		}else{
		    em.close();
		    ef.close();
		}
	    } catch (IOException ex) {
		Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
	    }
	}
    }
    
    /** ************************************************************************
     * Method for inserting user into db
     * @param firstName
     * @param lastName
     * @param address
     */
    private void insertUser(String firstName, String lastName, String address){
	User u = new User();
	u.setFirstName(firstName);
	u.setLastName(lastName);
	u.setAddress(address);
	
	em.getTransaction().begin();
	em.persist(u);
	em.getTransaction().commit();
    }
    
    /** ************************************************************************
     * Getting all users by using named query from User class
     */
    private void getAllUsers(){
	Query q = em.createNamedQuery("User.findAll");
	List list = q.getResultList();
	System.out.println(Arrays.toString(list.toArray()));
    }
    
    /** ************************************************************************
     * Getting user by ID
     */
    private void findUserByID(Integer id){
	User u = (User) em.find(User.class, id);
	System.out.println(u.toString());
    }
    
    /** ************************************************************************
     * Getting user by it's first name using named query from User class
     * @param firstName 
     */
    private void findUserByFirstName(String firstName){
	Query q = em.createNamedQuery("User.findByFirstName");
	q.setParameter("firstName", firstName);
	System.out.println(Arrays.toString(q.getResultList().toArray()));
    }
    
    /** ************************************************************************
     * Getting user by it's last name using named query from User class
     * @param lastName 
     */
    private void findUserByLastName(String lastName){
	Query q = em.createQuery("SELECT c FROM User c WHERE c.lastName = :lastName");
	q.setParameter("lastName", lastName);
	System.out.println(Arrays.toString(q.getResultList().toArray()));
    }
    
    /** ************************************************************************
     * Getting user by it's address using native query
     * @param address 
     */
    private void findUserByAddress(String address){
	Query q = em.createNativeQuery("SELECT * FROM users WHERE address LIKE \"%"+address+"%\"", User.class);
	List l = q.getResultList();
	System.out.println(Arrays.toString(l.toArray()));
    }
    
    /** ************************************************************************
     * Updating user by id
     * @param ID 
     */
    private void updateUserFirstName(Integer ID, String firstName){
	Query q = em.createQuery("UPDATE User c SET c.firstName = :firstName WHERE c.id = :id");
	q.setParameter("id", ID);
	q.setParameter("firstName", firstName);
	em.getTransaction().begin();
	int status = q.executeUpdate();
	em.getTransaction().commit();
	System.out.println("update status: " + status);
    }
    
    /** ************************************************************************
     * Deleting user by id
     * @param ID 
     */
    private void deleteUserByID(Integer ID){
	Query q = em.createQuery("DELETE FROM User c WHERE c.id = :id");
	q.setParameter("id", ID);
	em.getTransaction().begin();
	int status = q.executeUpdate();
	em.getTransaction().commit();
	System.out.println("update status: " + status);
    }
}