Let's take a look at what some of Datavail's clients and DBAs think are best practices for operating MongoDB.

1. Assigning Roles and Responsibilities

Roles are assigned based on the expectations for the new configuration. End users of reports are often immersed in configuration discussions, along with system administrators, data architects, and, of course, DBAs.

2. Preparing for a MongoDB Deployment                                                               

Storage engine solutions

  • MongoDB can be used with a variety of storage solutions — on premises, in the cloud, or hybrid.
  • The A variety of pluggable storage engines can be configured to work with MongoDB. The default package includes WiredTiger and MMAPv1.
  • MongoDB Enterprise Advanced edition includes support for encrypted storage engine and in-memory storage.

Schema design

NoSQL databases do not impose a schema, which is one of their great strengths. They can easily merge data in a wide variety of different formats. But the format they get merged into becomes a schema and its design should be carefully considered.

Database architects and schema designers need to consider the kind and number of documents to be stored, how they are grouped into collections, how they will be indexed and validated. With MongoDB Compass, these rules can be turned into a visual schema that makes it easier and faster to run database queries.

Data lifescycle management

Using MongoDB Zones, DBAs can build tiered storage solutions that support the data lifecycle, with frequently-used data stored in memory, less-used data stored on the server, and archived data taken offline at the proper time.

Managing indexes

Indexes are an important part of optimizing a database system. They can also take up a lot of space and need to be removed when no longer needed. Here are some of the best practices for modeling data as documents, below. The right approach depends on the objectives of your application.

  • Store data as a single document. The entire database can then be retrieved for a single query. This is efficient, but there are size limitations.
  • Avoid creating large documents. The maximum document size for MongoDB is 16MB. For files that are larger than 16MB, such as photos or videos, you need tools such as GridFS to break larger files into a series of smaller files. If the space allocated for a document is more than half the space available, it can’t be replicated in memory while an update is made. You need to monitor document growth and relocate documents when they get too large.
  • Avoid long field names. Long field names increase the minimum amount of space a database requires. The limit for field names is 125 characters. For a similar reason, avoid queries involving low-cardinal fields, because they can result in reports of enormous size.
  • Use MongoDB's new tools to manage Indexes.  The WiredTiger storage engine automatically compresses indexes. MongoDB Compass helps visibleize a database so that opportunities to eliminate infrequently used indexes are easy to spot.

USEFUL RESOURCES:

 

Mongodb training in chennai

 

Mongodb official

文章標籤

saravanagumar 發表在 痞客邦 留言(0) 人氣()

Spring Framework is a powerful lightweight application development framework used for Enterprise Java (JEE).

The core features of the Spring Framework can be used in developing any Java application. It can be described as complete and modular framework. The Spring Framework can be used for all layer implementations of a real time application. It can also be used for the development. Of a particular layer of a real time application unlike Struts and Hibernate, but with Spring we can develop all layers.

FEATURES:

Spring is non invasive : That means you no need to implements any interface or inherit any class from spring to your classes, so when ever you want to change from spring to any other technology then you no need to change the logics of your class.

Spring is light weight:  Spring is vast framework so spring people divide the whole spring in to different modules, they are designed in such a way that no module is dependent to other module , excep Spring core module, so according to your requirement you can learn a particular module, you no need to learn whole total framework.

End to end Development :  Spring supports all aspects of application development, Business aspects, persistence aspects, etc, so we can develop a complete application using spring.

Spring supports All types of application development:  We can develop any type of applications using spring, eg: Core java, web Application, Distributed application, Enterprise application.

Spring is versatile:  We can integrate any technologies with spring , so we can say spring is versatile,

Spring supports dependency injection:  The dependency between classes are managed by spring .

Dependency injection:

Spring core is one module which deals with dependency management

 

Here is the overview of new things that are introduced as part of Spring Framework 5.

JDK 8+9 and Java EE 7 Baseline


Minimum Java requirement will be raised to JDK 8.


There is also an upgrade to the minimum Java EE versions. The current minimum version is Servlet 2.5, this will be raised to Servlet 3.0.


JPA 1.1+ and Bean Valication API 1.1+ will be the minimum requirements.


Reactive Programming Model

Here some detailation:

JDK 8 + 9 and Java EE 7 Baseline

  • Java 8 as a minimum requirement as entire framework codebase is based on Java 8.
  • Java EE 7 required to run Spring Framework 5.0 applications.Hence, requires Servlet 3.1, JMS 2.0, JPA 2.1

Removed Packages, Classes and Methods

  • Package mock.static mock removed from spring-aspects module and hence no support for AnnotationDrivenStaticEntityMockingControl
  • Packages such as web.view.tiles2 and orm.hibernate3 / hibernate4 dropped.Hence Tiles 3 and Hibernate 5 be compulsarily used.
  • Support for Portlet, Velocity, JasperReports, XMLBeans, JDO, Guava dropped.
  • Most of the deprecated classes and methods removed.

Reactive Programming Model

  • Spring-core, DataBuffer and Encoder/Decoder abstractions with non-blocking semantics.
  • New WebClient with reactive support on the client side.

USEFUL RESOURCES:

Java spring certification in chennai

Spring official

文章標籤

saravanagumar 發表在 痞客邦 留言(0) 人氣()

Services : These are singleton objects which are instantiated only once in in app. AngularJS comes with several built-in services such as $http to make XMLHttpRequests.

Data-binding : It helps in automatic synchronization of data between model and view components.

Scope : These are objects that refer to the model. Scope acts as a glue between controller and view.

Controller : These are JavaScript functions bound to a particular scope

Filters : These select a subset of items from an array and returns a new array.

Directives : Directives are markers on DOM elements such as element, attribute, css, and more. They can be used to create custom HTML tags that serve as new, custom widgets. AngularJS has built-in directives such as ngBind, ngModel etc.

Templates : These are the rendered views with information from the controller and model. These can be a single file (such as index.html) or multiple views in one page using partials.

Routing : It is about the concept of switching views.

Model View Whatever : MVW is a design pattern for dividing an application into different parts called Model, View, and Controller, each with distinct responsibilities. AngularJS does not implement MVC in the traditional sense, but rather something closer to MVVM (Model-View- ViewModel). The Angular JS team refers to it humorously as Model View Whatever.

Deep Linking : Deep linking allows you to encode the state of application in the URL so that it can be bookmarked. The application can then be restored from the URL to the same state.

Dependency Injection : AngularJS has a built-in dependency injection subsystem that helps developer, understand, and test the applications easily.

 

Useful Resources:

 

Angularjs training in chennai

 

Angular 5 Features

 

Angular Official

文章標籤

saravanagumar 發表在 痞客邦 留言(0) 人氣()

 

RabbitMQ is a popular open source message queuing system developed in the erlang language.  RabbitMQ is a standard implementation of AMQP (Advanced Message Queuing Protocol).

Add maven dependency

  1. dependency  >

  2.       groupId  >  org.springframework.boot  </  groupId  >

  3.       artifactId  >  spring-boot-starter-amqp  </  artifactId  >

  4. </  dependency  >

Simple implementation

Configuration

Add the following configuration in application.properties

  1. Spring.rabbitmq.addresses=127.0.0.1:5672

  2. Spring.rabbitmq.username=guest

  3. Spring.rabbitmq.password=guest

  4. Spring.rabbitmq.publisher-confirms=true

  5. Spring.rabbitmq.virtual-host=/

Rabbitmq port description: 5672-amqp, 25672-clustering, 61613-stomp, 1883-mqtt

News producer

  1. Package   com.rabbitmq.send;

  2.  

  3. Import   org.springframework.amqp.rabbit.core.RabbitTemplate;

  4. Import   org.springframework.beans.factory.annotation.Autowired;

  5. Import   org.springframework.stereotype.Component;

  6.  

  7. @Component

  8. Public   class   Sender {

  9.  

  10.     @Autowired

  11.     Private   RabbitTemplate rabbitTemplate;

  12.  

  13.     Public   void   send(String msg) {

  14.         This  .rabbitTemplate.convertAndSend(  "foo"  , msg);

  15.     }

  16. }

Message listener

  1. Package   com.rabbitmq.listener;

  2.  

  3. Import   org.slf4j.Logger;

  4. Import   org.slf4j.LoggerFactory;

  5. Import   org.springframework.amqp.core.Queue;

  6. Import   org.springframework.amqp.rabbit.annotation.RabbitHandler;

  7. Import   org.springframework.amqp.rabbit.annotation.RabbitListener;

  8. Import   org.springframework.context.annotation.Bean;

  9. Import   org.springframework.context.annotation.Configuration;

  10. Import   org.springframework.messaging.handler.annotation.Payload;

  11.  

  12. @Configuration

  13. @RabbitListener  (queues =   "foo"  )

  14. Public   class   Listener {

  15.  

  16.     Private   static   final   Logger LOGGER = LoggerFactory.getLogger(Listener.  class  );

  17.  

  18.     @Bean

  19.     Public   Queue fooQueue() {

  20.         Return   new   Queue(  "foo"  );

  21.     }

  22.  

  23.     @RabbitHandler

  24.     Public   void   process(  @Payload   String foo) {

  25.         LOGGER.info(  "Listener: "   + foo);

  26.     }

  27. }

Test Controller

  1. Package   com.rabbitmq.controller;

  2.  

  3. Import   com.rabbitmq.send.Sender;

  4. Import   org.springframework.beans.factory.annotation.Autowired;

  5. Import   org.springframework.web.bind.annotation.GetMapping;

  6. Import   org.springframework.web.bind.annotation.RestController;

  7.  

  8. Import   javax.servlet.http.HttpServletRequest;

  9.  

  10. @RestController

  11. Public   class   RabbitmqController {

  12.  

  13.     @Autowired

  14.     Private   Sender sender;

  15.  

  16.     @GetMapping  (  "/send"  )

  17.     Public   String send(HttpServletRequest request, String msg) {

  18.         Sender.send(msg);

  19.         Return   "Send OK."  ;

  20.     }

  21. }

Test

Start the service, enter http://127.0.0.1:8080/send?msg=this%20is%20a%20test in the browser, click Enter to see the output in the console

  1. INFO 5559 - [cTaskExecutor-1] c.rabbitmq.listener.Listener : Listener: this is a test

  2. [SimpleAsyncTaskExecutor-1] INFO c.rabbitmq.listener.Listener – Listener: this is a test

Use with ConfirmCallback

Added callback processing, which no longer uses the default configuration of application.properties and will display the configuration information in the use file in the program.

Configuration

  1. Package   com.rabbitmq.config;

  2.  

  3. Import   org.springframework.amqp.rabbit.connection.CachingConnectionFactory;

  4. Import   org.springframework.amqp.rabbit.connection.ConnectionFactory;

  5. Import   org.springframework.amqp.rabbit.core.RabbitTemplate;

  6. Import   org.springframework.beans.factory.annotation.Value;

  7. Import   org.springframework.beans.factory.config.ConfigurableBeanFactory;

  8. Import   org.springframework.context.annotation.Bean;

  9. Import   org.springframework.context.annotation.Configuration;

  10. Import   org.springframework.context.annotation.Scope;

  11.  

  12. @Configuration

  13. Public   class   AmqpConfig {

  14.  

  15.     Public   static   final   String FOO_EXCHANGE =   "callback.exchange.foo"  ;

  16.     Public   static   final   String FOO_ROUTINGKEY =   "callback.routingkey.foo"  ;

  17.     Public   static   final   String FOO_QUEUE =   "callback.queue.foo"  ;

  18.  

  19.     @Value  (  "${spring.rabbitmq.addresses}"  )

  20.     Private   String addresses;

  21.     @Value  (  "${spring.rabbitmq.username}"  )

  22.     Private   String username;

  23.     @Value  (  "${spring.rabbitmq.password}"  )

  24.     Private   String password;

  25.     @Value  (  "${spring.rabbitmq.virtual-host}"  )

  26.     Private   String virtualHost;

  27.     @Value  (  "${spring.rabbitmq.publisher-confirms}"  )

  28.     Private   boolean   publisherConfirms;

  29.  

  30.     @Bean

  31.     Public   ConnectionFactory connectionFactory() {

  32.         CachingConnectionFactory connectionFactory =   new   CachingConnectionFactory();

  33.         connectionFactory.setAddresses(addresses);

  34.         connectionFactory.setUsername(username);

  35.         connectionFactory.setPassword(password);

  36.         connectionFactory.setVirtualHost(virtualHost);

  37.         /** If you want to make a message callback, this must be set to true */

  38.         connectionFactory.setPublisherConfirms(publisherConfirms);

  39.         Return   connectionFactory;

  40.     }

  41.  

  42.     @Bean

  43.     /** Because you want to set the callback class, it should be the prototype type. If it is the singleton type, the callback class is set to the last time. */

  44.     @Scope  (ConfigurableBeanFactory.SCOPE_PROTOTYPE)

  45.     Public   RabbitTemplate rabbitTemplate() {

  46.         RabbitTemplate template =   new   RabbitTemplate(connectionFactory());

  47.         Return   template;

  48.     }

  49.  

  50. }

News producer

  1. Package   com.rabbitmq.send;

  2.  

  3. Import   com.rabbitmq.config.AmqpConfig;

  4. Import   org.slf4j.Logger;

  5. Import   org.slf4j.LoggerFactory;

  6. Import   org.springframework.amqp.rabbit.core.RabbitTemplate;

  7. Import   org.springframework.amqp.rabbit.support.CorrelationData;

  8. Import   org.springframework.beans.factory.annotation.Autowired;

  9. Import   org.springframework.stereotype.Component;

  10.  

  11. Import   java.util.UUID;

  12.  

  13. @Component

  14. Public   class   Sender   implements   RabbitTemplate.ConfirmCallback {

  15.  

  16.     Private   static   final   Logger LOGGER = LoggerFactory.getLogger(Sender.  class  );

  17.  

  18.     Private   RabbitTemplate rabbitTemplate;

  19.  

  20.     @Autowired

  21.     Public   Sender(RabbitTemplate rabbitTemplate) {

  22.         This  .rabbitTemplate = rabbitTemplate;

  23.         This  .rabbitTemplate.setConfirmCallback(  this  );

  24.     }

  25.  

  26.     Public   void   send(String msg) {

  27.         CorrelationData correlationData =   new   CorrelationData(UUID.randomUUID().toString());

  28.         LOGGER.info(  "send: "   + correlationData.getId());

  29.         This  .rabbitTemplate.convertAndSend(AmqpConfig.FOO_EXCHANGE, AmqpConfig.FOO_ROUTINGKEY, msg, correlationData);

  30.     }

  31.  

  32.     /** Callback method */

  33.     @Override

  34.     Public   void   confirm(CorrelationData correlationData,   boolean   ack, String cause) {

  35.         LOGGER.info(  "confirm: "   + correlationData.getId());

  36.     }

  37. }

Message listener

  1. Package   com.rabbitmq.listener;

  2.  

  3. Import   com.rabbitmq.config.AmqpConfig;

  4. Import   org.slf4j.Logger;

  5. Import   org.slf4j.LoggerFactory;

  6. Import   org.springframework.amqp.core.Binding;

  7. Import   org.springframework.amqp.core.BindingBuilder;

  8. Import   org.springframework.amqp.core.DirectExchange;

  9. Import   org.springframework.amqp.core.Queue;

  10. Import   org.springframework.amqp.rabbit.annotation.RabbitHandler;

  11. Import   org.springframework.amqp.rabbit.annotation.RabbitListener;

  12. Import   org.springframework.context.annotation.Bean;

  13. Import   org.springframework.context.annotation.Configuration;

  14. Import   org.springframework.messaging.handler.annotation.Payload;

  15.  

  16. @Configuration

  17. @RabbitListener  (queues = AmqpConfig.FOO_QUEUE)

  18. Public   class   Listener {

  19.  

  20.     Private   static   final   Logger LOGGER = LoggerFactory.getLogger(Listener.  class  );

  21.  

  22.     /** Set switch type */

  23.     @Bean

  24.     Public   DirectExchange defaultExchange() {

  25.         /**

  26.          * DirectExchange: Distribution to the specified queue according to the routingkey

  27.          * TopicExchange: Multiple Keyword Matching

  28.          * FanoutExchange: Distribution of messages to all binding queues, no concept of routingkey

  29.          * HeadersExchange : Matching by adding attribute key-value

  30.          */

  31.         Return   new   DirectExchange(AmqpConfig.FOO_EXCHANGE);

  32.     }

  33.  

  34.     @Bean

  35.     Public   Queue fooQueue() {

  36.         Return   new   Queue(AmqpConfig.FOO_QUEUE);

  37.     }

  38.  

  39.     @Bean

  40.     Public   Binding binding() {

  41.         /** Bind the queue to the switch */

  42.         Return   BindingBuilder.bind(fooQueue()).to(defaultExchange()).with(AmqpConfig.FOO_ROUTINGKEY);

  43.     }

  44.  

  45.     @RabbitHandler

  46.     Public   void   process(  @Payload   String foo) {

  47.         LOGGER.info(  "Listener: "   + foo);

  48.     }

  49. }

Or use the following code instead of the process method of the @RabbitHandler annotation

  1. @Bean

  2. Public   SimpleMessageListenerContainer messageContainer() {

  3.     SimpleMessageListenerContainer container =   new   SimpleMessageListenerContainer(connectionFactory());

  4.     container.setQueues(fooQueue());

  5.     container.setExposeListenerChannel(  true  );

  6.     container.setMaxConcurrentConsumers(  1  );

  7.     container.setConcurrentConsumers(  1  );

  8.     container.setAcknowledgeMode(AcknowledgeMode.MANUAL);   //Set confirm mode manual confirmation

  9.     container.setMessageListener(  new   ChannelAwareMessageListener() {

  10.  

  11.         @Override

  12.         Public   void   onMessage(Message message, Channel channel)   throws   Exception {

  13.             Byte  [] body = message.getBody();

  14.             LOGGER.info(  "Listener onMessage : "   +   new   String(body));

  15.             channel.basicAck(message.getMessageProperties().getDeliveryTag(),   false  );   //Confirm that the message was successfully consumed

  16.         }

  17.     });

  18.     Return   container;

  19. }

 

USEFUL RESOURCES:

 

Spring boot rabbitmq example

 

Spring boot official

 

 

 

文章標籤

saravanagumar 發表在 痞客邦 留言(0) 人氣()

Hibernate Many To Many Relation Mapping Example explains about how to implement A Many to Many relationship by using Hibernate

Many-to-many entity relationship , each record of an entity have multiple records in other associated entity and vice versa

On this standalone Hibernate Many To Many Mapping Example, we are using Hibernate With MySQL Database.

Required Libraries:

You need to download

  1. JDK 7
  2. Eclipse 3.7
  3. Hibernate 4.3.1
  4. Mysql 5.1.30

Following jar must be in classpath

  1. Antlr-2.7.7.jar
  2. Dom4j-1.6.1.jar
  3. hibernate-commons-annotations-4.0.4.Final.jar
  4. hibernate-core-4.3.1.Final.jar
  5. hibernate-entitymanager-4.3.1.Final.jar
  6. jandex-1.1.0.Final.jar
  7. Dom4j-1.6.1.jar
  8. jboss-logging-3.1.3.GA.jar
  9. hibernate-jpa-2.1-api-1.0.0.Final.jar
  10. jboss-transaction-api_1.2_spec-1.0.0.Final.jar
  11. Mysql-connector-java-5.1.28-bin.jar

Table Structure:

create table `employee` (
	`EMPLOYEEID` double ,
	`EMPLOYEENAME` varchar (765)
); 


create table `employee_event` (
	`EMPLOYEEID` double ,
	`EVENTID` double 
);

create table `event` (
	`EVENTID` double ,
	`EVENTNAME` varchar (765)
);

 

Create Employee & Event model classes as per the above table structure

Employee.java

package com.hibernate.manytomany;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;

@Entity
public class Employee implements java.io.Serializable {

    
private static final long serialVersionUID = 1L;

    
@Id
    @GeneratedValue
    @Column
(name = "EMPLOYEEID")
    
private long employeeId;
    
@Column(name = "EMPLOYEENAME")
    
private String employeeName;
    
@ManyToMany(cascade = CascadeType.ALL })
    
@JoinTable(name = "EMPLOYEE_EVENT", joinColumns = {@JoinColumn(name = "EMPLOYEEID") },
    inverseJoinColumns = 
@JoinColumn(name = "EVENTID") })
    
private Set<Event> events = new HashSet<Event>();

    
public Employee() {
        
super();
    
}

    
public Employee(String employeeName) {
        
super();
        
this.employeeName = employeeName;
    
}

    
public long getEmployeeId() {
        
return employeeId;
    
}

    
public void setEmployeeId(long employeeId) {
        
this.employeeId = employeeId;
    
}

    
public String getEmployeeName() {
        
return employeeName;
    
}

    
public void setEmployeeName(String employeeName) {
        
this.employeeName = employeeName;
    
}

    
public Set<Event> getEvents() {
        
return events;
    
}

    
public void setEvents(Set<Event> events) {
        
this.events = events;
    
}

}

 

 

Event.java

 

package com.hibernate.manytomany;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

@Entity
public class Event implements java.io.Serializable {

    
private static final long serialVersionUID = 1L;
    
@Id
    @GeneratedValue
    @Column
(name = "EVENTID")
    
private long eventID;
    
@Column(name = "EVENTNAME")
    
private String eventName;
   
    
@ManyToMany(mappedBy="events")
    
private Set<Employee> employees = new HashSet<Employee>();
   
    
public Event() {
        
super();
    
}

    
public Event(String eventName) {
        
this.eventName = eventName;
    
}

    
public long getEventID() {
        
return eventID;
    
}

    
public void setEventID(long eventID) {
        
this.eventID = eventID;
    
}

    
public String getEventName() {
        
return eventName;
    
}

    
public void setEventName(String eventName) {
        
this.eventName = eventName;
    
}

    
public Set<Employee> getEmployees() {
        
return employees;
    
}

    
public void setEmployees(Set<Employee> employees) {
        
this.employees = employees;
    
}

   

}

 

 

@ManyToMany(cascade = { CascadeType.ALL }) annotation is used for linking each record of Employee table with Event table and vice versa
@JoinTable(name = "EMPLOYEE_EVENT", joinColumns = { @JoinColumn(name = "EMPLOYEEID") }, inverseJoinColumns = { @JoinColumn(name = "EVENTID") }) is used to define the join table, here it is "EMPLOYEE_EVENT", which is connecting 2 columns ie; EMPLOYEEID belongs to employee table & EVENTID belongs to event table
@Entity declares the class as an entity (i.e. a persistent POJO class)
@Table is set at the class level; it allows you to define the table, catalog, and schema names for your entity mapping. If no @Table is defined the default values are used: the unqualified class name of the entity.
@Id declares the identifier property of this entity.
@GeneratedValue annotation is used to specify the primary key generation strategy to use. If the strategy is not specified by default AUTO will be used.
@Column annotation is used to specify the details of the column to which a field or property will be mapped. If the @Column annotation is not specified by default the property name will be used as the column name.

 

 

HibernateUtil.java

 

package com.hibernate.manytomany;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

    
private static SessionFactory    sessionFactory;
    
private static ServiceRegistry    serviceRegistry;

    
public static SessionFactory createSessionFactory() {
        
Configuration configuration = new Configuration();
        configuration.configure
("/META-INF/hibernate.cfg.xml");
        serviceRegistry = 
new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
                
.build();
        sessionFactory = configuration.buildSessionFactory
(serviceRegistry);
        
return sessionFactory;
    
}
}

 

hibernate.cfg.xml

 

hibernate.cfg.xml file must be under src/META-INF (Please check the screenshot(project structure)

 

<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="hibernate.connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="connection.pool_size">1</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">create-drop</property>
        <mapping class="com.hibernate.manytomany.Employee"/>
        <mapping class="com.hibernate.manytomany.Event"/>
    </session-factory>
</hibernate-configuration>

 

 

 

Project Structure

 

Now project structure looks like following

 

Hibernate Many To Many Mapping Example

 

Just execute below class and see the output

 

HibernateManyToManyExample.java

 

package com.hibernate.manytomany;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.hibernate.manytomany.Event;
import com.hibernate.manytomany.Employee;

public class HibernateManyToManyExample {
    
public static void main(String[] args) {
        
Session session = HibernateUtil.createSessionFactory().openSession();
        Transaction transaction = 
null;
        
try {

            
transaction = session.beginTransaction();
           
            Event event1 = 
new Event("Quaterly Sales meeting");
            Event event2 = 
new Event("Weekly Status meeting");
           
            Employee employee1 = 
new Employee("Rockey");
            Employee employee2 = 
new Employee("Jose");
           
            employee1.getEvents
().add(event1);
            employee1.getEvents
().add(event2);
           
            employee2.getEvents
().add(event1);
            employee2.getEvents
().add(event2);
           
            session.save
(employee1);
            session.save
(employee2);
           
            transaction.commit
();

        
catch (HibernateException e) {
            
transaction.rollback();
            e.printStackTrace
();
        
finally {
            
session.close();
        
}
    }
}

 

Output

 

EMPLOYEEID EMPLOYEENAME
1 Rockey
2 Jose
EMPLOYEEID EVENTID
1 1
2 1
1 2
2 2
EVENTID EVENTNAME
1 Weekly Status Meeting
2 Quaterly Sales Meeting

 

Useful Resources:

 

Hibernate Many to Many Relationship

 

Hibernate Official

saravanagumar 發表在 痞客邦 留言(0) 人氣()

 

Simple AngularJS application with Yahoo Weather API
After lot of ground work now we can easily start writing our AngularJS application. Let me just give you a brief about what you are going to build. We are going to develop a simple weather forecasting application with Yahoo API. There will be only one screen with one input box, you can enter zip code to see forecast of next 5 days. I am going to use Yahoo weather API to get forecasting data.

So let’s start writing body of index.html.
<body ng-app="myApp" ng-controller="listCtrl">
<center>
<div>
Weather Forecast - Enter zip code and click get forecast
</div>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<div ng-view></div>
<hr/>
<div>Angular seed app: v<span app-version></span></div>
</center>
<!-- In production use: <script src="//ajax.googleapis.com/ajax/libs/angularjs/x.x.x/angular.min.js"></script>-->
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="app.js"></script>
<script src="list/listController.js"></script>
<script src="components/version/version.js"></script>
<script src="components/version/version-directive.js"></script>
<script src="components/version/interpolate-filter.js"></script>
<script src="services/listService.js"></script>
</body>
Explanation
Observe above HTML properly and you will notice few new attributes starting with ng-

These are angular directives which informs AngularJS framework which DOM element to bind a mentioned behavior. For now let’s continue with the same example and you will understand the purpose of the directive.

Details of angular directives used in above markup are;

ng-app – We use this directive to auto-bootstrap the application
ng-controller – We use this to attach a controller class to specific UI element form view
ng-view – This directive helps to render the template which is attached to particular controller class
Note – please check the path of all js files mentioned in above code. You may need to create some directories like list, services. Such directories are not a part of the boiler plate, List is one of our screen so it’s always better to keep its controller and its template in same directory name “list”.

Now we need to write Angular service which will pull data from Yahoo API.
'use strict';
angular.module('myApp.services', []).
factory('weatherService', function($http) {
var API = {};
API.getForecast = function(countryZip)
{
return $http({
method: 'GET',
url: 'https://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20weather.forecast%20WHERE%20location%3D%22'+countryZip+'%22&format=json&diagnostics=true&callback='
});
}
return API;
});

An Angular service is an injectable object. It is a code block where we can write common logic which needs to be shared across application. For example in our application we need to make an AJAX call and get the data from Yahoo API. This part of code should not be reused and thus we are writing it in angular service and later on we will inject this service in one of our controller. This method of writing code is called as dependency injection.

Code explanation – You can see we have written a method in this service termed as – getForecast. Job of this method is to make REST call to Yahoo API and then return the response object.

AngularJS provides $http service to make AJAX calls to server. You can see we have injected $http method in our factory service. Once it is injected we can make use of this method to make a call. The getForecast method is self-explanatory.

Time to introduce first controller of the application.
'use strict';
angular.module('myApp.list', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when( '/list', {
templateUrl: 'list/list.html',
controller: 'listCtrl'
});
}])
.controller('listCtrl', ["$scope","weatherService",function($scope, weatherService ) {
$scope.init = function(){
$scope.forecastList = [];
$scope.nameFilter = null;
$scope.countryZip = 10001; // new york
$scope.getData();
}
$scope.getData =
Function (){ weatherService.getForecast($scope.countryZip).Success(function(response){
$scope.forecastList = response.query.results.channel.item.forecast;
$scope.city = response.query.results.channel.location.city;
$scope.country = response.query.results.channel.location.country ;
});
}
$scope.getForecastFromZip = function(){
$scope.getData();
}
$scope.init();
}]);
In previous steps we completed writing Angular Service, which will fetch required data from API. We have designed this service so that we can inject it in any controller and thus it can be reusable. Now let's see how to inject this service and define the template to display the forecast data.

Check first code block in which I have configured my template list.html with the controller and URL. I will also share how to design this template, for now let’s continue completing this controller.

Init method – This method is used to initialize required variables. You can see I have initialized countryZip variable to 10001, this is New York’s zip code. So when an application loads it always loads with default data for New York.

geData – This method makes use of injected service “weatherService” and its methods to get the data from API. I am calling getForecast method and passing it an argument which is nothing but countryZip. Once the network call for Yahoo Api is complete service will return the response to our controller in response object. We will pick 3 objects from this response, forecast, country, and city. We will now learn how to show these 3 objects with template.

getForecastFromZip – when user enter some zip code and hit submit then this method gets called to get the data for entered zip code.

Let’s write App.js – to bootstrap the application
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ngRoute',
'myApp.list',
'myApp.version',
'myApp.services'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/list'});
}]);

We have just created some angular modules including service and controller. Next step is to inject them in application. I have named my application “myApp”, if you notice in the index.html body tag then you can see same name attached with tag ng-app. Now check app.js to understand how these modules can be added to angular application.

Create Template to display the forecast.
<input type="text" ng-model="countryZip" placeholder="enter zip code..." /> <input type="submit" name="submit" value="get forecast" ng-click="getForecastFromZip();">
<br/>
<br/>
<table border="1" cellpadding="2px;">
<thead>
<tr><th colspan="4">Forecast of - {{city}} ({{country}})</th></tr>
</thead>
<tbody>
<tr ng-repeat="forecast in forecastList">
<td>{{forecast.date}} - ({{forecast.day}})</td>
<td>
{{forecast.text}}
<br/>
High - {{forecast.high}}<br/>
Low - {{forecast.low}}
</td>
</tr>
</tbody>
</table>

We have received data in 3 variables from controller and we have to show these 3 variables in our view.

Search box – check attribute ng-model attached to input box. ng-model=”countryZip”. This is very important step to understand. We have initialized the same variable in controller init method and same is bound here with input box.

Observe the attribute ng-click attached with submit button. It’s bind with getForecastFromZip method. It means that click event of this UI element (submit button) is bind to call getForecastFromZip method of the controller defined with ng-controller. If you are confused with this point then please go through index.html (body tag) .

Forecast of – {{city}} ({{country}}) – Check this line in my template. This is AngularJS way of writing variable value. In controller we have extracted 2 variables i.e. city and country. So if you want to echo them in your view then you simply have to embed them in {{}}.

ng-repeat – very important and most required directive while designing any UI component is ng-repeat. This can be used when you want particular UI element to repeat multiple times. In our example we need to show all records which are fetched from service. My template is based on table so I have to repeat <tr> multiple times. That’s the reason ng-repeat tag is added to <tr> tag and not table.

Now refresh your browser and check. Following is the screenshot of landing page.

 

 

Resources:

 

Angular training in chennai

 

Angular Official

saravanagumar 發表在 痞客邦 留言(0) 人氣()

First thing first, let’s start with the main objective of this post. Do not worry when you will complete this blog, you will have an intermediate level of expertise on AngularJS modules & controllers. 

In the  previous AngularJS Tutorial, titled Data-binding in AngularJS, you might have noticed  the source code similar to the one mentioned  below:

angular.module(name, [requires], [configFn]);

Parameter
name: name of the module.
requires:  is an optional parameter, if mentioned the new module get created. If not, an existing module is being retrieved.
configFn:  is an optional parameter, execute function on module load

The universal way to create or register the module with Angular is Parameter. It has a suite of services, controllers, services, configuration & directives. In other words, you can consider it as a main() function to initialize and get chained with variable and methods for an application. 

Sample code:

Var MyNewapp = angular.module(“MyNewApp”, []);

Code simplification:  We are using an Angular object to create the module. Here you will also find two parameters of angular.module, the first parameter is the name of a module and second refers to a blank array. 

Remember, there could be a scenario when your custom module will be dependent on another module. In that situation, you can pass that module over Angular module function as a parameter and utilize their resources.

Use: To bootstrap an Angular application, declare ng-app name on your page. 

  <!DOCTYPE html>
  <html>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  <body>
  <div ng-app=”myApp ">
  <p>Myself {{ firstname }}</p>
  </div>
  </body>
  </html>
  /*New App Declaration*/
  <script>
  var app = angular.module('myApp', []);
  app.controller('myCtrl', function($scope) {
  $scope.firstname = "Jaywant Topno";
  });
  </script>

In above source code, the <div ng-app=”myApp "> section will start bootstrapping (initializing/ resource gathering) process. It tells the browser that this is an Angular app. Here you can also see <p> tag have {{firstname}}. The browser will look for Angular variable and print the value in the view.

Now let’s move to the controller (new app declaration). A controller is nothing but a JavaScript constructor function, which is responsible for building a model (data) so that the same data could be displayed in a view. It has the ability to perform some operation or initializing the variable or getting the data from endpoint URL. 

In other words, when you work on decoupled website, the job of a controller is to get the data from web services. Hope this information is clear and helpful. Let’s view the basic syntax code and explanation of the code.

Syntax: 

  
    
var ControllerName  =  function ($scope) {
   /* variable initialization goes here */
}
    
   

Explanation: In the above source code, we are creating an anonymous function and assigning back to a variable. Note that it has one parameter, called $scope, which is an angular object pass to the controller. ControllerName is the name of the controller. Using the AngularJS Data binding methods, we can fetch the data in the view. Here we are also assigning ValueAproperty to  $scope object. 

         $scope.ValueA = "100 INR"; 

Once the controller has been created. The next step would be to Register the controller with the newly created module (myApp).  

Syntax: 

      Module object.Controller(“NewControllerName”, Controller-Function)

Sample:

 
   
Myapp.controller(“'myCtrl'”, function($scope) {   
   $scope.firstname = "Jaywant Topno";
});
  


Follow the above steps to:

1. Create a controller and register it with the app.
2. Avoid unnecessary variable storage by declaring and then referring.

  var NewApp = angular.module("NewApp,[]");
  var NewController = function ($scope) {
  $scope.ValueA = "100 INR";
  }
  var newApp.controller("NewController",NewController);
  /* Alternate way to write controller */
  var NewApp = angular.module("NewApp,[]");
  var newApp.controller("NewController", function ($scope) {
  $scope.ValueA = "100 INR";
  });

In case the name of controller gets changed then you need to make the similar changes in view also. Else view won’t be able to recognize your variable. 

Sample code:

  var ControllerName = function($scope) {
  $scope.ValueA = "100 INR";
  }
  Var NewApp.Controller("NewController", function($scope) {
  $scope.ValueA = "100 INR";
  }

So far we have created a module, a controller and registered that newly created controller.

Now let’s have a look how to pull up model to view using ng-app and ng-controller.

  <!DOCTYPE html>
  <html>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  <body>
  <div ng-app="NewApp">
  <p>Myself {{ firstName }}</p>
  </div>
  <div ng-controller=" NewController ">
  <p>Myself {{ ValueA }}</p>
  </div>
  </body>
  </html>

Points to remember:

1. View data won’t work outside scope until the controller is declared in the self <div> directory.
2. Create and register controller within single code to reduce unwanted memory allocation.

Phew! That was quite a ride. Remember, before building an application, it is necessary to have an intermediate level knowledge of AngularJS. Modules and controllers are building blocks of a newly created module where controller helps to initialize variable and perform an operation. Further, using ng-app we can tell the view to use specific app and ng-controller for the scope of the variable.

Resources:

Angular Training in chennai

Angular Official

saravanagumar 發表在 痞客邦 留言(0) 人氣()

Mapping shows how two entities are related to each other. In many to many mapping many entities of class A can only have multiple entities in class B. Like for example suppose the two classes are Student and Courses. So if these two classes have many to many relationship then it means that each Student can have multiple Courses .And each Course can have multiple students

We will explain this with the help of an example:

We make two class Student(We named the class Stu3 but we will reference it as Student to make it more easy to understand) and Course.

Listing 1: Course class

package model;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

/**
 *
 * @author Anurag
 */
@Entity
public class Course implements Serializable {

    @Id
    @GeneratedValue
    @Column(name = "C_ID")
    private Long id;
    private String name;
    private int duration;

    public Course() {
    }

    public Long getId() {
        return id;
    }

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

    public Course(String n, int dur) {
        name = n;
        duration = dur;
    }

    public int getDuration() {
        return duration;
    }

    public void setDuration(int duration) {
        this.duration = duration;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
 
  • We defined a class Course with fields like id, name, duration.
  • We define the setter and getter function for these
  • We set the id to be auto generated and also we set the name for this column to be C_ID

Listing 2: Student class

package model;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;

/**
 *
 * @author Anurag
 */
@Entity
public class Stu3 implements Serializable {

    private Long id;
    private String name;
    private List<Course> c;

    public Stu3() {
        c = new ArrayList<Course>();
    }

    @Id
    @GeneratedValue
    @Column(name = "STUDENT_ID")
    public Long getId() {
        return id;
    }

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

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "STUDENT_Course", joinColumns = {@JoinColumn(name = "STUDENT_ID")}, inverseJoinColumns = {@JoinColumn(name = "C_ID")})
    public List<Course> getC() {
        return c;
    }

    public void setC(List<Course> c) {
        this.c = c;
    }

    public String getName() {
        return name;
    }

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

 
  • We made a student class with fields like id ,name. We also made a variable c which can contain course
  • We made setter and getter function for each field
  • We used @Id and @GeneratedValue because we will use the field id as a primary key and its value will be auto generated
  • For implementing many to many mapping we use @ManyToMany(cascade = CascadeType.ALL)
  • @JoinTable(name = "STUDENT_Course", joinColumns = {@JoinColumn(name = "STUDENT_ID")}, inverseJoinColumns = {@JoinColumn(name = "C_ID")}) This is used to make a third table named Student_course which will have two columns student_id from the student(stu) class and C_ID from the course class.

Now we will define the configuration file:

Listing 3: hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernateArt</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">csanurag</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.current_session_context_class">thread</property>
        <mapping class="model.Stu3"/>
        <mapping class="model.Course"/>
    </session-factory>
</hibernate-configuration>
 
  • We defined the configuration parameter for the database
  • We also defined the mapping class for both the classes

Now we will define the Utility class which will be used to obtain instance of session factory

Listing 4: Utility class

package Main;

/**
 *
 * @author Anurag
 */
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class Utility {

    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {

            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

Lastly we will make a class which will make this all work.

Listing 5: App2 class

package Main;

/**
 *
 * @author Anurag
 */
import model.Course;
import model.Stu3;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class App2 {

    public static void main(String args[]) {

        SessionFactory sf = Utility.getSessionFactory();
        Session s = sf.getCurrentSession();
        Transaction tx = s.beginTransaction();
        Course f = new Course("J2EE", 12);
        Course f2 = new Course("Hibernate", 6);
        Stu3 s1 = new Stu3();
        Stu3 s2 = new Stu3();

        s1.setName("Anurag");
        s1.getC().add(f);
        s1.getC().add(f2);

        s2.setName("XYZ");
        s2.getC().add(f);

        s.save(s1);
        s.save(s2);
        tx.commit();
    }
}
 
  • Firstly, We made a session instance with help of session factory object.
  • Now we start the transaction and made two object for course
  • Now we make two student object .
  • The first student is set to have both the courses and the second student is set to have one of the courses selected by first student. So in this case multiple students have opted for one course. Similarly we see that both courses belong to first user so multiple course belong to single user.
  • We save the session.
  • We commit the transaction to make the changes permanent
  • When the program is run then three table named Stu3, Courses, student_course are made and the student record have many to many dependency on the course table.Actually the table student_course will contain the mapping between 2 tables and have values(For this program) (1,1) , (1,2) and (2,1)



Resources:

 

Hibernate many to many relationship

 

Hibernate official

saravanagumar 發表在 痞客邦 留言(0) 人氣()

The important piece of all this is that these these are all people without a technical background.

They come from careers where software was not a large part of their job. The need for learning software from a more human focused vantage point is clear.

It is likely that college will persist as the place to learn deeply technical things and bootcamps will be the place to dip your toes in the water.

Everything about computers that exists today was created by humans. It’s all a product of our imaginations and hard work. We have the tools for anyone to learn it.

The path to becoming a programmer is simple. You start at a point on the spectrum where you feel most comfortable and you work your way towards the middle.

The path to becoming a programmer is simple. You start at a point on the spectrum where you feel most comfortable and you work your way towards the middle. The middle ground is a place where people are equally comfortable with people and computers. It’s the future we’ve dreamed about where most people are able to write their own software to solve their problems.

If you start on the deeply technical side of the spectrum, you’ll be best served by figuring out how to apply your technical skills to solve human problems. All the hard work and innovative software you create can be used by thousands of people to solve their problems in unique ways.

If you start on the human side, learning technical skills and programming will give you a tremendous advantage in solving those human problems you work on every day. Maybe that nagging issue you can’t seem to fix is solvable by writing your own tool to improve communication.

The important thing to realize is that there’s no one way to start and no one direction to go. If there were, everyone would be doing this and it would be easy. But you should keep trying because coding is one of the most valuable and creative things you could ever do. You can literally build things out of thin air that don’t exist yet.

And one day you’ll step back from the computer and realize you finally get it. There’s no feeling like it. As Neil Gaiman says, “Perfection is like chasing the horizon. Keep moving.”

As you move up the chain, you can see things shift more towards humans.

Assembly is introduced to make the 1s and 0s more memorable for us.

C is designed to be an easier level than assembly but you still have to heavily think about how the internals of a computer works.

C++ begins to introduce some human concepts into the language so we can represent ideas better in code.

Java builds upon the ideas of C++ but abstracts away the internals of the computer as best it can. You don’t need to care about how things inside your computer like RAM is used as much.

Python takes another step towards humans and focuses on a syntax that’s more readable for humans but still has a lot of the structure inside it.

Ruby is focused on flexibility. They want your code to be like writing a story or a poem. Sure, you still have to worry about how the computer works was somewhat, but even less so than Python.

 

RESOURCES:

 

JAVA TRAINING INSTITUTE IN CHENNAI

 

JAVA WIKIBOOK

文章標籤

saravanagumar 發表在 痞客邦 留言(0) 人氣()

If you are planning for Java certification, here is a Java certification path for you to give the best shot at the right time. For top organizations, certification is taken as the proof of knowledge that showcases your skills to the outer world.

Oracle is the most desirable certification and usually preferred by software developers around the world. This would not be saying wrong that Java certification keeps you ahead of the crowd when you apply for Java jobs in the technical marketplace.

First of all, you need to be sure on latest Java version. Java 9 is the most recent version that completely focuses on the modularization concept to speed up overall execution and implementation time.

The best idea is to start with Java SE 9 certification that covers all basic concepts of Java and OOPs. You would get complete details of the certification on the Oracle site with examples and topics included in the certification.

To get the certification, you need to understand each and every concept of Java deeply. Once you are sure on the basics, then you can opt for advance certification too, like Java EE certification and many others.

Yes, it sounds little difficult, but you need to understand each concept well about the latest version. Every new release has some surprises and improvements that are made public for the developers and end-users. You have to be sure that all the concepts are learned well before you attempt for the certification.

This is true that you could improve your overall knowledge base with the Java certification. Every minute you spend in learning Java is worthwhile. This is true that certification demands thinking on the concept deeply. You just don’t have to look at the concept in brief as you were doing earlier. I am sure you would learn just amazing programming techniques that are actually interesting and workable in the real world. Also, you would be familiar with the latest Java version and the significant improvements made with the recent version.

 

Apart from that keep coding, coding, and coding! Whatever you see in your daily life, you just try to automate the concept through Java programs. For example- if you want to manage your daily expenses well then write your own Java app to automate the things. Remember, Programming is not about learning the existing things only, but it is all about “REINVENT THINKING”.

So, just keep moving and start coding your way to excellence.

Resources:

Java training in chennai

Core java training in chennai

 

文章標籤

saravanagumar 發表在 痞客邦 留言(0) 人氣()

1 2