MongoDB With Log4j using maven

Standard

With MongoDB and spring data mongodb log4j appender has facility to log your applications log into  mongodb  instead of your file system.

I am going to create the project using netbeans as maven project following are my pom file

<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>ed.ws</groupId>
<artifactId>MongoLog</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>MongoLog</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-log4j</artifactId>
<version>1.0.0.M4</version>

</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.5.3</version>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-snapshot</id>
<name>Spring Maven SNAPSHOT Repository</name>
<url>http://s3.amazonaws.com/maven.springframework.org/snapshot</url>
</repository>

<repository>
<id>spring-milestone</id>
<name>Spring Maven MILESTONE Repository</name>
<url>http://maven.springframework.org/milestone</url>
</repository>
</repositories>
</project>

And the main part of Log4j log4j property files as follows


log4j.rootCategory=INFO, stdout
log4j.appender.stdout=org.springframework.data.document.mongodb.log4j.MongoLog4jAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n
log4j.appender.stdout.host = localhost
log4j.appender.stdout.port = 27017
log4j.appender.stdout.database = logs
log4j.appender.stdout.collectionPattern = %X{year}%X{month}
log4j.appender.stdout.applicationId = my.mongolog
log4j.appender.stdout.warnOrHigherWriteConcern = FSYNC_SAFE
log4j.category.org.springframework.batch=DEBUG
log4j.category.org.springframework.data.document.mongodb=DEBUG
log4j.category.org.springframework.transaction=INFO
# for debugging datasource initialization
log4j.category.ed.ws=all

as  per above configuration it will store the logs in the database called “logs” and  for different date you able to get diffrent collections .

Now below test code to  storing the logs back to mongodb.


package ed.ws.mongolog;

import org.apache.log4j.Logger;

/**
* Hello world!
*
*/
public class App
{
private static final Logger logger = Logger.getLogger(App.class);
public static void main( String[] args )
{
logger.info("Testing mongodb ");
logger.error("its error reported");
logger.debug("its debuging message");

}
}

for checking the log i use the following query in mongodb consol .


db.getCollection("201112").find()

it will return the following results .

SpringData MongoDB GeoSpatial Query

Standard

Please refer my previous posting if you not yet read yet .

Mongo Beginning

Mongo Crud

Mongo DB supports GeoQuery  query as that is not supported by rdbms by default .

So we can query that near by location based on longitude and latitude  and it will be sorted by distance and it will give distance from base location  too .

This is basic command we going to implement using sping mongodb , spring mv and  google map.


db.runCommand({geoNear : "map", near : [ 1.4377786502730732,103.78692984580994
num : 10,maxDistance:1, query{_class:edu.samples.mvc.basic.LocationMap}});

In the above code “map” is collection name . The above document storing location as double array ( double [] {double value, double value})

In  this tutorial  mongodb  store business details with latitude and longitude . For forcing indexing  pojo need  annotate location field  with @GeoSpatialIndexed

Same LocationMap pojo is using for saving into mongodb and spring mvc command object .

So for above purpose  @Transient two fields(latitude, longitude)  to make  sure not to store those fields in mongodb , its using only for mapping in the spring mvc .

following are my pojo


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.samples.mvc.basic;

import java.util.Arrays;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.index.GeoSpatialIndexed;
import org.springframework.data.mongodb.core.mapping.Document;

/**
*
* @author home
*/
@Document(collection = "map")
public class LocationMap {
@Id
private String id;
private String name;
private String businessName;
private String type;
@GeoSpatialIndexed
private double[] location;
@Transient
private double latitute;
@Transient
private double logitute;

public double getLatitute() {
if (location!=null  )
{
this.latitute = location[0];

}
return latitute;
}

public void setLatitute(double latitute) {

this.latitute = latitute;

}

public double getLogitute() {
if (location!=null  )
{
this.logitute = location[1];

}
return logitute;
}

public void setLogitute(double logitute) {

this.logitute = logitute;
}

public void setLocation(double[] location) {
this.location = location;
}
public void setName(String name) {
this.name = name;
}

public String getId() {
return id;
}

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

public String getBusinessName() {
return businessName;
}

public void setBusinessName(String businessName) {
this.businessName = businessName;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public String getName() {
return name;
}

public double[] getLocation() {
return location;
}

@Override
public String toString() {
return "Venue [id=" + id + ", name=" + name + ", location="
+ Arrays.toString(location) + "]";
}
}

following are code to save the data


public void insertLocation(LocationMap locationMap) {

mongoTemplate.save(locationMap);

}

Next move to Spring MVC Controller layer.
Create  MapInsertData Controller for saving the LocationMap data saving back to mongodb using “insertLocation” method in Repository .

As its using mongotemplate.save(object) , it will insert the data into mongodb as long id field is null . If id field is matched with mongodb document then it will update instead of insert.
following are the code in my controler

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.samples.mvc.basic;

import edu.samples.repository.ContactRepository;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
*
* @author home
*/
@Controller
@RequestMapping(value = "/mapinsert")
public class MapInsertData {
private static final Logger logger = Logger.getLogger(MapInsertData.class);
@Autowired
ContactRepository repository;

@RequestMapping(method = RequestMethod.GET)
public String getCreateForm(Model model) {

model.addAttribute("locationbean", new LocationMap());
return "basic/mapinsert";
}

@RequestMapping(method = RequestMethod.POST)
public String createContact(@ModelAttribute("locationbean")LocationMap locationmap, BindingResult result) {
if (result.hasErrors()) {
for (ObjectError error : result.getAllErrors()) {
System.err.println("Error in uploading: " + error.getCode() + " - " + error.getDefaultMessage());
}
}

double[]  tempLocation = {locationmap.getLatitute(), locationmap.getLogitute()};
locationmap.setLocation(tempLocation );
repository.insertLocation(locationmap);
return "basic/mapinsert";
}
}

Iam not updating jsp page here . Once deployed the project , its looks like as follows . When click on save button
It will store data back to MongoDB.

Next going to do two things

  • display the data with Google Maps .
  • Search near by location with distance .

Display the data with Google Maps

For displaying data creating new controller “MapView” with two rest method , one with name as parameter another one is name and business name as parameter . with above rest method after mapview next parameter will name and  after name business name as the parameter


@Controller
@RequestMapping(value = "/mapview")
public class MapView {
private static final Logger logger = Logger.getLogger(MapView.class);
@Autowired
ContactRepository repository;

@RequestMapping(value="/{name}/{business}",method = RequestMethod.GET)
public String getCreateForm(Model model,  @PathVariable  String name, @PathVariable  String business ) {

model.addAttribute("locationbean",repository.getBusinessByNameAndBusiness(name, business));
return "basic/mapview";
}
@RequestMapping(value="/{name}",method = RequestMethod.GET)
public String getCreateForm(Model model,  @PathVariable  String name) {

model.addAttribute("locationbean", repository.getBusinessByName(name));
return "basic/mapview";
}

following are the my jsp page to display the business details with goggle maps.

<%--
Document   : basicForm
Created on : Oct 11, 2011, 9:03:28 PM
Author     : home
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<title>spring-mvc-showcase</title>
<link href="<c:url value="/resources/css/custom-theme/jquery-ui-1.8.16.custom.css" />" rel="stylesheet" type="text/css" />

<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=true">
</script>
<script type="text/javascript" src="<c:url value="/resources/js/jquery-1.6.2.min.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/js/jquery-ui-1.8.16.custom.min.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/js/jquery.ui.button.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/js/jquery.ui.core.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/js/jquery.ui.widget.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/datatable/js/jquery.dataTables.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/datatable/js/jquery.json-2.3.js" />"></script>
<script>
$(document).ready(function() {



$("button").button();
var name= $("input[name='name']").val();
var lon =$("input[name='logitute']").val();
var lat =$("input[name='latitute']").val();

initialize(lat, lon);
});
function initialize(lat, lon,name)
{

// var latlng = new google.maps.LatLng(1.385001, 103.756047);
var latlng = new google.maps.LatLng(lat, lon);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var marker = new google.maps.Marker({
position: latlng,
title:name
});
marker.setMap(map);
var circle = new google.maps.Circle({
map: map,
radius: 1000    // metres
//fillColor: '#AA0000'
});
circle.bindTo('center', marker, 'position');
google.maps.event.addListenerOnce(map, 'idle', function(){

});
}
function test()
{
var lon =$("input[name='logitute']").val();
var lat =$("input[name='latitute']").val();
var url = "../mapnearby/" + lon + "/" + lat + "/1.9";

var results="";
$.getJSON(url, function(data) {


results = "<b>Found near by result </b> </br>"
for(var i=0, l=data.results.length; i < l ;   i++)
{
// Process each image
// alert(results +data.results[i].name);
results = results +data.results[i].obj.name;
results = results +  "<a href=\"/mongospring-1.0-SNAPSHOT/mapview/"+  data.results[i].obj.name + "\"> " +  data.results[i].obj.name + " Distance " +  data.results[i].dis +"</a></br>" ;
}
$.each(data, function(i,item){
// results = results +"<a href=\"/mongospring-1.0-SNAPSHOT/mapview/"+  item.obj.name + "\"> " + "item.obj.businessName" + "test " +item.obj.name + "</a></br>" ;
});
});

$('#result').html(results);
}
</script>
<style type="text/css">
*{
margin:0;
padding:0;
font:bold 12px "Lucida Grande", Arial, sans-serif;
}
body {
padding: 10px;
}
#status{
width:250px;
padding:10px;
outline:none;
height:36px;
}

</style>
</head>
<body >
<form:form modelAttribute="locationbean" method="post" >
<h2>Its for Map Data details back to MongoDB</h2>
<table>
<tr>
<td> <div> Location name </div></td>
<td>
<form:input path="name"/>
</br></td>
</tr>
<tr>
<td>  <div> Business Name </div></td>
<td>
<form:input path="businessName"/>
</br></td>
</tr>
<tr>
<td>

<div> Type </div></td>
<td>
<form:input path="type"/>

</td>
</tr>
<tr>
<td><div>Longitute </div></td>
<td>  <form:input path="logitute"/>
</td>
</tr>
<tr>
<td><div> Latitute </div></td>
<td>  <form:input path="latitute"/>
</td>
</tr>

</table>









</form:form>


</button>
<div id="map_canvas" style="width:300px; height:300px"></div>
<br/>
<div id="dynamic">
<input type="button" onclick="test()" value="Search Near By Locations"/>
<div id="result"></div>

</body>
</html>


Nothing fancy just pass latitude and longitutue to google map to display the map in the web page .

Search Near By Location
When click on Search near by location it will call restless web serice and it will return json data with distance from the current locations.

using jquery json call , its call MapNearBy web service and update result below search button .
For returning json  data its using  MapNearBy controller , its passing  two parameter  latitude and longitude .

Following are code for MapNearBy Controller

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.samples.mvc.basic;

import edu.samples.repository.ContactRepository;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.geo.GeoResults;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
*
* @author home
*/
@Controller
@RequestMapping(value = "/mapnearby")
public class MapNearBy {
private static final Logger logger = Logger.getLogger(MapNearBy.class);
@Autowired
ContactRepository repository;

@RequestMapping(value="/{lat}/{longit}/{nearby}",method = RequestMethod.GET)
public @ResponseBody String getCreateForm(Model model,  @PathVariable  double lat, @PathVariable  double longit , @PathVariable double nearby ) {

//System.out.println("id nme " +   lat+ longit + nearby);

// GeoResults<LocationMap> locMap = repository.getnearestLocation(longit, lat, nearby);
//model.addAttribute("locationbean",repository.getBusinessByNameAndBusiness(name, business));
return repository.getnearestLocation(lat,longit, nearby);
}

}

getnearestLocation is actual implementation for returning data as json based on longitude and latitude .

Following are the code for above method.

public String getnearestLocation(double log, double lat, double nearby) {

//Circle circle = new Circle(log, lat, nearby);

DBObject cmd = null;
BasicDBObject query = new BasicDBObject();
query.put("_class", "edu.samples.mvc.basic.LocationMap");
BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start().add("geoNear", "map").add("near", new
double[] {lat,log}).add("num", 10).add("maxDistance", 10).add("distanceMultiplier", (6371 * Math.PI / 180.0d)).add("query", query);
cmd = documentBuilder.get();
CommandResult cr =mongoTemplate.executeCommand(cmd);
return  cr.toString();
}

It will return maximum 10 results withing 10 KM and distance in KM .

Once run everything it will show like this way .

Following are the source code for the above project.

http://www.mediafire.com/?cbe7cyxkkgdd90x

Spring MVC With Mongo DB CRUD Operations

Standard

This is following my previous post about the mongodb.

If you not read yet go through it for a basic understanding about mongodb and insert document using spring mongo data.

Mongo DB Introduction

Following are we going to do in this section.

  1. Read all documents of Contact and view in the web page using jquery datatable .
  2. Update the exisitng record.

For getting all documents follwing code snipitet is using.


public List<Contact> getPersonCollection() {
List<Contact> results = mongoTemplate.findAll(Contact.class);
return results;
}

for finding document based on the id using the following snippet in the service layer.


public Contact getContactById(String id) {
Contact contact = mongoTemplate.findOne(query(where(&quot;id&quot;).is(id)), Contact.class);
return contact;
}

For updating document the following code snippet is using.


public void updateExistingContact(Contact tempcontact)
{

mongoTemplate.save(tempcontact);
}

As long as your id is same it will update in mongo server .

If there is no id it will do insert .

In my opinion this is one of simplest CRUDE operation compared jdbc template or hibernate template.

I am not explain controller and Jsp Page here . you able to find that code attachment in the end of this tutorials .

 

 

All document view is using getPersonCollection()  from my repository .

When clicking update link it will open update link .As its using rest style id parameter like update/parameter.

Download Sample Code

Convert hibernate template into sessionFactory

Standard

Hi,

Please refer my following three post if you not read yet.

Part 1

Part 2

Part 3

Part 4

Before iam was using Hibernate template . For this tutorials iam going to use Hibernate Sesson .

Following are my Repository Code after change the code .


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ed.ws.hiber;

import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
*
* @author home
*/
@Transactional(readOnly = true)
@Repository
public class HibernateDao {
private SessionFactory sessionFactory;

public void setSessionFactory(SessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;

}

public void saveAuthor(Author Author)throws DataAccessException {
sessionFactory.getCurrentSession().saveOrUpdate(Author);

//
}
public List<Author>  getAuthors()throws DataAccessException
{
return   sessionFactory.getCurrentSession().createQuery("From Author a inner join fetch a.booksCollection b").list();
}
public List<Books>  getBooks()throws DataAccessException
{
return   sessionFactory.getCurrentSession().createQuery("From Books b inner join fetch b.parentId a").list();
}
public List<Author> getAuthorsbyname(String name)throws DataAccessException
{
return sessionFactory.getCurrentSession().getNamedQuery("findAuthorByName").setString( "params", "%" + name + "%" ).list();

}
public List<Author> getAuthorsbynameRole(String [] name)throws DataAccessException
{

return sessionFactory.getCurrentSession().getNamedQuery("findAuthorByNameRole").setString("param", name[0]).setString("role", name[1]).list();

}
@Transactional(readOnly = false,propagation = Propagation.REQUIRES_NEW)
public void saveRestaurant(Restaurant rest)
{
sessionFactory.getCurrentSession().saveOrUpdate(rest);
}
@Transactional(readOnly = false,propagation = Propagation.REQUIRES_NEW)
public void saveCuisine(Cuisine cuisine)
{
sessionFactory.getCurrentSession().saveOrUpdate(cuisine);
}
}

Finally i upload the source code for this project too..

http://www.mediafire.com/?97gaen8tam362z9

Hibernate Spring @manytomany with JPA

Standard

This is my fourth tutorials about hibernate and spring .

If you not able to see refer back following link .

Basic idea behind is Restaurant have multiple Cuisine and one Cusine will be served in multiple restaurants.

Part 1

Part 2

Part 3

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

The following are the sql script without relationships , netbeans javadb not giving sql for relationship that you need to add manually the relationship as above .


create table "APP".CUISINE
(
ID NUMERIC(5) not null primary key,
NAME VARCHAR(200),
SUBTYPE VARCHAR(200)
)

create table "APP".RESTAURANT
(
ID NUMERIC(5) not null primary key,
NAME VARCHAR(200),
LOCATION VARCHAR(200),
WEBSITE VARCHAR(200),
PHONE VARCHAR(200)
)

create table "APP".RESTAURANT_CUISINE
(
CUISINE_ID NUMERIC(5) not null primary key,
RESTAURANT_ID NUMERIC(5) not null primary key
)

Now iam going to generate Pojo using Create entity with database .

After generate need small modifications ..

following are the pojo .

Cusine.java sourccode


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ed.ws.hiber;

import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;

/**
*
* @author home
*/
@Entity
@Table(name = "CUISINE" ,catalog = "", schema = "APP")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Cuisine.findAll", query = "SELECT c FROM Cuisine c"),
@NamedQuery(name = "Cuisine.findById", query = "SELECT c FROM Cuisine c WHERE c.id = :id"),
@NamedQuery(name = "Cuisine.findByName", query = "SELECT c FROM Cuisine c WHERE c.name = :name"),
@NamedQuery(name = "Cuisine.findBySubtype", query = "SELECT c FROM Cuisine c WHERE c.subtype = :subtype")})
public class Cuisine implements Serializable {
private static final long serialVersionUID = 1L;
@Id

@Column(name = "ID",nullable = false)
private Integer id;
@Column(name = "NAME")
private String name;
@Column(name = "SUBTYPE")
private String subtype;
@JoinTable(name = "RESTAURANT_CUISINE", catalog = "", schema = "APP",joinColumns = {
@JoinColumn(name = "CUISINE_ID", referencedColumnName = "ID")}, inverseJoinColumns = {
@JoinColumn(name = "RESTAURANT_ID", referencedColumnName = "ID")})
@ManyToMany(cascade=CascadeType.ALL)
private List<Restaurant> restaurantList;

public Cuisine() {
}

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

public Integer getId() {
return id;
}

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

public String getName() {
return name;
}

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

public String getSubtype() {
return subtype;
}

public void setSubtype(String subtype) {
this.subtype = subtype;
}

public List<Restaurant> getRestaurantList() {
return restaurantList;
}

public void setRestaurantList(List<Restaurant> restaurantList) {
this.restaurantList = restaurantList;
}

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

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

@Override
public String toString() {
return "ed.ws.hiber.Cuisine[ id=" + id + " ]";
}

}

Restaurant.java as follows


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ed.ws.hiber;

import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;

/**
*
* @author home
*/
@Entity
@Table(name = "RESTAURANT",catalog = "", schema = "APP")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Restaurant.findAll", query = "SELECT r FROM Restaurant r"),
@NamedQuery(name = "Restaurant.findById", query = "SELECT r FROM Restaurant r WHERE r.id = :id"),
@NamedQuery(name = "Restaurant.findByName", query = "SELECT r FROM Restaurant r WHERE r.name = :name"),
@NamedQuery(name = "Restaurant.findByLocation", query = "SELECT r FROM Restaurant r WHERE r.location = :location"),
@NamedQuery(name = "Restaurant.findByWebsite", query = "SELECT r FROM Restaurant r WHERE r.website = :website"),
@NamedQuery(name = "Restaurant.findByPhone", query = "SELECT r FROM Restaurant r WHERE r.phone = :phone")})
public class Restaurant implements Serializable {
private static final long serialVersionUID = 1L;
@Id

@Column(name = "ID",nullable = false)
private Integer id;
@Column(name = "NAME")
private String name;
@Column(name = "LOCATION")
private String location;
@Column(name = "WEBSITE")
private String website;
@Column(name = "PHONE")
private String phone;
@ManyToMany(mappedBy = "restaurantList",cascade=CascadeType.ALL)
private List<Cuisine> cuisineList;

public Restaurant() {
}

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

public Integer getId() {
return id;
}

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

public String getName() {
return name;
}

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

public String getLocation() {
return location;
}

public void setLocation(String location) {
this.location = location;
}

public String getWebsite() {
return website;
}

public void setWebsite(String website) {
this.website = website;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

public List<Cuisine> getCuisineList() {
return cuisineList;
}

public void setCuisineList(List<Cuisine> cuisineList) {
this.cuisineList = cuisineList;
}

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

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

@Override
public String toString() {
return "ed.ws.hiber.Restaurant[ id=" + id + " ]";
}

}

My Respository iam modifying with the following code to save my Cuisine and Restaurant .


public void saveRestaurant(Restaurant rest)
{
hibernateTemplate.saveOrUpdate(rest);
}
public void saveCuisine(Cuisine cuisine)
{
hibernateTemplate.saveOrUpdate(cuisine);
}

Finally doing testing and insert one Cuisine With mutliple restaurant.


package ed.ws.hiber;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
* Hello world!
*
*/
public class App1onetoMany
{
public static void main( String[] args )
{
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/applicationContext.xml");
HibernateDao dao = (HibernateDao)context.getBean("userDao");
Cuisine cuisine = new Cuisine();
cuisine.setId(12);
cuisine.setName("Brazilian");
cuisine.setSubtype("Southeast");
Restaurant rest = new Restaurant();
rest.setLocation("CBD");
rest.setName("Deo Gen");
rest.setId(60);
rest.setPhone("12345");
rest.setWebsite("www.deo.gen.com");
Restaurant rest1 = new Restaurant();
rest1.setLocation("CBD1");
rest1.setId(44);
rest1.setPhone("123451");
rest1.setWebsite("www.deo.gen.bz");
List<Restaurant> restList = new ArrayList<Restaurant>();
restList.add(rest);
restList.add(rest1);
cuisine.setRestaurantList(restList);

dao.saveCuisine(cuisine);

}
}

When you run the above code , it will insert into three tables the values .

Hope it wll help you. Please give me your feedback too .