Showing posts with label @Column. Show all posts
Showing posts with label @Column. Show all posts

Wednesday, October 23, 2013

Primary key generation strategies in JPA(Java Persistence API)

Hi,

In this post we will discuss about generating primary key values in JPA(Java Persistence API).In general there are two strategies.A sequence number in JPA is a sequential id generated by the JPA implementation and automatically assigned to new objects

Natural id :- is like using telephone number,SSN number etc as primary keys in tables
Generated id :- where primary key value is generated by application/framework

Generated id is preferably used because data of Natural Id may change with time
There are different ways of generating primary key id's in JPA
  • Identity
  • Table
  • Sequence
  • Auto
Each one of it is described below with examples
  • IDENTITY :-Specifies the use of database identity column.@GeneratedValue annotation indicates that identifier value should be automatically created, and the specified strategy of IDENTITY indicates that an identity column should be used to generate the identifier

        @Entity
        public class Company implements Serializable {
        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private BigDecimal sno;

  • TABLE :- There are two ways of generating sequence using TABLE

    • Using default strategy:-JPA will create a default table for identifier generation,Specify the strategy of TABLE in the @GeneratedValue. JPA will create default table during schema generation at run time
      @Entity
         public class Company implements Serializable {
         private static final long serialVersionUID = 1L;
         @Id
         @GeneratedValue(strategy = GenerationType.TABLE)
         private BigDecimal sno;

    • User defined table :- We can map an existing table or tell JPA to create a table with user defined name columns etc. Generating or specifying a table will be done by using @TableGenerator annotation,after declaring the required details then we can use @GeneratedValue

      @GeneratedValue(strategy = GenerationType.IDENTITY)
      @TableGenerator(name = "javarecent_seq", table = "GEN_ID", pkColumnName = "NAME_ID", valueColumnName = "VAL_ID", pkColumnValue = "GEN_INV")
      private BigDecimal sno;
 
NAME_ID
    VAL_ID
    GEN_INV
    <Recent_Generated_Value>
      When ever a new value is required,value from VAL_ID will be picked and incremented and send that value to JPA to use.we can specify the allocationSize = "value to be incremented"

  • Sequence generator :- will create a sequence for generating unique values.Like TABLE generator JPA provides two ways
    • Default Sequence :- JPA can generate unique values for a persistence object.JPA will generate/create a default sequence object during run time and will be used for genearting unique values
      @Entity
      public class Company implements Serializable {
      private static final long serialVersionUID = 1L;
      @Id
      @GeneratedValue(strategy = GenerationType.SEQUENCE)
      private BigDecimal sno;
    • User defined sequence:- If we want to use specific sequence already created or to create and use a new one can be possible by using @SequenceGenerator annotation
      @Entity
      public class Company implements Serializable {
      private static final long serialVersionUID = 1L;
      @Id
      @GeneratedValue(strategy = GenerationType.SEQUENCE,generator="my_seq")
      @SequenceGenerator(name = "my_seq" , sequenceName="pk_generator", allocationSize=3)
      private BigDecimal sno;
In above example a example a sequence is generated if not present with name pk_generator and each time a new value will be created with an increment of 3 as specified in allocationSize ,this sequence is named as my_seq and used in @GeneratedValue

  • AUTO :- Indicates that JPA will pick the appropriate generation strategy for a particular database,there is no gaurentee that generated values will be in sequence,by default TABLE strategy is picked as this is the mosdt portable approach which is supported by all databases
        @Entity
        public class Company implements Serializable {
        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private BigDecimal sno;

    Common Problems
    Error when allocating a sequence number.
  1. Errors such as "table not found","invalid column" can occur if you do not have a SEQUENCE table defined in your database, or its schema does not match what you have configured, or what your JPA provider is expecting by default. Ensure you create the sequence table correctly, or configure your @TableGenerator to match the table that you created, or let your JPA provider create you tables for you (most JPA provider support schema creation). You may also get an error such as "sequence not found", this means you did not create a row in the table for your sequence. You must insert an initial row in the sequence table for your sequence with the initial id (i.e. INSERT INTO SEQUENCE_TABLE (SEQ_NAME, SEQ_COUNT) VALUES ("EMP_SEQ", 0)), or let your JPA provider create your schema for you.
  2. If there is any issue using TABLE sequence creation in JPA.We need to first change/check the persistence.xml file
    Specify <property name="eclipselink.ddl-generation" value="create-tables"/>



                         Happy Learning

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


Contact me @ sudheer.reddy@live.com or admin@java-recent.com

Sunday, August 4, 2013

Internationalization(i18n) and Localization(L10N)

Internationalization(i18n):-The process of preparing an application to support more than one language and to represent data in different formats.There are 18 letters between i and n so will refer as i18n

Localization(L10N): -The process of adapting an internationalized application to support a specific region or locale
Lets take an example of Facebook which supports multiple languages like Engilish,Portugal,Hindi etc.
This can be achieved in JSF by using resource bundle.

Steps to Internationalization :-
  • Create a JSF web application in Eclipse
    • Open work space
    • Then New-->Create dynamic web application
    • Select run time environment like Tomcat etc.
    • Place JSF related libraries/Jars into build path(Ex:- ApacheMyFaces.lib etc.)
  • Create a resource bundle :- generally they will be .properties files,where we write text for different languages
  • Loading resource bundle :- There are two ways of implementing
    • faces-config.xml :- use <resource-bundle> is used to i18n for entire application
    • <f:loadBundle> :- is used to i18n for a particule web page

We will now implement i18n and L10N in a web application. We have a login page which supports English and French languages.Text related to this are placed in .properties file
  1. Create two .properties file one for English and One for French languages.Place them under src folder
    ApplicationResource.properties
    LoginId: Login Id:
    Password: Password:
    Login: Login
    Reset: Reset
ApplicationResource_fr.properties
LoginId: Identification d'ouverture :
Password: Mot de passe :
Login: Ouverture
Reset: Remettre à l'état initial
  1. Now we will use this resources in faces-config.xml .We can do this from GUI of faces-config.xml

<application>
<resource-bundle>
<base-name>ApplicationResource</base-name>
<var>msg</var>
</resource-bundle>
<locale-config>
<default-locale>en</default-locale>
<supported-locale>fr_FR</supported-locale>
</locale-config>
</application>
  1. Create a ManagedBean-LoginBean.java and register it in faces-config.xml . We can do this from GUI of faces-config.xml
    LoginBean.java
import java.util.Locale;
import javax.faces.context.FacesContext;

public class LoginBean {
private String uName;
private String password;

public String getuName() {
return uName;
}

public void setuName(String uName) {
this.uName = uName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}
public String changeFrench()
{
FacesContext.getCurrentInstance().getViewRoot().setLocale(Locale.FRENCH);
return "";
}
}

Explanation :-
In LoginBean.java we have a method changeFrench() which will take care of getting text from properties file and converting it into respective language
FacesContext.getCurrentInstance().getViewRoot().setLocale(Locale.FRENCH);
The above statement is used change language to French
  1. Login.jsp

<f:view>
<h:form>
<h:outputText value="#{msg.LoginId}">
</h:outputText>
<h:inputText value="#{loginBean.uName }"></h:inputText>
<br>
<h:outputText value="#{msg.Password}"></h:outputText>
<h:inputText value="#{loginBean.password }"></h:inputText>
<br>
<h:commandButton value="#{msg.Login}"></h:commandButton>
<h:commandButton value="#{msg.Reset}"></h:commandButton>
<h:commandLink action="#{loginBean.changeFrench }">
<h:outputText value="French"></h:outputText>
</h:commandLink>
</h:form>
</f:view>

Here we have used #{msg.LoginId} etc. statements. The variable msg is declared in faces-config.xml .
Now run the application .By default the page will be in english for converting into French click on link French.
Screenshot of Login.jsp in English :-

Click on French the method changeFrench in LoginBean will get called and converts the text into French


If we want to do it for a specific jsp page we can use
<f:loadBundle var="msg" basename="ApplicationResource"/> after <f:view> tag
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.



Like and Share