Unit-2 Beans and Containers.

Slides:



Advertisements
Similar presentations
An Object/Relational Mapping tool Free and open source Simplifies storage of object data in a relational database Removes the need to write and maintain.
Advertisements

Persistence Jim Briggs 1. 2 Database connectivity: JDBC Java Database Connectivity An API for connecting Java programs (applications, applets and servlets)
Introduction to Spring Matt Wheeler. Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack – Basic.
1 Design patterns Lecture 4. 2 Three Important skills Understanding OO methodology Mastering Java language constructs Recognizing common problems and.
ASP.NET Programming with C# and SQL Server First Edition
Session-02.
Session-01. Hibernate Framework ? Why we use Hibernate ?
Spring Basic Bean wiring
Data Persistence and Object-Relational Mapping Slides by James Brucker, used with his permission 1.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Spring Framework. Spring Overview Spring is an open source layered Java/J2EE application framework Created by Rod Johnson Based on book “Expert one-on-one.
Think Possibility Integrating Web Applications With Databases.
UPortal Developers MIT August 2004 Persistence Strategy for uPortal 3 Mike DeSimone the r-smart group
Maven for building Java applications By Nalin De Zoysa
LINQ Boot Camp ADO.Net Entity Framework Presenter : Date : Mahesh Moily Nov 26, 2009.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 8 Object Oriented Programming in Java Advanced Topics Java Database.
Javax.sql and java.sql. java.sql Interface Connection public interface Connection extends WrapperWrapper A connection (session) with a specific database.
© D. Wong  Indexes  JDBC  JDBC in J2EE (Java 2 Enterprise Edition)
Using JavaBeans and Custom Tags in JSP Lesson 3B / Slide 1 of 37 J2EE Web Components Pre-assessment Questions 1.The _____________ attribute of a JSP page.
CHAPTER 14 USING RELATIONAL DATABASES TO PROVIDE OBJECT PERSISTENCE (ONLINE) © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Understanding the Bean Lifecycle An.
EJB Framework.  As we know, EJB is the center of the J2EE architecture that provides a sturdy framework for building enterprise applications. The major.
Spring core v3.x Prepared by: Nhan Le. History v3.0 Spring Expression Language Java based bean metadata v3.1 Cache Abstraction Bean Definition Profile.
Spring Framework. Spring Overview Spring is an open source layered Java/J2EE application framework Created by Rod Johnson Based on book “Expert one-on-one.
Introduction to Spring Matt Wheeler. Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack – Basic.
Stored procedures1 Stored procedures and functions Procedures and functions stored in the database.
Creative Commons Attribution- NonCommercial-ShareAlike 2.5 License Sakai Programmer's Café Sakai Montreal CRIM Workshop Introduction to Spring Framework,
JSTL Lec Umair©2006, All rights reserved JSTL (ni) Acronym of  JavaServer Pages Standard Tag Library JSTL (like JSP) is a specification, not an.
Andrew S. Budarevsky Adaptive Application Data Management Overview.
Spring Database Access Ojitha Kumanayaka Copyright © Virtusa, 2007.
Hibernate 3.0. What is Hibernate Hibernate is a free, open source Java package that makes it easy to work with relational databases. Hibernate makes it.
JPA / HIBERNATE CSCI 6370 Nilayan Bhattacharya Sanket Sable.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
DATABASE CONNECTIVITY TO MYSQL. Introduction =>A real life application needs to manipulate data stored in a Database. =>A database is a collection of.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
JAVA BEANS JSP - Standard Tag Library (JSTL) JAVA Enterprise Edition.
1 Spring Framework April, 2012 Lam Ho Lam To. © 2010 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 2 1.Spring Overview 2.Framework.
Hibernate Basics. Basics What is persistence? Persistence in Object Oriented Applications? Paradigm Mismatch.  The Problem of Granularity.  The Problem.
Dependency Injection JAVA EE - Spring Framework. Inner Beans As you know Java inner classes are defined within the scope of other classes, similarly,
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Data Access with Spring.
Basics of JDBC Session 14.
Java Programming: Advanced Topics 1 Enterprise JavaBeans Chapter 14.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool Used in data layer of applications Implements JPA.
Introduction – ORM, Helloworld Application
1 JDBC – Java Database Connectivity CS , Spring 2010.
Introduction to ORM Hibernate Hibernate vs JDBC. May 12, 2011 INTRODUCTION TO ORM ORM is a programming technique for converting data between relational.
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
CS422 Principles of Database Systems Object-Relational Mapping (ORM) Chengyu Sun California State University, Los Angeles.
CS520 Web Programming Object-Relational Mapping with Hibernate and JPA (I) Chengyu Sun California State University, Los Angeles.
CS 440 Database Management Systems Stored procedures & OR mapping 1.
Hibernate Java Persistence API. What is Persistence Persistence: The continued or prolonged existence of something. Most Applications Achieve Persistence.
CS520 Web Programming Spring – Web MVC Chengyu Sun California State University, Los Angeles.
HIBERNATE/Java Overview of technology for Hibernate by محمد حسن کاظمی پوران Master : M.M.Nematollahi.
CS520 Web Programming Spring – Inversion of Control Chengyu Sun California State University, Los Angeles.
Lec - 14.
Chengyu Sun California State University, Los Angeles
J2EE Lecture 6: Spring – IoC and Dependency Injection
ATS Application Programming: Java Programming
JDBC – Java Database Connectivity
A very brief introduction
Persistence – Iteration 4 Vancouver Bootcamp
CS520 Web Programming Spring – Inversion of Control
Java Beans Sagun Dhakhwa.
Java Data Persistence Using Hibernate
Database Fundamentals
Hibernate Bayu Priyambadha, S.Kom.
Chapter 8 Advanced SQL.
Enterprise Java Beans.
CS4961 Software Design Laboratory Understand Aquila Backend
Chengyu Sun California State University, Los Angeles
Presentation transcript:

Unit-2 Beans and Containers

Factory Pattern

Spring Container In a Spring-based application, your application objects will live within the Spring container. the container will create the objects, wire them together, configure them, and manage their complete lifecycle from the instance the new() method is called to the when finalize() method is called. The container is at the core of the Spring Framework. Spring’s container uses dependency injection (DI) to manage the components that make up an application

Categories of container implementations BeanFactory defined by the org.springframework.beans.factory.BeanFactory package. The simplest of containers, providing basic support for DI. ApplicationContext defined by the org.springframework.context.ApplicationContext package. ability to read textual messages from a properties file. ability to publish application events to interested event listeners

BeanFactory A bean factory is an implementation of the Factory design pattern. It is a class whose responsibility is to create and dispense beans; general-purpose factory. Because a bean factory knows about many objects within an application, it is able to create associations between collaborating objects as they are instantiated. When a bean factory hands out objects, those objects are fully configured, are aware of their collaborating objects, and are ready to use.

XmlBeanFactory A most commonly used is org.springframework.beans.factory.xml.XmlBeanFactory which loads its beans based on the definitions contained in an XML file. To create an XmlBeanFactory, you must pass an instance of org.springframework. core.io.Resource to the constructor. The Resource object will provide the XML to the factory. Most commonly used resource implementation is FileSystemResource. BeanFactory factory = new XmlBeanFactory(new FileSystemResource("c:/spring.xml"));

Lazily Loaded Beans The Beans are “lazily” loaded into bean factories i.e. while the bean factory will immediately load the bean definitions (the description of beans and their properties), the beans themselves will not be instantiated until they are needed.

Retrieving Bean To retrieve a bean from a BeanFactory, simply call the getBean() method, passing the ID of the bean you want to retrieve: MyBean myBean = (MyBean) factory.getBean("myBean"); When getBean() is called, the factory will instantiate the bean and set the bean’s properties using DI. With this, the life of a bean starts in the Spring container.

ApplicationContext An ApplicationContext is much the same as a BeanFactory. Both load bean definitions, wire beans together, and dispense beans upon request. But an ApplicationContext offers much more: Application contexts provide a means for resolving text messages, including support for internationalization. Application contexts can publish events to beans that are registered as listeners.

ApplicationContext Implementations of ApplicationContext are three that are commonly used: ClassPathXmlApplicationContext Loads a context definition from an XML file located in the classpath. FileSystemXmlApplicationContext Loads a context definition from an XML file in the file system.

ApplicationContext ApplicationContext context = To load an application context from within the application’s classpath using ClassPathXmlApplicationContext: ApplicationContext context = new ClassPathXmlApplicationContext(“spring.xml"); To load a FileSystemXmlApplicationContext: new FileSystemXmlApplicationContext("c:/spring.xml");  

ApplicationContext The difference between these uses of FileSystemXmlApplicationContext and ClassPathXmlApplicationContext is that FileSystemXmlApplicationContext will look for spring.xml in a specific location within the file system, whereas ClassPathXmlApplicationContext will look for spring.xml anywhere in the classpath.

BeanFactory & ApplicationContext In either case, you can retrieve a bean from an ApplicationContext just as you would from a BeanFactory: by using the getBean() method.

Bean Scope Prototype : Singleton : A new object is created each time it is injected. Singleton : The same object is returned each time it is injected.

Setter Injection <bean id=“cir" class="org.java.Circle"> <property name=“a" value=“10"/> <property name=“msg" value=“Hello"/> </bean>

Constructor Injection <bean id=“cir" class="org.java.Circle"> <constructor-arg value="10" index="1"/> <constructor-arg value="Hello"/> </bean>

Constructor Injection <bean id="tri" class="org.java.Triangle"> <constructor-arg type="int" value="10"/> </bean>

Autowiring So far you’ve seen how to wire all of your bean’s properties using either the <constructor-arg> or the <property> element. In a large application, however, all of this explicit wiring can result in a lot of XML. Rather than explicitly wiring all of your bean’s properties, you can have Spring automatically figure out how to wire beans together by setting the autowire property on each <bean> that you want Spring to autowire. The autowiring in specified at the autowire attribute inside <bean/>. The four types of autowiring:

Autowiring ■ byname:: Attempts to find a bean in the container whose ID is the same as the name of the property being wired. If a matching bean is not found, the property will remain unwired. ■ byType:: Attempts to find a single bean in the container whose type matches the type of the property being wired. If no matching bean is found, the property will not be wired. If more than one bean matches, an org.springframework.beans.factory.UnsatisfiedDependencyException will be thrown.

Autowiring ■ constructor:: Tries to match up one or more beans in the container with the parameters of one of the constructors of the bean being wired. In the event of ambiguous beans or ambiguous constructors, an org.springframework. beans.factory.UnsatisfiedDependencyException will be thrown. ■ autodetect:: Attempts to autowire by constructor first and then using byType. Ambiguity is handled the same way as with constructor and byType wiring.

Summary Factory Method Adding JARs Spring Containers getBean() BeanFactory ApplicationContext getBean() <property> <constrtuctor-arg> Type Index Injecting Object Reference Point Class Inner Beans Autowire byname byType constructor

Wiring Collection Value and ref are only useful when your bean’s properties are singular. Spring offers four types of collection configuration elements when configuring collection of values.

Injecting Collection <list> This helps in wiring ie injecting a list of values, allowing duplicates. <set> This helps in wiring a set of values but without any duplicates. <map> This can be used to inject a collection of name-value pairs where name and value can be of any type. <props> This can be used to inject a collection of name-value pairs where the name and value are both Strings.

<list> and <set> <list> and <set> elements are useful when configuring properties that are either array or some implementation of java.util.Collection.

<map> and <props> <map> and <props> these two elements are correspond to collection that are java.util.Map and java.util.Properties. The java.util.Map interface represents a mapping between a key and a value. The Map interface is not a subtype of the Collection interface. Therefore it behaves a bit different from the rest of the collection types.

<map> and <props> The java.util.Properties class which represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string.

Java.util.List public interface List<E> extends Collection<E> E - the type of elements in this list. Syntax : private List<E> var_name;

Java.util.List private List<Integer> points; <property name="points"> <list> <value>1</value> <value>2</value> </list> </property>

Java.util.List private List<Point> points; <property name="points"> <list> <ref bean="one"/> <ref bean="two"/> </list> </property>

Java.util.Set public interface Set<E> extends Collection<E> E - the type of elements maintained by this set. Syntax : private Set<E> var_name;

Java.util.Set private Set<Integer> points; <property name="points"> <set> <value>1</value> <value>2</value> </set> </property>

Java.util.Set private Set<Point> points; <property name="points"> <set> <ref bean="one"/> <ref bean="two"/> </set> </property> NOTE :- *[one,two,three] are some external bean definition.

Java.util.Map Map<K,V> K - the type of keys maintained by this map. V - the type of mapped values Syntax : Private Map<K,V> var_name;

Java.util.Map private Map<Integer, Integer> points; <property name="points"> <map> <entry key="1" value="10" /> <entry key="2" value="20" /> <entry key="3" value="30" /> </map> </property>

Java.util.Map System.out.println("Key :"+a1); for (Integer a1 : points.keySet()) { System.out.println("Key :"+a1); System.out.println("Value :"+getPoints().get(a1)); }

Java.util.Map private Map<Integer, Point> points; <property name="points"> <map> <entry key="1" value-ref=“one" /> <entry key="2" value-ref=“two" /> <entry key="3" value-ref=“three" /> </map> </property> NOTE :- *[one,two,three] are some external bean definition.

Java.util.Map for(int key : points.keySet()){ } s.o.p(“Key :”+key); s.o.p(“Value : (“+getPoints().get(key).getX()+”,”+getPoints().get(key).getY()+”)”); }

Java.util.Properties public class Properties extends Hashtable<Object,Object> Syntax : private Properties var_name;

Java.util.Properties private Properties pros; <property name="pros"> <props> <prop key="admin">admin@nospam.com</prop> <prop key="support">support@nospam.com</prop> </props> </property>

Java.util.Properties for(Object key : points.keySet()){ } s.o.p(“Key :”+key); s.o.p(“Value : (“+getPoints().getProperty(key),null)); }

Read from Properties file org.springframework.context.support.ResourceBundleMessageSource basename basenames <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basenames“ > <list> <value>myMsg</value> <value>myProperty</value> </list> </property> </bean>

Database connectivity Connection con; (import java.sql.Connection) Statement st; (import java.sql.Statement) dataSource : org.springframework.jdbc.datasource.DriverManagerDataSource driverClassName url username (Optional) password (Optional)

Database connectivity <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName” value="org.apache.derby.jdbc.ClientDriver"/> <property name="url" value="jdbc:derby://localhost:1527/myDB"/> <property name="username" value="app"/> <property name="password" value="app"/> </bean>

Database connectivity Data Definition Language (DDL) : (create ,alter ,drop etc.) con = getDs().getConnection(); st = con.createStatement(); st.execute(sql); Data Manipulation Language (DML) : (insert ,update , delete etc.) st.executeUpdate(sql);

Database connectivity Data Manipulation Language (DML) : (select) con = getDs().getConnection(); st = con.createStatement(); st.executeQuery(sql);

PreparedStatement PreparedStatement pst; pst = con.prepareStatement(sql); pst.setInt(1, getC().getC_id()); ResultSet rs = pst.executeQuery();

Using JDBC API Main getBean(“”circleDAO”); Circle int c_id; String c_name; circleDAOimpl Circle c; DataSource ds; <bean id=“Circle”/> <bean id=“DataSource”/>

Using JdbcTemplate Main getBean(“”circleDAO”); Circle int c_id; String c_name; circleDAOimpl Circle c; JdbcTemplate jdbcT; <bean id=“Circle”/> <bean id=“jdbcTemplate”/> <bean id=“DataSource”/>

JdbcTemplate Spring JdbcTemplate is a powerful mechanism to connect to the database and execute SQL queries. It internally uses JDBC API, but eliminates a lot of problems of JDBC API. org.springframework.jdbc.core.JdbcTemplate dataSource

JdbcTemplate Problems of JDBC API : We need to write a lot of code before and after executing the query, such as creating connection, statement, closing resultset, connection etc. We need to perform exception handling code on the database logic. Repetition of all these codes from one to another database logic is a time consuming task.

JdbcTemplate Advantage of Spring JdbcTemplate : Spring JdbcTemplate eliminates all the above mentioned problems of JDBC API. It provides you methods to write the queries directly.

JdbcTemplate <bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate"> <property name=" dataSource " ref="dataSource"/> </bean> NOTE :- *[dataSource] is the external bean definition.

JdbcTemplate Returning Integer value : Returning Long value : queryForInt("SELECT COUNT(*) FROM circle"); Returning Long value : queryForLong(“SELECT salary FROM employee");

JdbcTemplate Returning String value : Returning Class : String sql = "SELECT c_name FROM circle WHERE c_id = ? "; queryForObject(sql, new Object[] {circle_id}, String.class); Returning Class : String sql = "SELECT * FROM circle WHERE c_id = ?"; queryForObject(sql, new Object[] {circle_id}, new RowMapper<Circle>);

JdbcTemplate Returning List<Circle> : String sql = "SELECT * FROM circle"; queryForObject(sql, new RowMapper<Circle>);

JdbcTemplate Insert Data : String sql = "INSERT INTO circle VALUES(?,?)"; update(sql, new Object[]{getC().getC_id(),getC().getC_name()});

Hibernate

Hibernate An ORM tool. Implements JPA.

Hibernate Hibernate is an Object-Relational Mapping(ORM) solution for JAVA and it raised as an open source persistent framework created by Gavin King in 2001. It is a powerful, high performance Object-Relational Persistence and Query service for any Java Application. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from 95% of common data persistence related programming tasks.

Hibernate position

The Problem Class User Class ID Name Address Phone Date of Birth

The Problem Table Class ID Name Addr Phone DOB User Class ID Name Address Phone Date of Birth

The Problem Table Class ID Name Addr Phone DOB User Class ID Name Address Phone Date of Birth Relational Object Mapping

The Problem Mapping member variables to columns. Handling data types. Managing changes to object state.

Without Hibernate Database Configuration. The Model Object. Service method to create the model Object. Database Design. DAO method to save the object using SQL queries.

Using Hibernate Database Configuration – Hibernate configuration The Model Object – Annotations Service method to create the model object – Use The Hibernate API Database Design – Not needed..! DAO method to save the object using SQL queries – Not needed..!

Hibernate Advantages Hibernate takes care of mapping Java classes to database tables using XML files and without writing any line of code. Provides simple APIs for storing and retrieving Java objects directly to and from the database. If there is change in Database or in any table then the only need to change XML file properties. Abstract away the unfamiliar SQL types and provide us to work around familiar Java Objects. Hibernate does not require an application server to operate. Manipulates Complex associations of objects of your database. Minimize database access with smart fetching strategies. Provides Simple querying of data.

Hibernate Architecture Class Objects APIs

Hibernate Architecture Configuration : The Configuration object is the first Hibernate object you create in any Hibernate application and usually created only once during application initialization.  The Configuration object provides two keys components: 1.) Database Connection : This is handled through configuration files supported by Hibernate - hibernate.cfg.xml. 2.) Class Mapping Setup : This component creates the connection between the Java classes and database tables.

Hibernate Architecture SessionFactory : Configuration object is used to create a SessionFactory object which intern configures Hibernate for the application. The SessionFactory is heavyweight object so usually it is created during application start up and kept for later use.  You would need one SessionFactory object per database using a separate configuration file. So if you are using multiple databases then you would have to create multiple SessionFactory objects. The org.hibernate.SessionFactory interface provides factory method to get the object of Session.

Hibernate Architecture Session : A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database.  The session object provides an interface between the application and data stored in the database. The org.hibernate.Session interface provides methods to insert, update and delete the object.

Hibernate Architecture Transaction : A Transaction represents a unit of work with the database and most of the RDBMS supports transaction functionality. Transactions in Hibernate are handled by an underlying transaction manager and transaction (from JDBC or JTA). The org.hibernate.Transaction interface provides methods for transaction management.

Hibernate Architecture Query : Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects. A Query instance is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query.

Hibernate Architecture Criteria : Criteria object are used to create and execute object oriented criteria queries to retrieve objects.

Singular Database Configuration SessionFactory Session- 1 Transaction - 1 Session - 2 Transaction – 1 Transaction – 2

Multiple Database Configuration – 1 SessionFactory Session – 1 Transaction - 1 Session – 2 Configuration – 2 SessionFactory Session – 1 Transaction - 1 Session – 2