JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Read Only / Write Only Operations using Spring Data Repository Services

June 16, 2014 by Amr Mohammed Leave a Comment

As we’ve learned about Spring Data Repository in our previous tutorials, it’s an abstraction layer that built in top of persistent store that leverage the ability of accessing that store for achieving CRUD operations.

Spring Data Repository had integrated seamlessly with all of the aspects that might be concerned by a developer, one of those aspect is the security. Security is the one of the main reason for why specific technology gets more importance, while others didn’t. Repository provides an open gate for accessing the persistent store with full capacity for any one has the ability of gaining its reference; either those developers have developed sub classes for it or any one has the ability of consuming that repository through whatever technique they want even using the RESTful principle.

also read:

  • Spring Data JPA
  • Spring Data MongoDB
  • Spring Data Neo4j

However, there could be scenarios in which you would like to expose or restrict only the reading methods (The R in CRUD) or simply prevent the delete methods from being exposed in your repository interface that can be accessed by every one. Spring Data now allows you to custom base repository with the following steps:

  • Create an interface either extending Repository or annotated with @Repository Definition.
  • Add all of the methods that you want to expose it, and make sure they actually match the signatures of methods provided by the Spring Data base repository interfaces.
  • Use this interface as a base interface for the interface declarations for your entities.

To illustrate this, let’s assume we’d like to expose only the findAll() method while preventing all writable methods. End of this tutorial, you can download the source code used in this example.

1. Spring Data Read Only / Write Only

MySQL database contained two tables, Address and Employee along with a Spring Data Repository for handling the all operations that you may need.

The repositories being used in two ways, ReadOnly and WriteOnly. ReadOnly repositories will provide us the ability to read the data that located in the database, while the write will be used for writing operation.

The JSF managed bean will use a Spring service for locating both of these repositories for handling the required operations, meanwhile, those repositories are also exported as a RESTful services.

You’ll see the ReadOnly REST repository for persisting a record inside the database and at the other hand, you’ll try to retrieve all the records of the database through using  WriteOnly REST repository.

2. Defining Read/Write Base Repositories

Along with the mentioned steps for creating the required repositories, we’ve developed two repositories, one for read only and second for just write operation.

BaseReadOnlyRepository.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import java.io.Serializable;

import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.Repository;

@NoRepositoryBean

public interface BaseReadOnlyRepository<T, ID extends Serializable> extends Repository<T,ID>{
Iterable<T> findAll();
}

[/code]

BaseWriteOnlyRepository.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import java.io.Serializable;

import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.Repository;

@NoRepositoryBean

public interface BaseWriteOnlyRepository<T, ID extends Serializable> extends Repository<T,ID>{
<S extends T> S save(S entity);
}

[/code]

3. Read Only Repository Example

In this section, we’re going to develop an Employee and Address read only repository that extends the read only base repository defined above. We would see what’s the impact of using Read-Only repositories for achieving the operations of write.

EmployeeReadOnlyRepository.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.jpa.data.Employee;

import org.springframework.data.rest.core.annotation.RestResource;

@RestResource(rel="employeesReadOnly",path="employeeReadOnlyRepository")
public interface EmployeeReadOnlyRepository extends BaseReadOnlyRepository<Employee,Integer>{

}

[/code]

AddressReadOnlyRepository.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.jpa.data.Address;

import org.springframework.data.rest.core.annotation.RestResource;

@RestResource(rel="addressesReadOnly",path="addressReadOnlyRepository")
public interface AddressReadOnlyRepository extends BaseReadOnlyRepository<Address,Integer>{

}

[/code]

RegistraionService.java

[code lang=”java”]
package net.javabeat.springdata.beans;

import net.javabeat.springdata.repo.EmployeeReadOnlyRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RegistrationService {

@Autowired
private EmployeeReadOnlyRepository readOnlyRepository;

public EmployeeReadOnlyRepository getReadOnlyRepository() {
return readOnlyRepository;
}

public void setReadOnlyRepository(EmployeeReadOnlyRepository readOnlyRepository) {
this.readOnlyRepository = readOnlyRepository;
}

}

[/code]

RegistraionManagedBean.java

[code lang=”java”]
package net.javabeat.primefaces.managedbeans;

import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

import net.javabeat.springdata.beans.RegistrationService;
import net.javabeat.springdata.jpa.data.Employee;

import com.google.common.collect.Lists;

@ManagedBean
@SessionScoped
public class RegistrationManagedBean {

private Employee employee = new Employee();

private List<Employee> employees = new ArrayList<Employee>();

@ManagedProperty(value="#{registrationService}")
private RegistrationService service;

public Employee getEmployee() {
return employee;
}

public void setEmployee(Employee employee) {
this.employee = employee;
}

public List<Employee> getEmployees() {
this.employees = Lists.newArrayList(this.service.getReadOnlyRepository().findAll());
return employees;
}

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

public RegistrationService getService() {
return service;
}

public void setService(RegistrationService service) {
this.service = service;
}

}

[/code]

index.xhtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<f:view>
<h:form prependId="false">
<h2>JavaBeat Tutorials</h2>
<h2>Spring Data + Exposing/Hiding Repository Services</h2>
<h:panelGrid columns="2">
<h:outputText value="Enter Employee Name:"/>
<p:inputText value="#{registrationManagedBean.employee.employeeName}"></p:inputText>
<h:outputText value="Enter Employee Address Country:"/>
<p:inputText value="#{registrationManagedBean.employee.address.addressCountry}"></p:inputText>
<h:outputText value="Enter Employee Address City:"/>
<p:inputText value="#{registrationManagedBean.employee.address.addressCity}"></p:inputText>
</h:panelGrid>
<p:separator/>
<h:panelGrid columns="1" width="50%">
<p:dataTable value="#{registrationManagedBean.employees}" var="employee">
<p:column headerText="Employee’s Name">
<h:outputText value="#{employee.employeeName}"/>
</p:column>
<p:column headerText="Employee’s Country">
<h:outputText value="#{employee.address.addressCountry}"/>
</p:column>
<p:column headerText="Employee’s City">
<h:outputText value="#{employee.address.addressCity}"/>
</p:column>
</p:dataTable>
</h:panelGrid>
</h:form>
</f:view>
</html>
[/code]

By defining all of the required classes as mentioned, your project structure should look like:

Project Is not compilable

As you’ve seen, the project isn’t compilable for one reason in that the EmployeeReadOnlyRepository no longer support service like save.

Save Is not defined

At the same time, no issues was reported for findAll() neither inside the Spring service nor through using of RESTful service as you’d see. Below two provided snapshots, one for using of RegistrationService, while the other for RESTful access.

ReadOnly - Employees Fetched Successfully

ReadOnly - Employees Fetched Successfully - REST

Also, for simplicity, we’ve tried to post a record of employee using the ReadOnly repository via REST-SHELL and we’ve got the following error:

Employee Insertion Using ReadOnly Repository

While by using the same operation against WriteOnly repository, we’ve got success message, and the employee has been created.

Employee Insertion Using WriteOnly Repository

And by looking into records in the database, we’ve ensured that the employee has really located there.

Real Employee Insertion

You may be asking about employeeId, which is vary from the one used in the post; the answer is the MySQL database has ignored the employeeId that passed and it’s used its sequence. Look below for another request without providing employeeId.

Create Employee Without Providing EmployeeId Real Employee Insertion - Without Using EmployeeId

By using Spring or RESTful ways, the employees are fetched successfully from the MySQL. In the first snapshot, a primefaces view has been used for displaying the employees and their respective addresses and in the second the all employees and their respective addresses got displayed using the RESTful invocation.

4. Write Only Repository Example

In this section, we’re going to develop an Employee and Address write only repository that extends the write only base repository defined above. We would see what’s the impact of using Write-Only repositories for achieving the operations of read using the RESTful service.

EmployeeWriteOnlyRepository.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.jpa.data.Employee;

import org.springframework.data.rest.core.annotation.RestResource;

@RestResource(rel="employeesWriteOnly",path="employeeWriteOnlyRepository")
public interface EmployeeWriteOnlyRepository extends BaseWriteOnlyRepository<Employee,Integer>{

}

[/code]

AddressWriteOnlyRepository.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.jpa.data.Address;

import org.springframework.data.rest.core.annotation.RestResource;

@RestResource(rel="addressesWriteOnly",path="addressWriteOnlyRepository")
public interface AddressWriteOnlyRepository extends BaseWriteOnlyRepository<Address,Integer>{

}

[/code]

RegistrationService.java

[code lang=”java”]
package net.javabeat.springdata.beans;

import net.javabeat.springdata.repo.EmployeeWriteOnlyRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RegistrationService {

@Autowired
private EmployeeWriteOnlyRepository writeOnlyRepository;

public EmployeeWriteOnlyRepository getWriteOnlyRepository() {
return writeOnlyRepository;
}

public void setWriteOnlyRepository(
EmployeeWriteOnlyRepository writeOnlyRepository) {
this.writeOnlyRepository = writeOnlyRepository;
}

}

[/code]

RegistrationManagedBean.java

[code lang=”java”]
package net.javabeat.primefaces.managedbeans;

import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

import net.javabeat.springdata.beans.RegistrationService;
import net.javabeat.springdata.jpa.data.Employee;

@ManagedBean
@SessionScoped
public class RegistrationManagedBean {

private Employee employee = new Employee();

private List<Employee> employees = new ArrayList<Employee>();

@ManagedProperty(value="#{registrationService}")
private RegistrationService service;

public Employee getEmployee() {
return employee;
}

public void setEmployee(Employee employee) {
this.employee = employee;
}

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

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

public RegistrationService getService() {
return service;
}

public void setService(RegistrationService service) {
this.service = service;
}

public String register(){
this.service.getWriteOnlyRepository().save(this.employee);
return "";
}

}

[/code]

Likewise the impact of using the Read-Only repository, all of these services that are related to the Read will be eliminated and so the compiler will complaint about them.

Write Only - FindAll Causes Error

While the RESTful service won’t going far apart from the same result but using different words.

RESTful Read Employees Failed

Even if you’re using the REST-SHELL for reading an employees from WriteOnly Repository by executing the operation list which means findAll(), you will get the same result.

Read Employees By Using WriteOnly Repository - REST SHELL

5. Summary

Spring Data Repositories, have the ability of exposing/hiding the services provided by them. By making a base interface for just reading, all of those interfaces that extend it should serve as READ ONLY and if any part try to get read the data by READ ONLY repository it will get an error. The same issue when it comes for making interfaces for write.

This tutorial provides full explanation of how could you make your repositories for read only or for write. Also, it shows you the possible exceptions and errors that you may get when it comes to violate the rules of spring data repository.

Download Source Code

[wpdm_file id=114]

Filed Under: Spring Framework Tagged With: MySQL, Repositories, Spring Data

PrimeFaces + Spring Data using PagingAndSortingRepository Example

June 4, 2014 by Amr Mohammed Leave a Comment

In general, Spring Data JPA module implements the Spring Data Commons repository abstraction to ease repository implementations. As well as the Spring Data repository approach allows you to get rid of most of the implementation code by using a plain interface definition. You’ve leveraged repository implementation in your applications by creating an interfaces that extends the Repository that provided by the Spring Data infrastructure.

The Spring Data Repository captures the type of domain class as well as the type identity. But that isn’t the whole story, Spring Data, also provides different kinds of repositories.

So Spring Data provides you the following repositories.

  • Repository: A plain marker interface to let the Spring Data infrastructure pick up user defined repositories (configuration wise).
  • CrudRepository: Extends Repository and adds basic persistence methods like saving, finding and deleting entities.
  • PagingAndSortingRepositories: Extends CrudRepository and adds methods for accessing entities page by page ans sorting them by given criteria.

This tutorial guides you through a sample application to implement PrimeFaces, Spring Data and MySQL database using the PagingAndSortingRepositories to paginate the display of data. If you have any questions, please write it in the comments section.

Also read:

  • Spring Data JPA
  • Spring Data JPA + Querydsl
  • Spring Data + MongoDB 
  • Connect With Us : Google+ | Twitter | FaceBook

Lets look at how EmployeeRepository inherits the CrudRespository provided by Spring Data.

EmployeeRepository.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.jpa.data.Employee;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface EmployeeRepository extends CrudRepository<Employee,Integer>{
}
[/code]

The EmployeeRepository interface now will inherit all of these methods defined in the CurdRepository which lead us for repository containing those defined methods in the CurdRepository itself.

CrudRepository.java (This is Spring Data API implementation)

[code lang=”java”]
public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {
<S extends T> save(S entity);
<S extends T> Iterable<S> save(Iterable<S> entities);
T findOne(ID id);
Iterable<T> findAll();
void delete(ID id);
void delete(T entity);
void deleteAll();
}
[/code]

So, it contains methods to save a single entity as well as an Iterable of entities, finder methods for single entity or all entities, and delete methods of different flavors. PagingAndSortingRepository now in turn extends CrudRepository and adds methods to allow handing instances of Pagable and Sort into the generic findAll methods to actually access entities page by page.

This tutorial would give the PagingAndSortingRepository example application with user interface developed using PrimeFaces.

1. Database Tables

It’s just a depicts for the database models that used for implementing the enterprise sample that really depends on a real record.

Queries For Tables Creation

[code lang=”xml”]
CREATE TABLE `address` (
`addressId` bigint(20) NOT NULL AUTO_INCREMENT,
`addressCountry` varchar(45) DEFAULT NULL,
`addressCity` varchar(45) DEFAULT NULL,
PRIMARY KEY (`addressId`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
SELECT * FROM javabeat.employee;

CREATE TABLE `employee` (
`employeeId` bigint(20) NOT NULL AUTO_INCREMENT,
`employeeName` varchar(20) DEFAULT NULL,
`address` bigint(20) DEFAULT NULL,
PRIMARY KEY (`employeeId`),
KEY `FK_EMP_ADD` (`address`),
CONSTRAINT `FK_EMP_ADD` FOREIGN KEY (`address`) REFERENCES `address` (`addressId`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
[/code]

Address Table

Employee Table

Employee Foreign Key

2. Business Domain

As you knew before, the JPA contains two major parts, the mapping and the entity manager. Here, we’ll list the mapping classes, which will be used later for achieving the CRUD operations against defined database models mentioned in the previous section.

Address.java

[code lang=”java”]
package net.javabeat.springdata.jpa.data;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;

@Entity(name = "address")
public class Address {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer addressId;
private String addressCountry = "";
private String addressCity = "";

@OneToOne(cascade = CascadeType.ALL, mappedBy = "address")
private Employee employee;

public Employee getEmployee() {
return employee;
}

public void setEmployee(Employee employee) {
this.employee = employee;
}

public Integer getAddressId() {
return addressId;
}

public void setAddressId(Integer addressId) {
this.addressId = addressId;
}

public String getAddressCountry() {
return addressCountry;
}

public void setAddressCountry(String addressCountry) {
this.addressCountry = addressCountry;
}

public String getAddressCity() {
return addressCity;
}

public void setAddressCity(String addressCity) {
this.addressCity = addressCity;
}
}
[/code]

Employee.java

[code lang=”java”]
package net.javabeat.springdata.jpa.data;

import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

@Entity
public class Employee {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer employeeId;

@Basic(optional = false)
private String employeeName;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "Address")
private Address address = new Address();

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

public Integer getEmployeeId() {
return employeeId;
}

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

public String getEmployeeName() {
return employeeName;
}

public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
}
[/code]

3. Spring Data Repositories

PagingAndSortingRepository would be used for implementing the Spring Data operations. It is the specialized version of the CrudRepository interface. PagingAndSortingRepository defines extra methods for finding the rows by passing the page numbers. Lets look at the example implementation for AddressRepository and EmployeeRepository classes.

AddressRepositiry.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.jpa.data.Address;

import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface AddressRepository extends PagingAndSortingRepository<Address,Integer>{
}
[/code]

EmployeeRepository.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.jpa.data.Employee;

import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface EmployeeRepository extends PagingAndSortingRepository<Employee,Integer>{

}
[/code]

4. Spring Context Configuration

Here is the XML Spring configuration that used for configuring Spring beans, repositories and MySQL entity manager.

SpringContext.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

<!– For consider the using of annotations foe defining Spring Bean –>
<context:annotation-config />

<!– For defining Spring Bean –>
<context:component-scan base-package="net.javabeat.springdata.beans" />

<!– For bootstrapping the Spring Repository –>
<jpa:repositories base-package="net.javabeat.springdata.repo" />

<!– Necessary to get the entity manager injected into the factory bean –>
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

<!– Define EclipseLink JPA Vendor Adapter –>
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="databasePlatform"
value="org.eclipse.persistence.platform.database.MySQLPlatform" />
<property name="generateDdl" value="false" />
<property name="showSql" value="true" />
</bean>

<!– Entity Manager Factory –>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="SpringData"></property>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
</bean>

<!– Transaction Manager –>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<!– Enable Transactional Manner –>
<tx:annotation-driven transaction-manager="transactionManager" />

</beans>
[/code]

5. Spring Bean Service

Here is the Spring component had used for retaining a repositories proxies.

RegistrationService.java

[code lang=”java”]
package net.javabeat.springdata.beans;

import net.javabeat.springdata.repo.EmployeeRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RegistrationService {
@Autowired
private EmployeeRepository employeeRepository;

public EmployeeRepository getEmployeeRepository() {
return employeeRepository;
}

public void setEmployeeRepository(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
}
[/code]

6. Primefaces Managed Beans

It’s the managed bean that used for holding the business logic for the primefaces view.

RegistrationManagedBean.java

[code lang=”java”]
package net.javabeat.primefaces.managedbeans;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

import net.javabeat.springdata.beans.RegistrationService;
import net.javabeat.springdata.jpa.data.Employee;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;

@ManagedBean
@SessionScoped
public class RegistrationManagedBean {

private Employee employee = new Employee();

private List<Employee> employees = new ArrayList<Employee>();

private Page<Employee> page;

public RegistrationManagedBean(){
}

@PostConstruct
public void postInitialization(){
// Create & Initialize a Sort Object
Sort sort = new Sort(Direction.ASC,"employeeName");
// Create & Initialize a Page Object
page = this.service.getEmployeeRepository().findAll(new PageRequest(0, 3,sort));
// Fetch the employees from the page object
this.employees = page.getContent();
}

@ManagedProperty(value="#{registrationService}")
private RegistrationService service;

public Employee getEmployee() {
return employee;
}

public void setEmployee(Employee employee) {
this.employee = employee;
}

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

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

public String nextEmployees(){
if(page.hasNextPage()){
this.page = this.service.getEmployeeRepository().findAll(page.nextPageable());
this.employees = page.getContent();
}
return "";
}

public String previousEmployees(){
if(page.hasPreviousPage()){
this.page = this.service.getEmployeeRepository().findAll(page.previousPageable());
this.employees = page.getContent();
}
return "";
}

public String sortByEmployeeName(){
if(page != null){
if(page.getSort() != null){
Sort sort= new Sort(Direction.ASC,"employeeName");
this.page = this.service.getEmployeeRepository().findAll(new PageRequest(this.page.getNumber(), this.page.getSize(), sort));
this.employees = this.page.getContent();
}
}
return "";
}

public String sortByEmployeeId(){
if(page != null){
if(page.getSort() != null){
Sort sort= new Sort(Direction.ASC,"employeeId");
this.page = this.service.getEmployeeRepository().findAll(new PageRequest(this.page.getNumber(), this.page.getSize(), sort));
this.employees = this.page.getContent();
}
}
return "";
}

public RegistrationService getService() {
return service;
}

public void setService(RegistrationService service) {
this.service = service;
}

public Page<Employee> getPage() {
return page;
}

public void setPage(Page<Employee> page) {
this.page = page;
}

public String register(){
this.service.getEmployeeRepository().save(this.employee);
this.employee = new Employee();
return "";
}
}
[/code]

7. Faces Configuration File

For making the Spring beans referenced by the faces managed beans, your face-config.xml should look like

faces-config.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
version="2.2">
<application>
<resource-bundle>
<base-name>net.javabeat.jsf.application</base-name>
<var>msg</var>
</resource-bundle>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
</faces-config>
[/code]

8. Primefaces View

It’s the primefaces view page.

index.xhtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<f:view>
<h:form prependId="false">
<h2>JavaBeat Tutorials</h2>
<h2>Primefaces + Spring Data + PagingAndSortingRepository + MySQL</h2>
<div style="width: 700px;border: 1px;border-style: dotted;">
<h:panelGrid columns="2">
<h:outputText value="Enter Employee Name:"/>
<p:inputText value="#{registrationManagedBean.employee.employeeName}"></p:inputText>
<h:outputText value="Enter Employee Address Country:"/>
<p:inputText value="#{registrationManagedBean.employee.address.addressCountry}"></p:inputText>
<h:outputText value="Enter Employee Address City:"/>
<p:inputText value="#{registrationManagedBean.employee.address.addressCity}"></p:inputText>
</h:panelGrid>
<p:commandButton value="Register" action="#{registrationManagedBean.register}" ajax="false"/>
<p:separator/>
<h:panelGrid columns="1" width="100%">
<p:dataTable value="#{registrationManagedBean.employees}" var="employee" style="width:100%">
<p:column headerText="Employee’s Name">
<h:outputText value="#{employee.employeeName}"/>
</p:column>
<p:column headerText="Employee’s Country">
<h:outputText value="#{employee.address.addressCountry}"/>
</p:column>
<p:column headerText="Employee’s City">
<h:outputText value="#{employee.address.addressCity}"/>
</p:column>
</p:dataTable>
<h:panelGrid columns="4" width="100%">
<p:commandButton value="Next Employees" action="#{registrationManagedBean.nextEmployees}" ajax="false"/>
<p:commandButton value="Previous Employees" action="#{registrationManagedBean.previousEmployees}" ajax="false"/>
<p:commandButton value="Sort By Employee Name" action="#{registrationManagedBean.sortByEmployeeName}" ajax="false"/>
<p:commandButton value="Sort By Employee Id" action="#{registrationManagedBean.sortByEmployeeId}" ajax="false"/>
</h:panelGrid>
</h:panelGrid>
</div>
</h:form>
</f:view>
</html>
[/code]

9. Web Deployment Descriptor

It’s the deployment descriptor for this sample application.

web.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" metadata-complete="true" version="2.5">
<context-param>
<description>State saving method: ‘client’ or ‘server’
(=default). See JSF Specification 2.5.2
</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
<context-param>
<param-name>javax.faces.application.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config/*.xml</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
</web-app>
[/code]

10. Maven Build File

This is maven build file used for building this application.

pom.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>next.javabeat.jsf</groupId>
<artifactId>JavaBeat-Primefaces-SpringData-PagingAndSortingRepository-MySQL</artifactId>
<packaging>war</packaging>
<version>1.0</version>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.7</java.version>
<junit.version>4.9</junit.version>
<slf4j.version>1.6.4</slf4j.version>
<logback.version>1.0.1</logback.version>
<log4j.version>1.2.14</log4j.version>

<servlet.version>2.5</servlet.version>
<jsp.version>2.1</jsp.version>
<jstl.version>1.2</jstl.version>
<taglibs-standard.version>1.1.2</taglibs-standard.version>

<maven.compiler.plugin>2.3.2</maven.compiler.plugin>
<maven.failsafe.plugin>2.4.3-alpha-1</maven.failsafe.plugin>

</properties>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>

<repositories>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>

<dependencies>
<!– Servlet –>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<!– Faces Implementation –>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.4</version>
</dependency>
<!– Faces Library –>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.4</version>
</dependency>
<!– Primefaces Version 5 –>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>5.0.RC2</version>
</dependency>
<!– JSP Library –>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<!– JSTL Library –>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<!– Spring Core –>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<!– Spring Web –>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<!– Google List Library –>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>r09</version>
</dependency>
<!– Dependencies for Eclipse JPA Persistence API –>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.0-RC1</version>
<exclusions>
<exclusion>
<groupId>org.eclipse.persistence</groupId>
<artifactId>commonj.sdo</artifactId>
</exclusion>
</exclusions>
</dependency>
<!– Spring Data Dependency –>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.5.2.RELEASE</version>
</dependency> <!– Dependency for MySql Java connector –>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
</dependencies>

</project>
[/code]

11. PagingAndSortingRepository Demo

The scenario implemented here contains of set of employees that could be paginated. For every single page the total amount of employees that shown inside is three. The user has the ability to add employees, see the next page, see the previous page and sorting by employee name and employee Id.

PagingAndSortingRepository - The Initial View
PagingAndSortingRepository - The Next Employees
PagingAndSortingRepository - Sorting By Employee Id

12. Summary

You’ve just developed a Spring Data application using PagingAndSortingRepository. That repository provides you a pagination feature for your data. If you have any questions. please write it in the comments section.

Download Source Code

[wpdm_file id=108]

Filed Under: Spring Framework Tagged With: MySQL, PrimeFaces, Spring Data, Spring Repository

PrimeFaces 5 + Spring Data + MySQL Integration

May 20, 2014 by Amr Mohammed Leave a Comment

This tutorial guides you through creating a web application that integrates between PrimeFaces 5, Spring Data and MySQL database. It’s important for you to learn the basics of the technologies PrimeFaces and Spring Data before start reading this tutorial.

Also read:

  • Spring Data JPA
  • Spring Data JPA + Querydsl
  • Spring Data + MongoDB 
  • Connect With Us : Google+ | Twitter | FaceBook

 

1. Tools Required

It’s the required tools for being able to develop this tutorial:

  • JDK 1.6+.
  • Tomcat 7+.
  • Spring 3.
  • Primefaces 5.
  • MySQL 5.

2. Java Beans (Business Domain)

Beans Address and Employees will be used as the entities for this tutorial.

Address.java

[code lang=”java”]
package net.javabeat.springdata.jpa.data;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;

@Entity(name = "address")
public class Address {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer addressId;
private String addressCountry = "";
private String addressCity = "";

@OneToOne(cascade = CascadeType.ALL, mappedBy = "address")
private Employee employee;

public Employee getEmployee() {
return employee;
}

public void setEmployee(Employee employee) {
this.employee = employee;
}

public Integer getAddressId() {
return addressId;
}

public void setAddressId(Integer addressId) {
this.addressId = addressId;
}

public String getAddressCountry() {
return addressCountry;
}

public void setAddressCountry(String addressCountry) {
this.addressCountry = addressCountry;
}

public String getAddressCity() {
return addressCity;
}

public void setAddressCity(String addressCity) {
this.addressCity = addressCity;
}
}
[/code]

Employee.java

[code lang=”java”]
package net.javabeat.springdata.jpa.data;

import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

@Entity
public class Employee {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer employeeId;

@Basic(optional = false)
private String employeeName;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "Address")
private Address address = new Address();

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

public Integer getEmployeeId() {
return employeeId;
}

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

public String getEmployeeName() {
return employeeName;
}

public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
}
[/code]

3. Persistence Context

Here is the required persistence configuration, which contains the targeted database schema and its credential details and any additional configuration required like logging level and etc. Also this persistence configuration declare the above listed beans as the persistence entities.

persistence.xml

[code lang=”xml”]<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="SpringData"
transaction-type="RESOURCE_LOCAL">
<class>net.javabeat.springdata.jpa.data.Employee</class>
<class>net.javabeat.springdata.jpa.data.Address</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/JavaBeat" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.password" value="root" />
<property name="eclipselink.logging.level" value="OFF" />
</properties>
</persistence-unit>
</persistence>
[/code]

4. Spring Data Repositories

Here is the spring data repository for each of the above entities. If you are familiar with the spring data repositories, these are just an abstract behaviour where the real implementation would be provided by the spring container at run time. It is the greatest advantage of using the spring data.

AddressRepository.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.jpa.data.Address;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface AddressRepository extends CrudRepository<Address,Integer>{}
[/code]

EmployeeRepository.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.jpa.data.Employee;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface EmployeeRepository extends CrudRepository<Employee,Integer>{}
[/code]

5. Spring Service

It’s just a spring bean that used for preventing the presentation layer talking directly with the repository. It’s just a type of orchestration that you would use. Spring bean will contain an instance of those defined repositories.

RegistrationService.java

[code lang=”java”]
package net.javabeat.springdata.beans;

import net.javabeat.springdata.repo.EmployeeRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RegistrationService {
@Autowired
private EmployeeRepository employeeRepository;

public EmployeeRepository getEmployeeRepository() {
return employeeRepository;
}

public void setEmployeeRepository(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
}
[/code]

6. Spring Context Configurations

It’s the minimal amount of lines that should be updated in the spring context, from which the Spring Container could initialize the beans and any other environment information needed for the spring container.

SpringContext.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

<!– For consider the using of annotations foe defining Spring Bean –>
<context:annotation-config />

<!– For defining Spring Bean –>
<context:component-scan base-package="net.javabeat.springdata.beans" />

<!– For bootstrapping the Spring Repository –>
<jpa:repositories base-package="net.javabeat.springdata.repo" />

<!– Necessary to get the entity manager injected into the factory bean –>
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

<!– Define EclipseLink JPA Vendor Adapter –>
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="databasePlatform"
value="org.eclipse.persistence.platform.database.MySQLPlatform" />
<property name="generateDdl" value="false" />
<property name="showSql" value="true" />
</bean>

<!– Entity Manager Factory –>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="SpringData"></property>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
</bean>

<!– Transaction Manager –>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<!– Enable Transactional Manner –>
<tx:annotation-driven transaction-manager="transactionManager" />

</beans>
[/code]

7. Primefaces / JSF Faces Configuration

It’s the faces configuration XML file, defines the managed beans and spring expression resolver.

faces-config.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
version="2.2">
<application>
<resource-bundle>
<base-name>net.javabeat.jsf.application</base-name>
<var>msg</var>
</resource-bundle>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
</faces-config>
[/code]

8. Primefaces / JSF Managed Bean

It’s the user defined managed bean that contain the business logic of the registration business scenario used in this tutorial.

RegistrationManagedBean.java

[code lang=”java”]
package net.javabeat.primefaces.managedbeans;

import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

import net.javabeat.springdata.beans.RegistrationService;
import net.javabeat.springdata.jpa.data.Employee;

import com.google.common.collect.Lists;

@ManagedBean
@SessionScoped
public class RegistrationManagedBean {

private Employee employee = new Employee();

private List<Employee> employees = new ArrayList<Employee>();

@ManagedProperty(value="#{registrationService}")
private RegistrationService service;

public Employee getEmployee() {
return employee;
}

public void setEmployee(Employee employee) {
this.employee = employee;
}

public List<Employee> getEmployees() {
this.employees = Lists.newArrayList(this.service.getEmployeeRepository().findAll());
return employees;
}

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

public RegistrationService getService() {
return service;
}

public void setService(RegistrationService service) {
this.service = service;
}

public String register(){
this.service.getEmployeeRepository().save(this.employee);
this.employee = new Employee();
return "";
}
}
[/code]

9. Primefaces View

It’s the view that will be used for presenting the required primefaces UI components for Employee & Address registration business scenario.

index.xhtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<f:view>
<h:form prependId="false">
<h2>JavaBeat Tutorials</h2>
<h2>Primefaces + Spring Data + MySQL</h2>
<h:panelGrid columns="2">
<h:outputText value="Enter Employee Name:"/>
<p:inputText value="#{registrationManagedBean.employee.employeeName}"></p:inputText>
<h:outputText value="Enter Employee Address Country:"/>
<p:inputText value="#{registrationManagedBean.employee.address.addressCountry}"></p:inputText>
<h:outputText value="Enter Employee Address City:"/>
<p:inputText value="#{registrationManagedBean.employee.address.addressCity}"></p:inputText>
</h:panelGrid>
<p:commandButton value="Register" action="#{registrationManagedBean.register}" ajax="false"/>
<p:separator/>
<h:panelGrid columns="1" width="50%">
<p:dataTable value="#{registrationManagedBean.employees}" var="employee">
<p:column headerText="Employee’s Name">
<h:outputText value="#{employee.employeeName}"/>
</p:column>
<p:column headerText="Employee’s Country">
<h:outputText value="#{employee.address.addressCountry}"/>
</p:column>
<p:column headerText="Employee’s City">
<h:outputText value="#{employee.address.addressCity}"/>
</p:column>
</p:dataTable>
</h:panelGrid>
</h:form>
</f:view>
</html>
[/code]

10. Web Deployment Descriptor

It’s the required XML file that used by the Java EE container for understanding of the web application that will be getting deployed.

web.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" metadata-complete="true" version="2.5">
<context-param>
<description>State saving method: ‘client’ or ‘server’
(=default). See JSF Specification 2.5.2
</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
<context-param>
<param-name>javax.faces.application.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config/*.xml</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
</web-app>
[/code]

11. PrimeFaces 5 + Spring Data + MySQL Demo

Primefaces Spring Data Registration View
Primefaces Spring Data Registered Employee

12. Database Records

Primefaces Registered Employees

13. Summary

Finally, we have  implemented a web application that uses the PrimeFaces 5, Spring Data & MySQL. If you have any questions, please write it in the comments section.

Download Source Code

[wpdm_file id=101]

Filed Under: Spring Framework Tagged With: MySQL, Primefaces 5, Spring Data, Spring JPA

Connect To MySQL With JDBC Driver

November 11, 2013 by Krishna Srinivasan Leave a Comment

Here is an example to connect your JDBC code to MySQl database. You have to download mysql.jar for the JDBC driver class from here.

[code]
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username", "password");
conn.close();
[/code]

 

[code lang=”java”]
package javabeat.net.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class MySQLConnectionExample {
public static void main(String[] argv) {

try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Problem in loading the MySQL Driver class!!!");
e.printStackTrace();
return;
}

Connection connection = null;

try {
//Get the connection object
connection = DriverManager
.getConnection("jdbc:mysql://<host>:3306/<dbname>","<username>", "<password>");

} catch (SQLException e) {
System.out.println("Problem in establishing connection!!");
e.printStackTrace();
return;
}

if (connection != null) {
System.out.println("Connection created successfully!!");
} else {
System.out.println("Problem in establishing connection!!");
}
}
}

[/code]

If you are not copying the mysql.jar file in the classpath, you will get the following error.

[code]
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:188)
at javabeat.net.db.MySQLConnectionExample.main(MySQLConnectionExample.java:11)
[/code]

Filed Under: MYSQL Tagged With: JDBC, MySQL

Hibernate, Maven and HSQL – Example Project (Using Annotations)

March 11, 2013 by Manisha Patil Leave a Comment

In this tutorial we will write a simple Java project to demonstrate Hibernate, HSQL and Maven using Java 5 Annotations. For this we will use our previous example in the post Hibernate, Maven and HSQL – Example Project (XML Mapping)) as base and convert it from XML Mapping to Annotation.
HSQL database is used to make the project simple, as we can use in-memory database and we would need only a JAR file to be included in our project. If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe here. If you are beginner for hibernate, please read the articles about introduction to hibernate, interceptors in hibernate and spring & hibernate integration. We also recommend good reference books for learning hibernate in our post about hibernate books.hibernate.

Following are the tools and technologies required for this project:

    1. Java JDK 5 or above
    2. Eclipse IDE 3.2 or above
    3. Maven 3.0 or above
    4. Hibernate 3.0 or above (Download from http://hibernate.org/downloads)
    5. HsqlDB (Download from http://hsqldb.org/)

1. Generating Maven Java project compatible with Eclipse

Follow the steps in the post Hibernate, Maven and HSQL – Example Project (XML Mapping)) to create project structure. Or you can directly download the source code from above post in Eclipse and rename the project in eclipse as HibernateHelloWorldAnnotation.

2.Updating the Hibernate dependency in pom.xml

As we are going to use Annotation mapping in Hibernate we will update our existing pom.xml file as below:

[java]
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.javabeat.hibernate</groupId>
<artifactId>HibernateHelloWorldXML</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>HibernateHelloWorldXML</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!– Hibernate library dependecy start –>
<b> <dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>4.1.9.Final</version>
</dependency></b>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.2.9</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>hibernate-tools</groupId>
<artifactId>hibernate-tools</artifactId>
<version>3.2.3.GA</version>
</dependency>
<dependency>
<groupId>jta</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.11</version>
</dependency>
<dependency>
<groupId>oscache</groupId>
<artifactId>oscache</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>persistence-api</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
<!– Hibernate library dependency end –>
</dependencies>
</project>
[/java]

As a next step, let’s execute the following command so that maven will download all the required JARs and update eclipse classpath. Go to the directory of the project (in our case it is C:\HibernateHelloWorldXML) and execute the following command:

[java]
mvn eclipse:eclipse
[/java]

This step is optional. If your Eclipse has Maven plugin installed in your IDE (Latest eclipse comes with this plugin built-in) you can just enable Maven dependencies by following these instructions : Right click on project > Maven > Enable Dependency Management.

3. Delete the unused Hibernate Mapping file

The file src\main\resources\net\javabeat\hibernate\Contact.hbm.xml is not required anymore. Delete this file from the project.

4. Update the Model class file

We will add simple annotations to the model class (src\main\java\net\javabeat\hibernate\Contact.java) as below:

[java]
package net.javabeat.hibernate;

import java.io.Serializable;

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

/**
* Model class for Conact
*/
@Entity
@Table(name="CONTACT")
public class Contact implements Serializable {
@Id
@GeneratedValue
private Integer contactId;

@Column(name="name")
private String name;

public Contact() {
}

public Integer getContactId() {
return contactId;
}

public void setContactId(Integer contactId) {
this.contactId = contactId;
}

public String getName() {
return name;
}

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

}
[/java]

5.Update the Hibernate Utility class

In our previous post for XML mapping, we were using Configuration class to generate SessionFactory object. In HibernateUtil we had following line of code:

[java]
sessionFactory = new Configuration().configure().buildSessionFactory();
[/java]

We will update this and use AnnotationConfiguration instead of Configuration(). The updated HibernateUtil.java file is as below:

[java]
package net.javabeat.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
[/java]

6. Update Hibernate Configuration file

The configuration file hibernate.cfg.xml, needs to be changed to add the new Annotation based entity class Contact.java instead of old XML Mapping Contact.hbm.xml. The updated src\main\resources\hibernate.cfg.xml is as below:

[java]
<?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">
<?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>
<!– Database connection settings, Connect to HSQL, IN Memory –>
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:mem:test</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>

<!– JDBC connection pool (use the built-in) –>
<property name="connection.pool_size">1</property>
<property name="show_sql">true</property><property name="format_sql">true</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!–create the database schema on startup if required –>
<property name="hbm2ddl.auto">update</property>
<mapping class="net.javabeat.hibernate.Contact"></mapping>
</session-factory>
</hibernate-configuration>
[/java]

Here we have replaced

[java]
<mapping resource="net/javabeat/hibernate/Contact.hbm.xml"></mapping>
[/java]

with

[java]
<mapping class="net.javabeat.hibernate.Contact"></mapping>
[/java]

7. Final project structure

Once you have created all these source files, your project structure should look like following:
final_proj_stuct_annotation

8. Execution of the above code

Now let us execute the code we created above. Let’s run the App class.
Right click on App.java >Run As > Java Application.
On start of each thread, a database schema will be created and the following actions will happen.

    • Each time a new thread starts the database schema will change the existing one as we have set hbm2ddl.auto option to update.
    • The SQL statement generated gets displayed on the console. This is set using the show_sql option in the hibernate configuration file.

Output on the console:

[java]
Maven + Hibernate + HSQL
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate:
insert
into
CONTACT
(contactId, name)
values
(null, ?)
Hibernate:
insert
into
CONTACT
(contactId, name)
values
(null, ?)
Hibernate:
insert
into
CONTACT
(contactId, name)
values
(null, ?)
Hibernate:
select
contact0_.contactId as contactId0_,
contact0_.name as name0_
from
CONTACT contact0_
Jiya
Manisha
Riya
[/java]

Summary

In this post we updated our previous Java project from post Hibernate, Maven and HSQL – Example Project (XML Mapping)) using Maven and made it compatible with eclipse. Then we updated the Hibernate configuration file and also deleted the hibernate mapping file. We also updated our Model class with Java annotations. We used a simple HSQL database, to insert records into CONTACT table and also listed these records. In the next article we shall look into Hibernate Association (One-to-one mapping(XML mapping)). If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe here

Filed Under: Hibernate Tagged With: Hibernate, MySQL

JDBC connection in JDeveloper with MySQL database

November 25, 2008 by Krishna Srinivasan Leave a Comment

The Java Database Connectivity (JDBC) API is used to access a SQL database from a Java application. JDBC also supports tabular data sources, such as a spreadsheet. Oracle JDeveloper is a free Integrated Development Environment (IDE) for modeling, developing, debugging, optimizing, and deploying Java applications. JDeveloper 10g is used to develop J2EE applications comprising the JSPs, EJBs, Struts, Servlets, and the Java classes that may require accessing a database table in the Oracle 10g Database, or a third-party database. In this article by Deepak Vohra, we will see how to configure JDBC in the JDeveloper IDE.

also read:

  • Java Tutorials
  • Java EE Tutorials
  • Design Patterns Tutorials
  • Java File IO Tutorials

Unlike Eclipse IDE, which requires a plug-in, JDeveloper has a built-in provision to establish a JDBC connection with a database. JDeveloper is the only Java IDE with an embedded application server, the Oracle Containers for J2EE (OC4J). This database-based web application may run in JDeveloper without requiring a third-party application server. However, JDeveloper also supports third-party application servers. Starting with JDeveloper 11, application developers may point the IDE to an application server instance (or OC4J instance), including third-party application servers that they want to use for testing during development. JDeveloper provides connection pooling for the efficient use of database connections. A database connection may be used in an ADF BC application, or in a JavaEE application.

A database connection in JDeveloper may be configured in the Connections Navigator. A Connections Navigator connection is available as a DataSource registered with a JNDI naming service. The database connection in JDeveloper is a reusable named connection that developers configure once and then use in as many of their projects as they want. Depending on the nature of the project and the database connection, the connection is configured in the bc4j.xcfg file or a JavaEE data source. Here, it is necessary to distinguish between data source and DataSource. A data source is a source of data; for example an RDBMS database is a data source. A DataSource is an interface that represents a factory for JDBC Connection objects. JDeveloper uses the term Data Source or data source to refer to a factory for connections. We will also use the term Data Source or data source to refer to a factory for connections, which in the javax.sql package is represented by the DataSource interface. A DataSource object may be created from a data source registered with the JNDI (Java Naming and Directory) naming service using JNDI lookup. A JDBC Connection object may be obtained from a DataSource object using the getConnection method. As an alternative to configuring a connection in the Connections Navigator a data source may also be specified directly in the data source configuration file data-sources.xml. In this article we will discuss the procedure to configure a JDBC connection and a JDBC data source in JDeveloper 10g IDE. We will use the MySQL 5.0 database server and MySQL Connector/J 5.1 JDBC driver, which support the JDBC 4.0 specification. In this article you will learn the following:

  • Creating a database connection in JDeveloper Connections Navigator.
  • Configuring the Data Source and Connection Pool associated with the connection configured in the Connections Navigator.
  • The common JDBC Connection Errors
  • Before we create a JDBC connection and a data source we will discuss connection pooling and DataSource.

Connection Pooling and DataSource

The javax.sql package provides the API for server-side database access. The main interfaces in the javax.sql package are DataSource, ConnectionPoolDataSource, and PooledConnection. The DataSource interface represents a factory for connections to a database. DataSource is a preferred method of obtaining a JDBC connection. An object that implements the DataSource interface is typically registered with a Java Naming and Directory API-based naming service. DataSource interface implementation is driver-vendor specific. The DataSource interface has three types of implementations:

Basic implementation: In basic implementation there is 1:1 correspondence between a client’s Connection object and the connection with the database. This implies that for every Connection object, there is a connection with the database. With the basic implementation, the overhead of opening, initiating, and closing a connection is incurred for each client session.

Connection pooling implementation: A pool of Connection objects is available, from which connections are assigned to the different client sessions. A connection pooling manager implements the connection pooling. When a client session does not require a connection, the connection is returned to the connection pool and becomes available to other clients. Thus, the overheads of opening, initiating, and closing connections are reduced.

Distributed transaction implementation: Distributed transaction implementation produces a Connection object that is mostly used for distributed transactions and is always connection pooled. A transaction manager implements the distributed transactions.

An advantage of using a data source is that code accessing a data source does not have to be modified when an application is migrated to a different application server. Only the data source properties need to be modified. A JDBC driver that is accessed with a DataSource does not register itself with a DriverManager. A DataSource object is created using a JNDI lookup and subsequently a Connection object is created from the DataSource object. For example, if a data source JNDI name is jdbc/OracleDS a DataSource object may be created using JNDI lookup. First, create an InitialContext object and subsequently create a DataSource object using the InitialContext lookup method. From the DataSource object create a Connection object using the getConnection() method:

[code lang=”java”]
InitialContext ctx=new InitialContext();
DataSource ds=ctx.lookup("jdbc/OracleDS");
Connection conn=ds.getConnection();
[/code]

The JNDI naming service, which we used to create a DataSource object is provided by J2EE application servers such as the Oracle Application Server Containers for J2EE (OC4J) embedded in the JDeveloper IDE.

A connection in a pool of connections is represented by the PooledConnection interface, not the Connection interface. The connection pool manager, typically the application server, maintains a pool of PooledConnection objects. When an application requests a connection using the DataSource.getConnection() method, as we did using the jdbc/OracleDS data source example, the connection pool manager returns a Connection object, which is actually a handle to an object that implements the PooledConnection interface.

A ConnectionPoolDataSource object, which is typically registered with a JNDI naming service, represents a collection of PooledConnection objects. The JDBC driver provides an implementation of the ConnectionPoolDataSource, which is used by the application server to build and manage a connection pool. When an application requests a connection, if a suitable PooledConnection object is available in the connection pool, the connection pool manager returns a handle to the PooledConnection object as a Connection object. If a suitable PooledConnection object is not available, the connection pool manager invokes the getPooledConnection() method of the ConnectionPoolDataSource to create a new PooledConnection object. For example, if connectionPoolDataSource is a ConnectionPoolDataSource object a new PooledConnection gets created as follows:

[code lang=”java”]
PooledConnection pooledConnection=connectionPoolDataSource.getPooledConnection();
[/code]

The application does not have to invoke the getPooledConnection() method though; the connection pool manager invokes the getPooledConnection() method and the JDBC driver implementing the ConnectionPoolDataSource creates a new PooledConnection, and returns a handle to it. The connection pool manager returns a Connection object, which is a handle to a PooledConnection object, to the application requesting a connection. When an application closes a Connection object using the close() method, as follows, the connection does not actually get closed.

[code lang=”java”]
conn.close();
[/code]

The connection handle gets deactivated when an application closes a Connection object with the close() method. The connection pool manager does the deactivation. When an application closes a Connection object with the close () method any client info properties that were set using the setClientInfo method are cleared. The connection pool manager is registered with a PooledConnection object using the addConnectionEventListener() method. When a connection is closed, the connection pool manager is notified and the connection pool manager deactivates the handle to the PooledConnection object, and returns the PooledConnection object to the connection pool to be used by another application. The connection pool manager is also notified if a connection has an error. A PooledConnection object is not closed until the connection pool is being reinitialized, the server is shutdown, or a connection becomes unusable.

In addition to connections being pooled, PreparedStatement objects are also pooled by default if the database supports statement pooling. It can be discovered if a database supports statement pooling using the supportsStatementPooling() method of the DatabaseMetaData interface. The PeparedStatement pooling is also managed by the connection pool manager. To be notified of PreparedStatement events such as a PreparedStatement getting closed or a PreparedStatement becoming unusable, a connection pool manager is registered with a PooledConnection manager using the addStatementEventListener() method. A connection pool manager deregisters a PooledConnection object using the removeStatementEventListener() method. Methods addStatementEventListener and removeStatementEventListener are new methods in the PooledConnection interface in JDBC 4.0. Pooling of Statement objects is another new feature in JDBC 4.0. The Statement interface has two new methods in JDBC 4.0 for Statement pooling: isPoolable() and setPoolable().

The isPoolable method checks if a Statement object is poolable and the setPoolable method sets the Statement object to poolable. When an application closes a PreparedStatement object using the close() method the PreparedStatement object is not actually closed. The PreparedStatement object is returned to the pool of PreparedStatements. When the connection pool manager closes a PooledConnection object by invoking the close() method of PooledConnection all the associated statements also get closed. Pooling of PreparedStatements provides significant optimization, but if a large number of statements are left open, it may not be an optimal use of resources. Thus, the following procedure is followed to obtain a connection in an application server using a data source:

  • Create a data source with a JNDI name binding to the JNDI naming service.
  • Create an InitialContext object and look up the JNDI name of the data source using the lookup method to create a DataSource object. If the JDBC driver implements the DataSource as a connection pool, a connection pool becomes available.
  • Request a connection from the connection pool. The connection pool manager checks if a suitable PooledConnection object is available. If a suitable PooledConnection object is available, the connection pool manager returns a handle to the PooledConnection object as a Connection object to the application requesting a connection.
  • If a PooledConnection object is not available the connection pool manager invokes the getPooledConnection() method of the ConnectionPoolDataSource, which is implemented by the JDBC driver.
  • The JDBC driver implementing the ConnectionPoolDataSource creates a PooledConnection object and returns a handle to it.
  • The connection pool manager returns a handle to the PooledConnection object as a Connection object to the application requesting a connection.
  • When an application closes a connection, the connection pool manager deactivates the handle to the PooledConnection object and returns the PooledConnection object to the connection pool.

ConnectionPoolDataSource provides some configuration properties to configure a connection pool. The configuration pool properties are not set by the JDBC client, but are implemented or augmented by the connection pool. The properties can be set in a data source configuration. Therefore, it is not for the application itself to change the settings, but for the administrator of the pool, who also happens to be the developer sometimes, to do so. Connection pool properties supported by ConnectionPoolDataSource are discussed in following table:

Connection Pool Property

Type

Description

maxStatements

int

Maximum number of statements the pool should keep open. 0 (zero)
indicates that statement caching is not enabled.

initialPoolSize

int

The initial number of connections the pool should have at the
time of creation.

minPoolSize

int

The minimum number of connections in the pool. 0 (zero)
indicates that connections are created as required.

maxPoolSize

int

The maximum number of connections in the connection pool. 0
indicates that there is no maximum limit.

maxIdleTime

int

Maximum duration (in seconds) a connection can be kept open
without being used before the connection is closed. 0 (zero) indicates that
there is no limit.

propertyCycle

int

The interval in seconds the pool should wait before implementing
the current policy defined by the connection pool properties.

maxStatements

int

The maximum number of statements the pool can keep open. 0
(zero) indicates that statement caching is not enabled.

Setting the Environment

Before getting started, we have to install the JDeveloper 10.1.3 IDE and the MySQL 5.0 database. Download JDeveloper from: http://www.oracle.com/technology/software/products/jdev/index.html. Download the MySQL Connector/J 5.1, the MySQL JDBC driver that supports JDBC 4.0 specification. To install JDeveloper extract the JDeveloper ZIP file to a directory. Log in to the MySQL database and set the database to test. Create a database table, Catalog, which we will use in a web application. The SQL script to create the database table is listed below:

[code]
CREATE TABLE Catalog(CatalogId VARCHAR(25)
PRIMARY KEY, Journal VARCHAR(25), Publisher VARCHAR(25),
Edition VARCHAR(25), Title Varchar(45), Author Varchar(25));
INSERT INTO Catalog VALUES(‘catalog1’, ‘Oracle Magazine’,
‘Oracle Publishing’, ‘Nov-Dec 2004’, ‘Database Resource Manager’, ‘Kimberly Floss’);
INSERT INTO Catalog VALUES(‘catalog2’, ‘Oracle Magazine’, ‘Oracle Publishing’,
‘Nov-Dec 2004’, ‘From ADF UIX to JSF’, ‘Jonas Jacobi’);
[/code]

MySQL does not support ROWID, for which support has been added in JDBC 4.0. Having installed the JDeveloper IDE, next we will configure a JDBC connection in the Connections Navigator. Select the Connections tab and right-click on the Database node to select New Database Connection.

jdbc-1

Click on Next in Create Database Connection Wizard. In the Create Database Connection Type window, specify a Connection Name—MySQLConnection for example—and set Connection Type to Third Party JDBC Driver, because we will be using MySQL database, which is a third-party database for Oracle JDeveloper and click on Next. If a connection is to be configured with Oracle database select Oracle (JDBC) as the Connection Type and click on Next.

jdbc-2

In the Authentication window specify Username as root (Password is not required to be specified for a root user by default), and click on Next. In the Connection window, we will specify the connection parameters, such as the driver name and connection URL; click on New to specify a Driver Class. In the Register JDBC Driver window, specify Driver Class as com.mysql.jdbc.Driver and click on Browse to select a Library for the Driver Class. In the Select Library window, click on New to create a new library for the MySQL Connector/J 5.1 JAR file. In the Create Library window, specify Library Name as MySQL and click on Add Entry to add a JAR file entry for the MySQL library. In the Select Path Entry window select mysql-connector-java-5.1.3-rcmysql-connector-java-5.1.3-rc-bin.jar and click on Select. In the Create Library window, after a Class Path entry gets added to the MySQL library, click on OK. In the Select Library window, select the MySQL library and click on OK. In the Register JDBC Driver window, the MySQL library gets specified in the Library field and the mysql-connector-java-5.1.3-rcmysql-connector-java-5.1.3-rc-bin.jar gets specified in the Classpath field. Now, click on OK. The Driver Class, Library, and Classpath fields get specified in the Connection window. Specify URL as jdbc:mysql://localhost:3306/test, and click on Next.

jdbc-3

In the Test window click on Test Connection to test the connection that we have configured. A connection is established and a success message gets output in the Status text area. Click on Finish in the Test window. A connection configuration, MySQLConnection, gets added to the Connections navigator.

jdbc-4

The connection parameters are displayed in the structure view. To modify any of the connection settings, double-click on the Connection node. The Edit Database Connection window gets displayed. The connection Username, Password, Driver Class, and URL may be modified in the Edit window. A database connection configured in the Connections navigator has a JNDI name binding in the JNDI naming service provided by OC4J. Using the JNDI name binding, a DataSource object may be created in a J2EE application. To view, or modify the configuration settings of the JDBC connection select Tools | Embedded OC4J Server Preferences in JDeveloper. In the window displayed, select Global | Data Sources node, and to update the data-sources.xml file with the connection defined in the Connections navigator, click on the Refresh Now button. Checkboxes may be selected to Create data-source elements where not defined, and to Update existing data-source elements.

jdbc-5

The connection pool and data source associated with the connection configured in the Connections navigator get listed. Select the jdev-connection-pool-MySQLConnection node to list the connection pool properties as Property Set A and Property Set B.

jdbc-6

The tuning properties of the JDBC connection pool may be set in the Connection Pool window. The different tuning attributes are listed in following table:

Tuning Attribute

Attribute Description

Default Value

Abandoned Connection Timeout

Interval (seconds) after which a connection acquired by a user
that has been inactive is returned to the cache.

-1 implies that the feature is not in effect.

Retry Interval

Interval (seconds) after which a failed connection attempt is
retried. Used with Max Connect Attempts.

1

Disable Connection Pooling

Specifies if application server’s connection pooling is to be
disabled. This attribute is available because some drivers provide connection
pooling inside the driver.

False

Inactivity Timeout

The number of seconds of inactivity after which an unused
connection is removed from the pool.

Inactivity Timeout

Initial Limit

The initial number of connections in the connection pool. If
value is greater than 0, the specified number of connections are pre-created
and available in the connection cache, thus reducing the time required to
build the cache to its optimal size.

0

Login Timeout

The number of seconds after which a login attempt is timed out.
0 implies that the system timeout value is used. If a system timeout is not
defined, a login attempt is not timed out.

0

Max Connect Attempts

The maximum number of connection attempts to a database. Used in
conjunction with retry interval.

3

Max Connections

The maximum number of available database connections in the
connection pool. A value of 0 or less implies that there is no maximum limit.

0

Min Connections

The minimum number of database connections in the connection
pool.

0

Select Property Set B to specify additional connection pool properties.

jdbc-7

The connection pool properties in Property Set B are discussed in the following table:

Property

Description

Default Value

Num Cached Statements

Specifies the maximum number of prepared and callable statements
that should be cached for each connection in each connection pool. Statement
caching increases system performance. A value greater than 0 enables
statement caching.

0

Property Check Interval

Specifies the time interval (seconds) after which property
values are checked for new values, and time out limits are implemented.

900

Time to Live Timeout

Specifies the maximum number of seconds a used connection may be
active, after which it is closed and returned to the connection pool. -1
indicates that the feature is not enabled.

-1

Used Connection Wait Timeout

Number of seconds for which a used connection remains unused
before being returned to the connection pool. Only applies if the maximum
numbers of connections that a connection pool may cache have been acquired by
clients, and a client requests a connection.

60

Validate Connections

Specifies if connections are to be validated, when given to a
client. Used in conjunction with Validate Connection Statements.

False

Validate Connection Statements

Specifies the SQL statements used to validate connections before
being acquired by a client.

None

The Connection Factory node specifies the Factory Class, User name, Password, Login Timeout, and connection URL. The factory class must implement one of the following interfaces: java.sql.Driver, javax.sql.DataSource, javax.sql.ConnectionPoolDataSource, javax.sql.XADataSource.

jdbc-8

The Managed DataSource node specifies the managed data sources associated with the connection, and which are data sources managed by the OC4J. A managed data source is an OC4J implementation of the javax.sql.DataSource interface that wraps a JDBC driver class, or data source class. Even if the factory class does not implement the javax.sql.DataSource interface, the OC4J implementation of the factory class implements the javax.sql.DataSource interface. A managed data source supports connection caching, global transaction management, and error handling, all provided by the OC4J. A managed data source is associated with a connection pool, and thus has the advantage of being able to specify the tuning parameters. The JNDI Name of the data source is specified in the managed data source window. The JNDI Name is in the jdbc/MySQLConnectionDS format, with MySQLConnection being the connection name configured in the Connections navigator.

jdbc-9

A connection MySQLConnection in the Connections navigator is available as a data source with the JNDI Name binding jdbc/MySQLConnectionDS. To obtain a connection from the data source, add a resource-ref element to the web application in which a connection is to be obtained. In a Servlet or JSP application, a connection may be obtained with the data source JNDI Name.

[code lang=”java”]
InitialContext initialContext = new InitialContext();
javax.sql.DataSource ds = (javax.sql.DataSource)
initialContext.lookup("java:comp/env/jdbc/MySQLConnectionDS");
java.sql.Connection conn = ds.getConnection();
[/code]

JavaEE 5 defines annotations to support resource injection. Resource injection is the injection of external resources, such as a data source in a JEE 5 application using the javax.annotation.Resource annotation. JDeveloper 11 will support resource injection with annotations to obtain a handle of a data source. For example, define a catalogDS resource of the javax.sql.DataSource type, as shown below:

[code lang=”java”]
private @Resource DataSource catalogDS;
[/code]

The catalogDS field of type javax.sql.DataSource is annotated with the @Resource annotation. JNDI lookup is not required with resource injection, and the DataSource resource is also not defined in the web.xml deployment descriptor.

JDBC Configuration Errors

You might get errors while configuring a JDBC connection. If you are using MySQL, and the connection URL is incorrect, or the MySQL database is not running, the following error message is generated:

Communications link failure

If you are using Oracle database, some possible connection configuration errors are listed below:

  • IO exception: The Network Adapter could not establish the connectionM
  • IO exception: Connection refused

The Network Adapter could not establish the connection exception is caused by one or more of the following configuration errors:

  • The database host name, port number, or database instance name is wrong.
  • The database TNSListener has not been started. The TNSListener may be started with the lsnrctl utility.

[code]
C:>lsnrctl start
The Connection refused exception is caused by one or more of the following configuration errors:
1. The database SID specified is incorrect.
2. The database instance has not been started. To start the database instance connect to SQL*Plus as SYSDBA.
C:>sqlplus SYS/<pwd> AS SYSDBA
At the SQL prompt, start the database instance with the startup command.
SQL>startup
[/code]

Summary

JDeveloper IDE provides a built-in Connections navigator to configure a connection with any relational database for which a JDBC driver is available. A connection configured in the Connections navigator is also available as a data source. In this article, we have configured a JDBC connection in JDeveloper with MySQL database using the MySQL Connector/J 5.1 JDBC 4.0 driver.

Filed Under: Java Tagged With: JDBC, JDeveloper, MySQL

Configure MySql Database With Hibernate Mappings

July 29, 2008 by Krishna Srinivasan Leave a Comment

Configure MySql Database

Configuring MySql database with hibernate is the same as with other databasses. The only difference will be connection url and the database dialect to be specified in the configuration file. This tips provides a basic example configuration file for configuaring the MySql with hibernate. But it doesn’t explain you installing the MySql database. If you are looing for installing MySql database please read it here : http://dev.mysql.com/downloads/

also read:

  • Introduction to Hibernate
  • Hibernate Interview Questions
  • Interceptors in Hibernate
  • Hibernate Books

Sample URL is jdbc:mysql://localhost:3306/SampleDB. In this URL port 3306 is default for the mysql database. If you are not specifying that in the URL, it will assume the port is 3306.localhost can be replaced with your system IP address and machine name.SampleDB is the database or catelog name you have created. Every session factory can have only one database. if you want to use multiple database, create multiple session factory with different database names.

org.hibernate.dialect.MySQLDialect (Read: List of Hibernate Dialects) is the dialect name for MySQL database. Each database has its own dialect declared in the hibernate package.

[code lang=”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>
<!– Database connection settings –>
<property name=’connection.driver_class’>com.mysql.jdbc.Driver</property>
<property name=’connection.url’>jdbc:mysql://localhost:3306/SampleDB</property>
<property name=’connection.username’>root</property>
<property name=’connection.password’>root</property>

<!– JDBC connection pool (use the built-in) –>
<property name=’connection.pool_size’>1</property>

<!– SQL dialect –>
<property name=’dialect’>org.hibernate.dialect.MySQLDialect</property>

<!– Echo all executed SQL to stdout –>
<property name=’show_sql’>true</property>

<!– Mapping files –>
<mapping resource=’Author.hbm.xml’/>
</session-factory>
</hibernate-configuration>
[/code]

Filed Under: Hibernate Tagged With: hibernate mappings, MySQL

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved