0% found this document useful (0 votes)
102 views21 pages

Spring Jpa

The document contains code for a Spring Boot application that manages weather report data using JPA and Hibernate. It includes entities for WeatherReport and related controller, repository interfaces. The WeatherReport entity contains fields for id, city, min and max temperatures. The WeatherController allows getting, adding, updating and deleting WeatherReport entities. WeatherRepository extends JpaRepository to provide CRUD methods for WeatherReport entity. The ApplicationProperties file configures JPA and data source settings.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
102 views21 pages

Spring Jpa

The document contains code for a Spring Boot application that manages weather report data using JPA and Hibernate. It includes entities for WeatherReport and related controller, repository interfaces. The WeatherReport entity contains fields for id, city, min and max temperatures. The WeatherController allows getting, adding, updating and deleting WeatherReport entities. WeatherRepository extends JpaRepository to provide CRUD methods for WeatherReport entity. The ApplicationProperties file configures JPA and data source settings.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Question 1

WeatherReport.java

package com.weather.jpa.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name = "weather_report")
public class WeatherReport {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "w_seq")
@SequenceGenerator(sequenceName = "w_seq", initialValue = 1, allocationSize = 1,
name = "w_seq")
private Long id;
@Column(name = "city")
private String city;
@Column(name = "min_temperature")
private Double minTemperature;
@Column(name = "max_temperature")
private Double maxTemperature;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Double getMinTemperature() {
return minTemperature;
}
public void setMinTemperature(Double minTemperature) {
this.minTemperature = minTemperature;
}
public Double getMaxTemperature() {
return maxTemperature;
}
public void setMaxTemperature(Double maxTemperature) {
this.maxTemperature = maxTemperature;
}
}

WeatherReportController

package com.weather.jpa.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.weather.jpa.domain.WeatherReport;
import com.weather.jpa.repository.WeatherRepository;
@RestController
public class WeatherController {
@Autowired
WeatherRepository wr;
@GetMapping("/weatherReport")
public List<WeatherReport> getData() {
return (List<WeatherReport>) wr.findAll();
}
@PostMapping("/weatherReport")
public WeatherReport addWeatherReport(@RequestBody WeatherReport cases) {
return wr.save(cases);
}
@PutMapping("/weatherReport")
public WeatherReport updateWeatherReport(@RequestBody WeatherReport cases) {
return wr.save(cases);
}
@GetMapping("/weatherReport/{id}")
public WeatherReport view(@PathVariable Long id) {
Optional<WeatherReport> owr=wr.findById(id);
WeatherReport wr=null;
if(owr.isPresent()) {
wr=owr.get();
}
return wr;
}
@DeleteMapping("/weatherReport/{id}")
public Boolean deleteUsers(@PathVariable Long id) {
try {
wr.deleteById(id);
return true;
}
catch (Exception e) {
return false;
}
}
}

WeatherRepository

package com.weather.jpa.repository;
import org.springframework.stereotype.Repository;
import com.weather.jpa.domain.WeatherReport;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
@Repository("weatherRepository")
public interface WeatherRepository extends JpaRepository<WeatherReport, Long>{
}

WeatherJpaApplication.class

package com.weather.jpa;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class WeatherJpaApplication {

public static void main(String[] args) {

SpringApplication.run(WeatherJpaApplication.class, args);

ApplicationProperties

spring.main.banner-mode=off
# create n drop tables, loads import.sql
spring.jpa.hibernate.ddl-auto=create-drop
server.port=8083
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe
spring.datasource.username=HR
spring.datasource.password=HR
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.form-at_sql=true

=====================================================================================
=====================================================================================

=====================================================================================
=====================================================================================

Q3 Jpa

Team.java
package com.springboot.jpa.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;

import java.util.*;

@Entity
@Table(name = "team")
public class Team {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "TEAM_SEQ")
@SequenceGenerator(sequenceName = "team_seq", initialValue = 1, allocationSize =
1, name = "TEAM_SEQ")

//@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;

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

@OneToMany(mappedBy="team")
private List<Player> playerList;

public Long getId() {


return id;
}

public void setId(Long id) {


this.id = id;
}

public String getTeamName() {


return teamName;
}

public void setTeamName(String teamName) {


this.teamName = teamName;
}

public List<Player> getPlayerList() {


return playerList;
}

public void setPlayerList(List<Player> playerList) {


this.playerList = playerList;
}

}
Player.java
package com.springboot.jpa.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;

@Entity
@Table(name = "player")
public class Player {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "PLAYER_SEQ")
@SequenceGenerator(sequenceName = "player_seq", initialValue = 1, allocationSize
= 1, name = "PLAYER_SEQ")

//@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;

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

@Column(name = "age")
Integer age;

@ManyToOne
@JoinColumn(name="team_id")
Team team;

public Long getId() {


return id;
}

public void setId(Long id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public Integer getAge() {


return age;
}
public void setAge(Integer age) {
this.age = age;
}

TeamRepository

package com.springboot.jpa.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.springboot.jpa.domain.*;
@Repository("teamRepository")
public interface TeamRepository extends CrudRepository<Team,Long>{
}

TeamController

package com.springboot.jpa.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.springboot.jpa.repository.*;
import com.springboot.jpa.domain.*;
@RestController
@RequestMapping("team")
public class TeamController {
@Autowired
TeamRepository tRepository;
// @PostMapping("saveteam")
// public Team addPlayer(@RequestBody Team team)
// {
// return tRepository.save(team);
// }
@GetMapping("list")
public List<Team> fetchAll()
{
return(List<Team>)tRepository.findAll();
}
@GetMapping("/{id}")
public Optional<Team> obtainTeamById(@PathVariable Long id) {
return tRepository.findById(id);
}
}

RelationshipJpaApplication

package com.springboot.jpa;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class RelationshipJpaApplication {

public static void main(String[] args) {


SpringApplication.run(RelationshipJpaApplication.class, args);
}

Application.property

spring.main.banner-mode=off

# create n drop tables, loads import.sql


spring.jpa.hibernate.ddl-auto=create-drop

server.port=8085
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe
spring.datasource.username=HR
spring.datasource.password=HR
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.form-at_sql=true

4th Jpa
App.Class

package com.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

public static void main(String[] args) {


SpringApplication.run(App.class, args);
}

UserController

package com.springboot.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties.Pageable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.springboot.domain.User;
import com.springboot.repository.UserRepository;
@RestController
//@RequestMapping("/user")
public class UserController {
@Autowired
UserRepository ur;
@GetMapping("/user")
public List<User> list(
@RequestParam(defaultValue = "0") Integer pageNo,
@RequestParam(defaultValue = "10") Integer pageSize,
@RequestParam(defaultValue = "id") String sortBy)
{
PageRequest page= PageRequest.of(pageNo, pageSize, Sort.by(sortBy));
Page<User> pr=ur.findAll(page);
if(pr.hasContent()) {
return pr.getContent();
}
else {
return new ArrayList<>();
}
}
}

User.java

package com.springboot.domain;

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

@Entity
@Table(name = "\"user\"")
public class User {
@Id
//@GeneratedValue(strategy = GenerationType.IDENTITY)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "Mach_SEQ")
@SequenceGenerator(sequenceName = "machine_seq", initialValue = 1,
allocationSize = 1, name = "Mach_SEQ")
private Integer id;
@Column(name = "name")
private String name;
@Column(name = "username")
private String username;
@Column(name = "email")
private String email;
@Column(name = "mobile_number")
private String mobileNumber;

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 getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public User(Integer id, String name, String username, String email,
String mobileNumber) {
this.id = id;
this.name = name;
this.username = username;
this.email = email;
this.mobileNumber = mobileNumber;
}

public User() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", username=" + username +
", email=" + email + ", mobileNumber="
+ mobileNumber + "]";
}

UserRespiratory

package com.springboot.repository;

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

import com.springboot.domain.User;

@Repository("userRepository")
public interface UserRepository extends PagingAndSortingRepository <User, Long>
{

Application.properties

spring.main.banner-mode=off
# create n drop tables, loads import.sql
spring.jpa.hibernate.ddl-auto=create-drop
server.port=8083
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe
spring.datasource.username=HR
spring.datasource.password=HR
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.form-at_sql=true

question 5

URL:  Base URL+”/hall/searchByLocationAndCost?cost=45000&location=Paris”

[
    {
        "id": 3,
        "name": "The Walt Disney Hall",
        "contactNumber": 8976543210,
        "costPerDay": 60000.0,
        "ownerName": "Peter Parker",
        "location": "Paris"
    },
    {
        "id": 4,
        "name": "The Oslo Opera House",
        "contactNumber": 7890654321,
        "costPerDay": 45000.0,
        "ownerName": "Shakespeare",
        "location": "Paris"
    },
    {
        "id": 9,
        "name": "Sydney Opera House",
        "contactNumber": 7890786512,
        "costPerDay": 45000.0,
        "ownerName": "Thomas Peterson",
        "location": "Paris"
    }
]
URL:  Base URL+”/hall/searchByCost?cost=50000”
URL:  Base URL+”/hall/searchByLocation?location=London”

URL:  Base URL+”/hall/searchByName?name=Esplanade”
package com.springboot;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class UserApplication {

public static void main(String[] args) {

SpringApplication.run(UserApplication.class, args);

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

package com.springboot.controller;

import java.util.List;
import javax.websocket.server.PathParam;

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

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import com.springboot.domain.Hall;

import com.springboot.repository.HallRepository;

@RestController

@RequestMapping("/hall")

public class HallController {

@Autowired

HallRepository repository;

// @GetMapping("hall")

// public List<Hall> fetchAll()

// {

// return(List<Hall>)repository.findAll();

//

// }

@GetMapping("/searchByName")

public Hall findByName(@PathParam("name") String name) {

return repository.findByName(name);

}
@GetMapping("/searchByLocation")

public List<Hall> findAllByLocation(@PathParam("location") String location) {

return (List<Hall> )repository.findAllByLocation(location);

@GetMapping("/searchByCost")

public List<Hall> findAllByPrice(@PathParam("cost") double cost) {

return (List<Hall>)repository.findAllByCostPerDayGreaterThanEqual(cost);

@GetMapping("/searchByLocationAndCost")

public List<Hall> findAllByLocationAndCost(@PathParam("location") String location,


@PathParam("cost") double cost) {

return
(List<Hall>)repository.findAllByLocationAndCostPerDayGreaterThanEqual(location, cost);

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

package com.springboot.domain;

import javax.persistence.Cacheable;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.Table;
import org.hibernate.annotations.Cache;

import org.hibernate.annotations.CacheConcurrencyStrategy;

@Entity

@Table(name = "hall")

@Cacheable

@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)

public class Hall {

@Id

private int id;

@Column(name = "name")

private String name;

@Column(name = "contact_number")

private long contactNumber;

@Column(name = "cost_per_day")

private double costPerDay;

@Column(name = "owner_name")

private String ownerName;

@Column(name = "location")

private String location;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public long getContactNumber() {


return contactNumber;

public void setContactNumber(long contactNumber) {

this.contactNumber = contactNumber;

public double getCostPerDay() {

return costPerDay;

public void setCostPerDay(double costPerDay) {

this.costPerDay = costPerDay;

public String getOwnerName() {

return ownerName;

public void setOwnerName(String ownerName) {

this.ownerName = ownerName;

public int getId() {

return id;

public void setId(int id) {

this.id = id;

public String getLocation() {

return location;

public void setLocation(String location) {

this.location = location;

}
public Hall(int id, String name, long contactNumber, double costPerDay,

String ownerName, String location) {

this.id = id;

this.name = name;

this.contactNumber = contactNumber;

this.costPerDay = costPerDay;

this.ownerName = ownerName;

this.location = location;

public Hall() {

@Override

public String toString() {

return "Hall [id=" + id + ", name=" + name + ", contactNumber=" + contactNumber + ",
costPerDay=" + costPerDay

+ ", ownerName=" + ownerName + ", location=" + location + "]";

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

package com.springboot.repository;

import java.util.List;

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

import org.springframework.data.repository.PagingAndSortingRepository;

import org.springframework.stereotype.Repository;

import com.springboot.domain.Hall;
@Repository

public interface HallRepository extends JpaRepository<Hall,Integer>{

Hall findByName(String name);

List<Hall> findAllByLocation(String location);

List<Hall> findAllByCostPerDayGreaterThanEqual(double costPerDay);

List<Hall> findAllByLocationAndCostPerDayGreaterThanEqual(String location,double


costPerDay);

You might also like