Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, February 14, 2018

Data Types in java


Java is a Strongly Typed Language:-


 It is important to state at the outset that Java is a strongly Typed language. Indeed,part of Java's safety and robustness comes from this fact. Let's see what
this means. First,every variable has a type, every expression has a type,and every type is strictly defined, Second, all assignments, whether explicit or via parameter passing in method c calls, are checked for type compatibility. There are no automatic corecions or conversions of conflicting types as in some languagees.The Java compile checks all expressions and parameters to ensure that the types are compatible. Any type mismatches are errors that must be corrected before the compiler will compiling the class.

The Primitive Types:-


Java Defines eight primitive types of data:

byte,short,int,long,char,float,double,and boolean. The primitive types are also commonly referred to as simple types,and both terms will be used in this book.These can be put in four groups.

* Integers:- This group includes byte,short,int and long, which are for whole-valued signed numbers.

* Floating-Point Numbers:- This group includes float and double, which represent numbers with fractional precision.

* Characters:-
  This group includes char,which represents symbols in a character set, like letters and numbers.

* boolean:- This group includes boolean,which ia a special type for representing true/fasle values.

The primitive types represent single values-not complex objects. Although Java is otherwise completely object-oriented, the primitive types are not. They are analogous to the simple types found in most other non-object-oriented langauges. The reason for this is efficiency. Making the primitive types into objects would have degraded performance
too much.


Friday, February 9, 2018

A First Simple HelloWorld Program In Java

In this post i have explain the simple HelloWorld program in java .
/*
This is a simple Java program.
Call this file "HelloWorld.java".
*/
class HelloWorld {
// Your program begins with a call to main().
        public static void main(String args[]) {
                   System.out.println("This is a simple HelloWorld Java program.");
         }
}


Entering The Program :-

For most computer languages, the name of the file that holds the source code to a program is immaterial. However,this is not case of Java. The first thing you must learn about java is that the name you give to a source file is very important. For this example ,the name of the source file should be HelloWorld.java

Let's see why..


In Java, a source file is official called a compilation unit. it is a text file that contains one or more class definitions.(For now,we will be using source file that contain only one class)
The Java compiler requires that a source file use the .java file name extension.

As you can see by looking at the program,the name of the class defined by the program is also HelloWorld. This is not a coincidence.In Java, all code must be  inside a class.
By convention,the name of the main class should match the name of the file that holds the program. You should also make sure that the capitalization of the file name matches the class name.
The reason for this is that java is case-sensitive.At this point,the convention that file names correspond to class name may seem arbitrary.However,this contention makes it easier to maintain
and organize your programs.

Compiling the program :-

To compile the HelloWorld program,execute the compiler,javac,specifying the name of the source file on the command line, as shown here :
c:\>javac HelloWorld.java

The javac compiler creates a file called HelloWorld.class that contains the bytecode version of the program. The java bytecode is the intermediate representation of your programs that contains instructions the Java Virtual Machine will execute.

To actually run the program,you must use the Java application launcher called java. To do so,pass class name HelloWorld as a command-line argument, as shown here:
c:\> java HelloWorld

When the program is run the following output displayed:A First Simple Program

This is a simple HelloWorld Java program.

A Closer Look at the First Sample Program:-


Although HelloWorld.java is quite short, it includes several key features that are common to all Java programs. Let's closely examine each part of the program.
The program begin with the follwing lines:
/*
This is a simple Java program.
Call this file "HelloWorld.java".
*/
This is comment,Like most other programming languages.Java lets you enter a remark into a program's source file.The contents of comment are ignored by the compiler.

The next line of code in the program is shown here:


class HelloWorld {
 
This line uses the keyword class to declare that a new class is being defined.HelloWorld is an identifier that is the name of the class. The entire class definition,including all of its members,will be between opening curly brace ({) and closing curly brace (}).

The next line in the program is the single-line comment, shown here:


// Your program begins with a call to main().

This is single line comment-> A single-line comment begins with a // and ends at the end of the line

The next of code is shown here :


public static void main(String args[]) {

This line begins the main method. All Java applications begin execution by calling main( ).

The public keyword is an access modifier,which allows the programmer to control the visibility of class members.When a class member is preceded by public,then that member may be accessed by code outside the class in which it is declared.(The opposite of public is private, which prevents a member from being used by code defined outside of its class.)
In this case main must be declared as a public, since it must be called by code outside of its class when the program is started.
The keyword static allows main() to be called without having to instantiate a particular instance of the class.This is necessary since main() is called by the Java Virtual Machine before any objects are made.The keyword void simply tells to compiler the main does not return a value.

Any information that you need to pass to a method is received by variables specified within the set of parentheses that follow the name of the method. These variables are called parameters. If there are no parameters required for a given method, you still need to include the empty parentheses. In main( ), there is only one parameter, albeit a complicated one.

String args[ ] declares a parameter named args, which is an array of instances of the class String. (Arrays are collections of similar objects.) Objects of type String store character
strings. In this case, args receives any command-line arguments present when the program is executed.

The next line of code is shown here. Notice that it occurs inside main().

System.out.println("This is a simple HelloWorld Java program.");

This line outputs the string "This is a simple HelloWorld Java program." followed by a new line on the screen. Output is actually accomplished by the built-in println( ) method. In this case, println( )
displays the string which is passed to it.

As you will see, println( ) can be used to display other types of information, too.
The line begins with System.out.

System is a predefined class that provides access to the system, and out is the output stream that is connected to the console.

Data Types in java


Monday, February 5, 2018

Object-Oriented Programming In Java


Object-Oriented Programming:-

object-oriented programming(OOP) is at the core of Java.In fact,all Java programs are to at least some extent object-oriented. OOP is so integral to Java that it is understand its basic principles before you begin writing even simple java programs.

All computer programs consist of two elements: code and data.Furthermore,a program can be conceptually organized around its code,or its data.That is, some programs are written around “what is happening” and others are written around “who is being affected.” These are the two paradigms that govern how a program is constructed. The first way is called the process-oriented model.

To manage increasing complexity,the second approach,called object-oriented programming.Object-oriented programming organize a program around its data(that is object) and  set of well defined interfaces to that data.An object-oriented program can be characterized as data controlling access to code.

Abstraction:-


An essential element of object-oriented programming is abstraction.Humans manage complexity through abstraction.For example,people do not think of a car as a set of tens thousands of individual parts.They think it is well defined object with its own unique behavior.This abstraction allows people to use a car to drive to the grocery store without being overwhelmed by the complexity of the parts that form the car. They can ignore the details of how the engine, transmission, and braking systems work. Instead, they are free to utilize the object as a whole.

A powerful way to manage abstraction is through the use of hierarchical classifications.This allow you to layer the semantics of complex systems,breaking them into more manageable pieces.From the outside, the car is single object.once inside,you see that the car consist of several subsystems: streening, breakes, sound system,seat belts,heating,cellular phone,
and so on. In turn,each of subsystems is made of more specialized units. For instance,the second system consist of a radio,a CD player ,and a tape or MP3 player.
The point is that you manage the complexity of the car through the use of hierarchical abstractions.

Hierarchical abstractions of complex systems can also be applied to computer programs.The data from a traditional process-oriented program can be transformed by abstraction into its component objects. A sequence of process steps can become a collection of messages between these objects. Thus, each of these objects describes its own unique behavior. You can treat these objects as concrete entities that respond to messages telling them to do something.

All object oriented programming languages provide mechanisms that help you implement the object oriented model. They are encapsulation,inheritance,and polymorphism.
 let's take a look at these concepts now.

Encapsulation:-

Encapsulation is the mechanisms that binds together code and the data it manipulates,and keeps both safe from outside interference and misuse. One way to think about encapsulation
ia as a protective wrapper that prevents the code and data from being arbitrarily accessed by other code defined outside the wrapper.

Inheritance:-


Inheritance is the process by which one object acquires the properties of another object. This is important because it supports the hierarchical classification. As mentioned earlier,most knowledge is made manageable hierarchical(that is top-down) classifications.

Polymorphism:-


Polymorphism(from Greek,meaning "Many forms") is a feature that allows one interface to be used for a general class of actions. The specific action is determined bye the exact nature of the situation. Consider a stack(Which is a last-in, first -out list). You might have a program that requires three types of stacks. One Stack is used for integer values,one for floating-point values,and one for characters. The algorithm that implements each stack is the same,even though the data being stored differs. In a non-object-oriented language,you would be required to create three different sets of stack routines, with each set using different names. However, because of polymorphism, in Java you can specify a general set of stack routines that all share the same names.

More generally, the concept of polymorphism is often expressed by the phrase “one interface, multiple methods.” This means that it is possible to design a generic interface to a group of related activities. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. It is the compiler’s job to select the specific action (that is, method) as it applies to each situation. You, the programmer, do not need to make this selection manually. You need only remember and utilize the general interface.

First Simple Helloworld Program in java
Data Types in java  

Saturday, February 3, 2018

CURD(Create,Update,Read,Delete) In JSF Using Java Persistence API


In this article i have explain the Create ,Update ,Read and Delete operation in ProductInfo table using JSF and Java Persistence API.

Step 1. Create The ProductInfo table in mysql database.

  create table ProductInfo(
      id int(11) NOT NULL AUTO_INCREMENT,
      title varchar(200),
      shortDescription varchar(250),
      longDescription varchar(500),
      price double,
      discount float,
      categoryId int(11),
      primary key(id)
    );

   
Folder Structure of Project as

   
   
   
Step 2. Creating Entity class

   
    ProductInfo.java
package entitiesClasses;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author brij
 */
@Entity
@Table(name = "productInfo")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "ProductInfo.findAll", query = "SELECT p FROM ProductInfo p"),
    @NamedQuery(name = "ProductInfo.findById", query = "SELECT p FROM ProductInfo p WHERE p.id = :id"),
    @NamedQuery(name = "ProductInfo.findByTitle", query = "SELECT p FROM ProductInfo p WHERE p.title = :title"),
    @NamedQuery(name = "ProductInfo.findByPrice", query = "SELECT p FROM ProductInfo p WHERE p.price = :price"),
    @NamedQuery(name = "ProductInfo.findByDiscount", query = "SELECT p FROM ProductInfo p WHERE p.discount = :discount"),
    @NamedQuery(name = "ProductInfo.findByCategoryId", query = "SELECT p FROM ProductInfo p WHERE p.categoryId = :categoryId")})
public class ProductInfo implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Size(max = 200)
    @Column(name = "title")
    private String title;
    @Lob
    @Size(max = 65535)   
    @Column(name = "shortDescription")
    private String shortDescription;
    @Lob
    @Size(max = 65535)
    @Column(name = "longDescription")
    private String longDescription;
    // @Max(value=?)  @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
    @Column(name = "price")
    private Double price;
    @Column(name = "discount")
    private Float discount;
    @Column(name = "categoryId")
    private Integer categoryId;

    public ProductInfo() {
    }

    public ProductInfo(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getShortDescription() {
        return shortDescription;
    }

    public void setShortDescription(String shortDescription) {
        this.shortDescription = shortDescription;
    }

    public String getLongDescription() {
        return longDescription;
    }

    public void setLongDescription(String longDescription) {
        this.longDescription = longDescription;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public Float getDiscount() {
        return discount;
    }

    public void setDiscount(Float discount) {
        this.discount = discount;
    }

    public Integer getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(Integer categoryId) {
        this.categoryId = categoryId;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof ProductInfo)) {
            return false;
        }
        ProductInfo other = (ProductInfo) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "DataObject.ProductInfo[ id=" + id + " ]";
    }
   
}


Step 3. Now Creating the EJB Model Classes 


  AbstractFacade.java

package ejbModel;

import java.util.List;
import javax.persistence.EntityManager;

/**
 *
 * @author brij
 */
public abstract class AbstractFacade<T> {

    private Class<T> entityClass;

    public AbstractFacade(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    protected abstract EntityManager getEntityManager();

    public void create(T entity) {
        getEntityManager().persist(entity);
    }

    public void edit(T entity) {
        getEntityManager().merge(entity);
    }

    public void remove(T entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
    }

    public T find(Object id) {
        return getEntityManager().find(entityClass, id);
    }

    public List<T> findAll() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return getEntityManager().createQuery(cq).getResultList();
    }

    public List<T> findRange(int[] range) {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        q.setMaxResults(range[1] - range[0] + 1);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    public int count() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
        cq.select(getEntityManager().getCriteriaBuilder().count(rt));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }
   
}

 AbstractFacade.java contain the create ,update read and delete mathod .


  ProductInfoFacade.java

 package ejbModel;

import entitiesClasses.ProductInfo;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author brij
 */
@Stateless
public class ProductInfoFacade extends AbstractFacade<ProductInfo> {

    @PersistenceContext(unitName = "jpaShopingPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public ProductInfoFacade() {
        super(ProductInfo.class);
    }
   
}

Step 4. Now creating the Javabeans

ProductBean.java

package jpaShopingBean;

import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

/**
 *
 * @author brij
 */
@Named(value="productBean")
@SessionScoped
public class ProductBean implements Serializable{
    private Integer id;
    private String title;
    private String shortDescription;
    private String longDescription;
    private Double price;
    private Float discount;
    private Integer categoryId;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getShortDescription() {
        return shortDescription;
    }

    public void setShortDescription(String shortDescription) {
        this.shortDescription = shortDescription;
    }

    public String getLongDescription() {
        return longDescription;
    }

    public void setLongDescription(String longDescription) {
        this.longDescription = longDescription;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public Float getDiscount() {
        return discount;
    }

    public void setDiscount(Float discount) {
        this.discount = discount;
    }

    public Integer getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(Integer categoryId) {
        this.categoryId = categoryId;
    }
   
}

ProductBean.java has the product fields ,propertices and getter and setter of  these fields .

now create the another class productController that control the our functionality
productController.java

package jpaShopingBean;

import entitiesClasses.ProductInfo;
import ejbModel.ProductInfoFacade;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;

/**
 *
 * @author brij
 */
@Named(value="productController")
@SessionScoped
public class productController implements Serializable{
    @EJB
    ProductInfoFacade productInfoFacade;
    @Inject
    ProductBean productbean;
   
    public List<ProductInfo> getAll() {
        return productInfoFacade.findAll();
    }
    public int getCount() {
        return productInfoFacade.count();
    }
    public String delete(ProductInfo p) {
        productInfoFacade.remove(p);
        return null;
    }
    public String addProduct() {
        ProductInfo p=new ProductInfo();
        p.setTitle(productbean.getTitle());
        p.setShortDescription(productbean.getShortDescription());
        p.setLongDescription(productbean.getLongDescription());
        p.setPrice(productbean.getPrice());
        p.setDiscount(productbean.getDiscount());
        p.setCategoryId(productbean.getCategoryId());
        productInfoFacade.create(p);
       
        return "index";
    }
    public String editProduct(ProductInfo p) {
        productbean.setId(p.getId());
        productbean.setTitle(p.getTitle());
        productbean.setShortDescription(p.getShortDescription());
        productbean.setLongDescription(p.getLongDescription());
        productbean.setPrice(p.getPrice());
        productbean.setDiscount(p.getDiscount());
        productbean.setCategoryId(p.getCategoryId());
       
        return "updateProduct";
    }
    public String saveProduct() {
        ProductInfo p=new ProductInfo();
        p.setId(productbean.getId());
        p.setTitle(productbean.getTitle());
        p.setShortDescription(productbean.getShortDescription());
        p.setLongDescription(productbean.getLongDescription());
        p.setPrice(productbean.getPrice());
        p.setDiscount(productbean.getDiscount());
        p.setCategoryId(productbean.getCategoryId());
        productInfoFacade.edit(p);
       
        return "index";
    }
   
   
}

Step 5. Now creating the JSF pages for performing CURD operation.

 //for display the list of the product
index.xhtml

  <?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
       xmlns:f="http://xmlns.jcp.org/jsf/core">
    <h:head>
        <title>Product Info</title>
    </h:head>
    <h:body>
        <h3>Total No of Product #{productController.getCount()}</h3>
        <h:form>
            <h:dataTable value="#{productController.getAll()}" var="product">
                <h:column>
                    <f:facet name="header">
                        edit
                    </f:facet>
                    <h:commandLink value="Edit" action="#{productController.editProduct(product)}"/>
                </h:column>
                <h:column>
                    <f:facet name="header">ID</f:facet>
                    #{product.id}
                </h:column>
                <h:column>
                    <f:facet name="header">Title</f:facet>
                    #{product.title}
                </h:column>
                <h:column>
                    <f:facet name="header">Short Description</f:facet>
                    #{product.shortDescription}
                </h:column>
                <h:column>
                    <f:facet name="header">Price</f:facet>
                    #{product.price}
                </h:column>
                <h:column>
                    <f:facet name="header">Discount</f:facet>
                    #{product.discount}
                </h:column>
                <h:column>
                <h:commandLink value="Delete" action="#{productController.delete(product)}"/>
                </h:column>
            </h:dataTable>
            <h:commandButton value="Add New Product" action="addProduct">
               
            </h:commandButton>
        </h:form>
    </h:body>
</html>

creating another jsf page addProduct.xhtml for adding the new product.


<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
    <h:head>
        <title>Add Product</title>
    </h:head>
    <h:body>
        <h:form>
            <h:panelGrid columns="2">
                Title
                <h:inputText value="#{productBean.title}"></h:inputText>
                Shot Description
                <h:inputText value="#{productBean.shortDescription}"></h:inputText>
                Long Description
                <h:inputText value="#{productBean.longDescription}"></h:inputText>
                Price
                <h:inputText value="#{productBean.price}"></h:inputText>
                Discount
                <h:inputText value="#{productBean.discount}"></h:inputText>
                Category Id
                <h:inputText value="#{productBean.categoryId}"></h:inputText>
            </h:panelGrid>
            <h:commandButton value="Save" action="#{productController.addProduct()}"/>
        </h:form>
    </h:body>
</html>


creating another jsf page updateProduct.xhtml for adding the updating existing product.


<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
    <h:head>
        <title>Update Product</title>
    </h:head>
    <h:body>
        <h:form>
            <h:panelGrid columns="2">
                ID
                <h:outputText value="#{productBean.id}"></h:outputText>
                Title
                <h:inputText value="#{productBean.title}"></h:inputText>
                Short Description
                <h:inputText value="#{productBean.shortDescription}"></h:inputText>>
                Long Description
                <h:inputText value="#{productBean.longDescription}"></h:inputText>
                Price
                <h:inputText value="#{productBean.price}"></h:inputText>
                Discount
                <h:inputText value="#{productBean.discount}"></h:inputText>
                Category Id
                <h:inputText value="#{productBean.categoryId}"></h:inputText>
            </h:panelGrid>
            <h:commandButton value="Save" action="#{productController.saveProduct()}"/>
        </h:form>
    </h:body>
</html>

Step 6. creating the glassfish-resource.xml file for configuring database setting


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
    <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false"
                          connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10"
                          connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0"
                          connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource"
                          fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false"
                          is-isolation-level-guaranteed="true"
                          lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false"
                          max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000"
                          name="mysql_brij_shoppingcart_rootPool" non-transactional-connections="false"
                          pool-resize-quantity="2" res-type="javax.sql.DataSource"
                          statement-timeout-in-seconds="-1" steady-pool-size="8"
                          validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
        <property name="serverName" value="localhost"/>
        <property name="portNumber" value="3306"/>
        <property name="databaseName" value="brij_shoppingcart"/>
        <property name="User" value="root"/>
        <property name="Password" value=""/>
        <property name="URL" value="jdbc:mysql://localhost:3306/brij_shoppingcart?zeroDateTimeBehavior=convertToNull"/>
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    </jdbc-connection-pool>
    <jdbc-resource enabled="true" jndi-name="java:app/jpaShoping" object-type="user" pool-name="mysql_brij_shoppingcart_rootPool"/>
</resources>

Step 7. Deploy and run the project .

 List of the product





Add new product
Edit existing product


   
   

Entities In Java Persistence API

Entities In Java Persistence :

An entities is a lightweight persistence domain object.Typically an entity represents a table in relational database, and each entity instance corresponds to a row in that tables.

The persistent state of an entity is represented either through persistent fields or persistent properties. These fields or properties use object/relational mapping annotations to map the entities and entity relationships to the relational data in the underlying data store.


Requirements for Entity Classes:-


An entity class must follow these requirements:
1.The class must be annotated with the javax.persistence.Entity annotation.
2.The class must have a public or protected ,no-argument constructor. The class may have other constructors.
3.The class must not be declared final. No method or persistent instance variable must be declared final.
4.Entities may extend both entity and non-entity classes,and non-entity classes may extend entity classes.
5.Persistent instance variables must be declared private, protected, or package-private, and can only be accessed directly by the entity class’s methods. Clients must access the entity’s state through accessor or business methods.
   
 
Persistent Fields and Properties in Entity Classes:- 

The persistent state of an entity can be accessed either through the entity's   instance variable or through JavaBeans-style properties. The fields or properties must be the following java language types:

 1. Java primitive types.
 2. Java.lang.String.

 Other serializable types including:-
 
  * Wrappers of java primitive types.
  * Java.math.BigInteger
  * Java.math.BigDecimal
  * Java.util.Date
  * Java.util.Calendar
  * Java.sql.Date
  * Java.sql.Time
  * Java.sql.TimeStamp
 
 User-defined serializable types:-

 
  *byte[]
  *Bytes[]
  *char[]
  *character[]

Enumerated types
Other entities and collections of entities.
Embeddable classes

Entities may either use persistent fields or persistent properties. If the mapping annotations are applied to the entity’s instance variables,
the entity uses persistent fields.

Persistent Fields:-


If the entity class uses persistent fields, the Persistence runtime accesses entity class instance variables directly.
all fields not annotated javax.persistence.Transient or not marked as java transient will be persisted to data store. The Object/relation mapping annotation
must be applied to the instance variables.


Persistent Properties:-

If the entity class use persistent properties, the entity must follow the method conventions of JavaBeans components. JavaBeans-style properties use getter and setter
methods that are typically named after the entity class's instance variable names. For every persistent property property of type Type of the entity, there is a getter method getProperty and setter method setProperty.

The method signature for single -valued persistent properties as follow:-

Type getProperty()
void setProperty(Type type)

Collection-valued persistent fields and properties must use the supported Java collection interfaces regardless of whether the entity uses persistent fields or properties.
The following collection interfaces may be used:

  *java.util.Collection
  *java.util.Set
  *java.util.List
  *java.util.Map
 
Primary Keys in Entities:-
 
Each object has a unique identifier. A customer entity, for example , might be identified by a customer number.
The unique identifier, or primary key, enables clients to locate a particular entity instance.
Every entity must have a primary key. An entity may have either a simple or a composite primary key.

The primary key, or the property or field of a composite primary key, must be one of the following Java language types:

    Java primitive types

    Java primitive wrapper types

    java.lang.String

    java.util.Date (the temporal type should be DATE)

    java.sql.Date

Floating point types should never be used in primary keys. If you use a generated primary key, only integral types will be portable.

Primary Key Clasees:-

A primary key class must these requirements:
  *The access control modifier of the class must be public.
  *The properties of the primary key class must be public or protected if property based access is used.
  *The class must have a public default constructor.
  *The class must be serializable

Multiplicity in Entity Relationships:-


 There are four types of multiplicities :
  1. one-to-one
  2. one-to-many
  3. many-to-one
  4. many-to-many

1. One-To-One:- Each entity instance is related to a single instance of another entity. For example, to model a physical warehouse in which each storage bin conatins a single widget.
2. One-To-Many:- An entity instance can be related to multiple instance of the other entities. A sales order, for example,can have multiple line items. In the order application,order would have a one-to-many relationship with line item.
3. Many-To-one:- Multiple instance of an entity can be related to a single instance of the other entity. this Multiplicity is the opposite of a one-to-many relationship.
4. Many-To-Many:-The antity instance can be related to multiple instance of each other. For example, in college each course has many students ,a nd every may take several courses.therefore in an enrollment application, Course and Student would have a many-to-many relationship.

Entity Inheritence:-
 
 Entities support class inheritence, polymorphic associations, and polymorphic queries. They can extend non-entity classes, and non-entity classes can extend entity classes. ENtity classes can be both abstract and concrete.

Abstract Entities:-


 An abstract class may be declared an entity by decorating the class with @Entity. Abstract entities differ from
 concrete entities only in that they cannot be instantiated.

 Abstract entities can be queried just like concrete queries. If an abstract entity is the target of a query, the query operates on all the concrete subclasses of the abstract entity.

@Entity
public abstract class Employee {
    @Id
    protected Integer employeeId;
    ...
}
@Entity
public class FullTimeEmployee extends Employee {
    protected Integer salary;
    ...
}
@Entity
public class PartTimeEmployee extends Employee {
    protected Float hourlyWage;
}



 

Saturday, January 20, 2018

Interfaces in Java


  In the java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods.

Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.

interface advanceCalculation {
    public int divisor_sum(int n) ;
}
 class Myclass implements advanceCalculation{

    @Override
    public int divisor_sum(int n) {
    int sum=0;
        if(n>1) {
        for(int i=1;i<=n;i++) {
            if(n%i==0) sum+=i;
        }
    }
        return sum;
    }
}
public class Mycalculation {
    public static void main(String arg[]) {
    Myclass obj=new Myclass();
    int s=obj.divisor_sum(6);
   
    System.out.println("The sum of divisor = "+s);
         
}
}


Tuesday, December 12, 2017

Introduction To Java

Java technology is both a programming language and platform.

The Java Programming language:->
 The java programming language is a high-level langauge that can be characterized by all the following feature

1.Simple
2.Object oriented
3.Distributed
4.High performance
5.Multithreaded
6.Architecture neutral
7.Dynamic
8.Portable
9.Robust
10.Secure

In Java programming langauge, all source code is written in the plain text files ending the .java extension. Those cource files are then compiiled into .class files by the javac compiler. A .class file does not contain code that is native to your processor.it instead contains bytecodes- the machine language of the java virtual machine (java JM). The java launcher tool then runs your application with an instance of the java virtual machine.

First Simple Helloworld Program in java

Featured Post

What is JavaScript? What is the role of JavaScript engine?

  The JavaScript is a Programming language that is used for converting static web pages to interactive and dynamic web pages. A JavaScript e...