addheader

Saturday, 2 February 2013

spring data jpa manytomany example:


spring data jpa manytomany example:
-----------------------------------

     JAVA-SERVLETS     JAVA-JDBC     JAVA-JSP       HIBERNATE-SHCEMABASED 

    HIBERNATE-ANNOTATIONS     SPRING-IOC       SPRING –AOP-SCHEMABASED   

    SPRING-AOP-ANNOTATIONS      SPRING -DAO     SPRIN-MVC     SPRING-SECUTITY

     SPRING-DATA-JPA     REST-WEB-SERVICE     STRUTS2HIBERNATE    GWT.... 





NOTE:   1)  maven dependeccy pom.xml  , we can get from previous example.
               2) presestance.xml , beans.xml file also we can get from my previous example program.

Course .java
----------------




package repository;

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

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

@Entity
@Table(name="course")
public class Course {
@Id
@GeneratedValue
private int c_id;
private String c_name;

@ManyToMany( cascade = CascadeType.ALL)
@JoinTable(
name = "selectedstudent", joinColumns ={
@JoinColumn(name = "c_id", nullable = false, updatable = false)},
inverseJoinColumns =  { @JoinColumn(name = "s_id")
}
)

private Set<Student> students=new HashSet<Student>(0);
public int getC_id() {
return c_id;
}
public void setC_id(int c_id) {
this.c_id = c_id;
}
public String getC_name() {
return c_name;
}
public void setC_name(String c_name) {
this.c_name = c_name;
}
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}

}


CourceRepository .java
---------------




package repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public interface CourceRepository extends JpaRepository<Course, Long>,
JpaSpecificationExecutor<Course>{

}


Student .java
--------------



package repository;

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

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

@Entity
@Table(name="student")
public class Student {
@Id
@GeneratedValue
private int s_id;
private String s_name;
@ManyToMany( cascade = CascadeType.ALL)
@JoinTable(
name = "selectedstudent", joinColumns ={
@JoinColumn(name = "s_id", nullable = false, updatable = false)},
inverseJoinColumns =  { @JoinColumn(name = "c_id")
}
)

private Set<Course> courses=new HashSet<Course>(0);
public int getS_id() {
return s_id;
}
public void setS_id(int s_id) {
this.s_id = s_id;
}
public String getS_name() {
return s_name;
}
public void setS_name(String s_name) {
this.s_name = s_name;
}
public Set<Course> getCourses() {
return courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
}


StudentRepository .java
--------------------------



package repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface StudentRepository extends JpaRepository<Student, Long>,
JpaSpecificationExecutor<Student>{

}



TestCase .java
---------------




package madhav;
import repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class TestCase {

@Autowired
    private CourceRepository courceRepository;
@Autowired
private StudentRepository studentRepository;
 
    @Transactional
public void createEmployee() {
       
         try
         {
       
        Student s1=new Student();
             s1.setS_name("madhva");
             Student s2=new Student();
             s2.setS_name("venkat");
             Course c1=new Course();
             c1.setC_name("hibernate");
             Course c2=new Course();
             c2.setC_name("spring");
             s1.getCourses().add(c1);
             s1.getCourses().add(c2);
             s2.getCourses().add(c1);
             s1.getCourses().add(c2);
             studentRepository.save(s1);
             studentRepository.save(s2);
               
         }
         catch(Exception ex)
         {
       
         }
   
}

public CourceRepository getCourceRepository() {
return courceRepository;
}

public void setCourceRepository(CourceRepository courceRepository) {
this.courceRepository = courceRepository;
}

public StudentRepository getStudentRepository() {
return studentRepository;
}

public void setStudentRepository(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
}



Test.java
---------------




package madhav;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");

Object tc=(Object)ctx.getBean("testCase");
TestCase g=(TestCase)tc;
g.createEmployee();
}

}


output from console:
----------------------

create table course (
        c_id integer not null auto_increment,
        c_name varchar(255),
        primary key (c_id)
    )


10:28:46.473 [main] ERROR o.h.tool.hbm2ddl.SchemaExport - HHH000389: Unsuccessful: create table course (c_id integer not null auto_increment, c_name varchar(255), primary key (c_id))
10:28:46.473 [main] ERROR o.h.tool.hbm2ddl.SchemaExport - Table 'course' already exists
10:28:46.473 [main] DEBUG org.hibernate.SQL -


    create table selectedstudent (
        c_id integer not null,
        s_id integer not null,
        primary key (s_id, c_id)
    )


10:28:46.661 [main] DEBUG org.hibernate.SQL -

  create table student (
        s_id integer not null auto_increment,
        s_name varchar(255),
        primary key (s_id)
    )


10:28:46.724 [main] ERROR o.h.tool.hbm2ddl.SchemaExport - HHH000389: Unsuccessful: create table student (s_id integer not null auto_increment, s_name varchar(255), primary key (s_id))
10:28:46.724 [main] ERROR o.h.tool.hbm2ddl.SchemaExport - Table 'student' already exists
10:28:46.724 [main] DEBUG org.hibernate.SQL -
 

 alter table selectedstudent
        add index FKB1A7B40F3A8A1D6 (c_id),
        add constraint FKB1A7B40F3A8A1D6
        foreign key (c_id)
        references course (c_id)


10:28:47.537 [main] DEBUG org.hibernate.SQL -
    alter table selectedstudent
        add index FKB1A7B40D2E6D3DE (s_id),
        add constraint FKB1A7B40D2E6D3DE
        foreign key (s_id)
        references student (s_id)






output from sql prompt:
------------------------


TUTIORALS FROM MADHAV:

     JAVA-SERVLETS     JAVA-JDBC     JAVA-JSP       HIBERNATE-SHCEMABASED 

    HIBERNATE-ANNOTATIONS     SPRING-IOC       SPRING –AOP-SCHEMABASED   

    SPRING-AOP-ANNOTATIONS      SPRING -DAO     SPRIN-MVC     SPRING-SECUTITY

     SPRING-DATA-JPA     REST-WEB-SERVICE     STRUTS2HIBERNATE    GWT....  



































    spring data jpa onetomany example

    spring data jpa onetomany example:
    -----------------------------------



         JAVA-SERVLETS     JAVA-JDBC     JAVA-JSP       HIBERNATE-SHCEMABASED 

        HIBERNATE-ANNOTATIONS     SPRING-IOC       SPRING –AOP-SCHEMABASED   

        SPRING-AOP-ANNOTATIONS      SPRING -DAO     SPRIN-MVC     SPRING-SECUTITY

         SPRING-DATA-JPA     REST-WEB-SERVICE     STRUTS2HIBERNATE    GWT.... 





    NOTE:   1)  maven dependeccy pom.xml  , we can get from previous example.
                   2) presestance.xml , beans.xml file also we can get from my previous example program.



    Dept .java
    ----------------



    package repository;

    import java.util.HashSet;


    import java.util.Set;

    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.OneToMany;
    import javax.persistence.Table;

    import org.springframework.data.jpa.domain.AbstractPersistable;

    @Entity
    @Table(name="dept")
    public class Dept {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long deptno;
    private String dname;
    private String loc;
    @OneToMany(mappedBy = "dept")
    private Set<Employee> employees=new HashSet<Employee>(0);
    public Long getDeptno() {
    return deptno;
    }

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

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

    public void setDeptno(Long deptno) {
    this.deptno = deptno;
    }
    public String getDname() {
    return dname;
    }
    public void setDname(String dname) {
    this.dname = dname;
    }
    public String getLoc() {
    return loc;
    }
    public void setLoc(String loc) {
    this.loc = loc;
    }

    }


    Employee .java
    ---------------




    package repository;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
    public interface DeptRepository extends JpaRepository<Dept, Long>,JpaSpecificationExecutor<Dept>{

    }



    Employee .java
    ----------------


    package repository;

    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.ManyToOne;
    import javax.persistence.Table;
    import org.springframework.data.jpa.domain.AbstractPersistable;
    @Entity
    @Table(name="employee2")
    public class Employee extends AbstractPersistable<Long>{

    private String ename;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "deptno")
    private Dept dept;
    public Dept getDept() {
    return dept;
    }
    public void setDept(Dept dept) {
    this.dept = dept;
    }
    public String getEname() {
          return ename;
    }
    public void setEname(String ename) {
          this.ename = ename;
    }
    }




    EmployeeRepository .java
    --------------------------


    package repository;

    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

    public interface EmployeeRepository extends JpaRepository<Employee, Long>,
    JpaSpecificationExecutor<Employee>{

    }


    TestCase .java
    ---------------



    package madhav;
    import repository.*;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    @Service
    public class TestCase {

    @Autowired
        private DeptRepository DeptRepository;
    @Autowired
    private EmployeeRepository EmployeeRepository;
     
        @Transactional
    public void createEmployee() {
           
             try
             {
           
            Dept dept = new Dept();
                 dept.setDname("hugo");
                 dept.setLoc("hyd");

                    DeptRepository.save(dept);
         
           Employee emp1 = new Employee();
           emp1.setEname("madhav");
           emp1.setDept(dept);

           Employee emp2 = new Employee();
           emp2.setEname("narendar");
           emp2.setDept(dept);
           EmployeeRepository.save(emp1);
           EmployeeRepository.save(emp2);

             }
             catch(Exception ex)
             {
           
             }
    }

    public DeptRepository getDeptRepository() {
    return DeptRepository;
    }

    public void setDeptRepository(DeptRepository deptRepository) {
    DeptRepository = deptRepository;
    }

    public EmployeeRepository getEmployeeRepository() {
    return EmployeeRepository;
    }

    public void setEmployeeRepository(EmployeeRepository employeeRepository) {
    EmployeeRepository = employeeRepository;
    }

    }




    Test.java
    ---------------




    package madhav;

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;

    public class Test {

    /**
    * @param args
    */
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");

    Object tc=(Object)ctx.getBean("testCase");
    TestCase g=(TestCase)tc;
    g.createEmployee();
    }

    }





    output from console:
    ----------------------




    output from sql prompt:
    ------------------------


    TUTIORALS FROM MADHAV:

         JAVA-SERVLETS     JAVA-JDBC     JAVA-JSP       HIBERNATE-SHCEMABASED 

        HIBERNATE-ANNOTATIONS     SPRING-IOC       SPRING –AOP-SCHEMABASED   

        SPRING-AOP-ANNOTATIONS      SPRING -DAO     SPRIN-MVC     SPRING-SECUTITY

         SPRING-DATA-JPA     REST-WEB-SERVICE     STRUTS2HIBERNATE    GWT....  




































    Friday, 1 February 2013

    restful webservice formparam example

    restful webservice formparam example:


         JAVA-SERVLETS     JAVA-JDBC     JAVA-JSP       HIBERNATE-SHCEMABASED 

        SPRING-AOP-ANNOTATIONS      SPRING -DAO     SPRIN-MVC     SPRING-SECUTITY

         SPRING-DATA-JPA     REST-WEB-SERVICE     STRUTS2HIBERNATE    GWT.... 


    ---------------------------------------




    PathParamMulValService .java
    --------------------------------


    package madhav;
    import javax.ws.rs.FormParam;
    import javax.ws.rs.POST;
    import javax.ws.rs.Path;
    @Path("/formparam")
    public class FormParamService {
     @POST
     @Path("/add")
     public String handleForm(@FormParam("id") String id,@FormParam("name") String name){

      //business logic

      return "id=" + id + "," + "name= " + name;
     }

    }



    web.xml
    --------



    <?
    xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name></display-name>
    <servlet>
    <display-name>JAX-RS REST Servlet</display-name>
    <servlet-name>JAX-RS REST Servlet</servlet-name>
    <servlet-class>
    com.sun.jersey.spi.container.servlet.ServletContainer
    </servlet-class>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
    <servlet-name>JAX-RS REST Servlet</servlet-name>
    <url-pattern>/services/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    </web-app>


    studentform.html
    -------------------------

    <html>
    <head>
    <title>studentform.html</title>
    </head>
    <body bgcolor="wheat">
    <form action="services/formparam/add" method="post">
    <p>
    id : <input type="text" name="id" />
    </p>
    <p>
    name : <input type="text" name="name" />
    </p>
    <input type="submit" value="Add student" />
    </form>
    </body>




     
    output -client as html::
    ----------------------






    Related topics:

                           Restful webservice json,spring dao

    2.     Restfulwebservice java, jquery, json,ajax example


    3.     Structr2 hibernate 3 integration example program


    4.     springmvc spring provided hibernate example


    5.     struct 2 spring dao


    6.     struts 2hibernate integration example 

       7. Jquery autocomplete from database restful webservice json,ajax


        8.     jax-rs say hai example program

         9.     jax-rs @pathparam example

         10.     jax rs @pathparam multiple value example

         11.     jax rs @Formparam  example


         JAVA-SERVLETS     JAVA-JDBC     JAVA-JSP       HIBERNATE-SHCEMABASED 

        SPRING-AOP-ANNOTATIONS      SPRING -DAO     SPRIN-MVC     SPRING-SECUTITY

         SPRING-DATA-JPA     REST-WEB-SERVICE     STRUTS2HIBERNATE    GWT.... 

    

    restful webservice pathparam multiple values example:

    restful webservice pathparam multiple values example
    :
    ---------------------------------------



    PathParamMulValService .java
    -----------------------


    package madhav;
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.PathParam;
    import javax.ws.rs.Produces;
    @Path("/pathparammul")
    public class PathParamMulValService {
     @GET
      @Path("{id}/{name}")
      @Produces("application/text")
         public String getClichedMessage(@PathParam ("id") String id,@PathParam ("name") String name)
     {

            return "id="+id + "," + "name=" +name;
         }
    }





    web.xml
    --------



    <?
    xml version="1.0"
    encoding="UTF-8"?>
    <web-app version="2.5"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name></display-name>
    <servlet>
    <display-name>JAX-RS REST Servlet</display-name>
    <servlet-name>JAX-RS REST Servlet</servlet-name>
    <servlet-class>
    com.sun.jersey.spi.container.servlet.ServletContainer
    </servlet-class>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
    <servlet-name>JAX-RS REST Servlet</servlet-name>
    <url-pattern>/services/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    </web-app>

    output from restclient:
    ----------------------



    Related topics:

                           Restful webservice json,spring dao

    2.     Restfulwebservice java, jquery, json,ajax example


    3.     Structr2 hibernate 3 integration example program


    4.     springmvc spring provided hibernate example


    5.     struct 2 spring dao


    6.     struts 2hibernate integration example 

       7. Jquery autocomplete from database restful webservice json,ajax


        8.     jax-rs say hai example program

         9.     jax-rs @pathparam example

         10.     jax rs @pathparam multiple value example

         11.     jax rs @Formparam  example