Showing posts with label JPA. Show all posts
Showing posts with label JPA. Show all posts

Sunday, October 27, 2013

Named and Native Queries in JPA

Named  and Native Queries in JPA :-
  • Named queires are reusable and can be declared at Entity level
  • @NamedQuery annotation is used
  • multiple named queries are declared in @NamedQueries
  • For executing native queries we use @NamedNativeQueries

@NamedQuery :-
@NamedQuery(name = "allCompanyDetails", query = "SELECT c FROM Company c")

Named query is called by using query = em.createNamedQuery("allCompanyDetails");

@NamedQueries :- annotation is used for declaring multiple named queries at entity level
In the below snippet we have two named queries-"allCompanyDetails" and "onlyMailIds"

@NamedQueries({ @NamedQuery(name = "allCompanyDetails", query = "SELECT c FROM Company c"),
@NamedQuery(name="onlyMailIds",query="SELECT c.mail FROM Company c")
})

Native Queries are used to execute SQL statements directly and to call procedures and functions from JPA
@NamedNativeQueries :-
@NamedNativeQuery(name = "nativeQueryEx", query = "select * from company")

entityManager.createNativeQuery("query") is used to execute native queries

Similar to SQL in JPQL we can write join queries etc,instead of Table names we use Entity class names

Query query = em.createQuery("SELECT c from Company c,Department d where c.mail= d.mail and c.name LIKE 'T%'");

Saturday, October 26, 2013

Persistence.xml file in JPA

Persistence.xml 
How will JPA API (EntityManager)  come to know which database to connect, connection parameters,transaction types,logging level etc.? Persistence.xml is a standard configuration file which gives complete flexibility to configure EntityManager

Persistence.xml :-
  1. is to be created under META-INF/persistence.xml
  2. A persistence.xml can contain one or more unique persistence unit names
  3. Persistence units are unique values used by EntityManagerFactory/Entitymanager
  4. Entities ,Connection parameters,logging level ,transaction types etc are declared in persistence.xml

EntityManagerFactory emf =Persistence.createEntityManagerFactory("JPAExample_Toplink");

The following persistence.xml defines one persistence unit with name JPAExample_Toplink

<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

<persistence-unit name="JPAExample_Toplink"
transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>model.Company</class>
<class>model.Department</class>
<class>model.DeptEmpl</class>

<properties>
<property name="javax.persistence.jdbc.password" value="admin" />
<property name="javax.persistence.jdbc.user" value="system" />
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@localhost:1521:XE" />
<property name="eclipselink.logging.level" value="INFO" />
<property name="eclipselink.ddl-generation" value="create-tables" />
</properties>
</persistence-unit>
</persistence>

Eclipse automatically creates persistence.xml file when we create a JPA project.It also provides an persistence xml file editor which reduces the manual effort of writing the file.
We can edit :-
Connection
Managed classes
mapping files
Query timeouts









                         Happy Learning

Please provide your valuable comments on this article and share it across your network.


Contact me @ sudheer@javarecent.com orjavarecent@gmail.com

Tuesday, August 6, 2013

Implementing Custom converters in Java Server Faces(JSF)

Custom converters :-
Java Server Faces provides set of standard converters but in some cases we need to implement our own converters.
We want to be date in a particular format or emailId should be of specific format etc.
We can implement this by using java script but if java script is disabled? So its always recommended to perform server side validations.

Steps to be followed for creating custom converters :-
  1. Create a Java class
  2. Implement javax.faces.convert.Converter
  3. Override the unimplemented methods getAsObject(FacesContext,UIComponent,String),getAsString(FacesContext,UIComponent,String)
Example :-

public class CustomConverter implements Converter {

@Override
public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2)
throws ConverterException {
// TODO Auto-generated method stub
return null;
}

@Override
public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2)
throws ConverterException {
// TODO Auto-generated method stub
return null;
}

}


As we get data from web page in form of String all the conversion
is done in getAsObject();

4.Registering custom converter class in faces-config.xml
<converter>
<description>Removes white spaces in the input</description>
<display-name></display-name>
<converter-id>cc</converter-id>
<converter-class>CustomConverter</converter-class>
</converter>

This can be done by component tab in faces-config.xml instead of writing the above lines.

The above converter can be implemented by using
1.Converter attribute :-
<h:inputText id="number" value="#{loginBean.num}" converter="cc">
</h:inputText>

  1. Using Converter tag nested inside the component tag
<h:inputText id="number" value="#{loginBean.num}">
<f:converter id="cc"/>
</h:inputText>


Happy Learning

Please provide your valuable comments on this article and share it across your network.


Sunday, August 4, 2013

Passing values to methods in Java-Primitives and Objects

In this post we will discuss about how method calling ,value passing happens in Java.

1.Passing Object reference variables to a method :-
  • when we pass an object to a method we are not actually passing object itself, we are passing object reference
  • Reference variable holds the address location of object and a way to load into memory
  • We are not passing actual reference variable,but a copy of reference variable-which holds the copy of bits present in actual value

Lets see below code snippent

Employee emp1=new Employee();
method1(emp1);
void method1(Employee emp)
{
}
Here both emp1 and emp point to same Employee Object in heap.

Example1 :-

public class ObjectReference {
private int var1;
private int var2;

public ObjectReference(int x, int y) {
var1 = x;
var2 = y;
}

public static void main(String[] args) {
ObjectReference op = new ObjectReference(5, 10);
System.out.println("before modify " + op.var1 + "&&" + op.var2);
op.modify(op);
System.out.println("after modify " + op.var1 + "&&" + op.var2);
}

void modify(ObjectReference pop) {
pop.var1 = pop.var1 + 10;
pop.var2 = pop.var2 + 10;
System.out.println("in modify " + pop.var1 + "&&" + pop.var2);
}
}



Output :-
before modify 5&&10
in modify 15&&20
after modify 15&&20

Here both op and pop reference variables are referring to same ObjectReference object .If one reference variable tries to change the value autotically it gets reflected to another varaible.

In the above example in change method we changed the value of var1 and var2 and when we print the value in main method it got reflected.
Now lets see what happens in case of primitive data types.

2.Passing primitive variables to a method :-
When we are passing primitive values to a method we are actually passing copy of bits that represent a value.Suppose we have int a=5,when we pass a to a method we are actually passing copy of bits of value 5. For this we use a terminology passbyvalue rather its passbycopyofvalue .

Example :-
public class PrimitivePass {
int a = 10;

public static void main(String[] args) {
PrimitivePass pp = new PrimitivePass();
System.out.println("Before change" + pp.a);
pp.change(pp.a);
System.out.println("After change" + pp.a);
}

void change(int pNum) {
pNum = pNum + 10;
System.out.println("in change" + pNum);
}
}

output :-
Before change10
in change20
After change10

From the output we can observe that value of a is not changed ,but in previous case we observed for object references the value has changed.

Note :-
  • While passing an Object we actually pass copy of the object reference
  • While passing a primitive type we pass the bits value stored in that variable
  • In both the cases we send copy of bits,in primitives actual value is stored but in case of Object reference it stores the address of the object

Happy Learning

Please provide your valuable comments on this article and share it across your network.



Saturday, July 27, 2013

Basic Annotations in Java Persistence API(JPA)

Hi,

Today we will discuss some of the basic JPA annotations.

Annotations :-
  • @Table
  • @Column
  • @Temporal
  • @Transient

Lets consider below table -Company

    SNO
  • NAME
    MAIL
    1
  • Google
  • google@gmail.com
    2
  • Yahoo
  • yahoo@yahoo.com
    3
  • Microsoft
  • microsoft@live.com

1.@Table :-is used to map your entity java bean with the table
In general your table name and entity bean will have same name at that time there is no need to use @Table
If the Entity bean is different from the table name we map it by using @Table annotation

Example :-
Lets take the above table-Company ,but my entity bean name is named as Organization  then we can use @Table to map them

@Entity
@Table(name="Company")
Public class Organization{.......}


2.@Column :- is used to map an instance variable with a column in a table
If the variable name and database column name is same ,then there is no need to use column
This is similar to @Table

Example :-
Lets take the data base column -Name in the above table
In Entity bean we have companyName.so how to map them?

@Column(name="Name")
Private String companyName;

3.@Temporal :-
  • In Java we have java.util.Date and java.util.Calendar classes,if we wnat to persist them into data base we should use @Temporal
  • Temporal are set of time based types
Example :-
@Temporal(TemporalType.DATE)
Date currentDate;

In Entity                                                                   Mapped to data base
  • TemporalType.DATE
  • Mapped to java.sql.Date
  • TemporalType.TIME
  • Mapped to java.sql.Time
  • TemporalType.TIMESTAMP
  • Mapped to java.sql.Timestamp

4.@Transient :-
  • Attributes that are part of Entity but should not be persisted should be marked as @Transient
  • Suppose we have a attribute lastName and should not be persisted to data base,we use@Transient
Example :-
@Transient
private String lastName;

There are many annotations in JPA,each one of them has special functionality which i will discuss in my later posts


Happy Learning

Please provide your valuable comments on this article and share it across your network.



Thursday, July 4, 2013

Introduction to Entity beans in Java Persistence API (JPA)

Hi All,

In this post we will discuss about Java Persistence API(JPA) entity bean.

Lets have a brief introduction about JPA.
JPA is a Java data base framework which eases interaction with database by providing following features
  1. Java Persistence Query language (JPQL)
  2. Object relational mapping
  3. Providing annotation etc.
The most important aspect in JPA is a Java bean class .
Bean in Java is a simple class with properties and their getter and setter methods

In JPA we call this bean with a special name called as Entity.

Entity Bean :- is an exact replica of a table in a database,it is independent of database used.
  • The mapping between a Entity Bean and data base table is configured in persistence.xml file
  • There are different types of annotations(@) which helps in representing primary keys,table name etc.
  • Annotation are in simple metadata(Data about Data),they give extra information to compiler
  • A normal Java bean can be converted into a Entity by using @Entity annotation
we will discuss more about annotations in upcoming posts.

In this post we will see how to write a Entity Bean

Environment used :-
  • Eclipse Juno
  • Oracle
  • JPA 2.0 jars
Lets have below COMPANY table in data base

    SNO
  • NAME
    MAIL
    1
  • Google
  • google@gmail.com
    2
  • Yahoo
  • yahoo@yahoo.com
    3
  • Microsoft
  • microsoft@live.com

Now we will write a Entity class for the same. In Eclipse its simple to create most of the required code will be auto generated.
  1. Switch to JPA perspective in Eclipse
  2. Configure data base connection by using Data Source Explorer view(window-->Show view-->Data Source Explorer)
  3. Create a JPA project(File—New-->Create JPA project)
  4. Open the project,in JPA content you will find persistence.xml file
  5. Now select the project click on new-->others--JPA Entity from tables
  6. Select the data base connection , schema configured in step 2 and select tables that you want to generate Entities
  7. Click the check box-- update in persistence.xml
  8. Select a primary key generator type like Auto etc(Not mandatory) continue and click finish
Lets see the code that gets generated for COMPANY table


@Entity
public class Company implements Serializable {
private static final long serialVersionUID = 1L;

@Id
private BigDecimal sno;
private String mail;
private String name;
public Company() {
}

public String getMail() {
return this.mail;
}

public void setMail(String mail) {
this.mail = mail;
}

public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

public BigDecimal getSno() {
return this.sno;
}

public void setSno(BigDecimal sno) {
this.sno = sno;
}

}


Explanation :-

Here we need to take a look at two annotations

  1. @Entity :- Gives a identification for a normal Java bean as entity
  2. @Id :- Indicates the primary key in the table

Here we have three properties and their getter and setter methods,we will be accessing (setting/retrieving )the properties by using these methods.

There are lot more annotations available for various purposes will explain in details in my upcoming posts.

Now have a look at persistence.xml, we will find the Entity class added.

                         Happy Learning

Please provide your valuable comments on this article and share it across your network.


Like and Share