SpringBoot CRUD - java

I stuck with my Springboot Crud project and i need your helps.Problem is i want to use GET with my barcode string variable , and to DELETE and PUT using my id int variable but somehow i could not managed to DELETE and PUT with id variable and i stuck with this all the day. i will post my code and i will apriciate every help
Application.java
package com.javahelps.restservice;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import com.javahelps.restservice.entity.User;
import com.javahelps.restservice.repository.UserRepository;
import com.javahelps.restservice.repository.UserRepository2;
import com.javahelps.restservice.repository.UserRepository3;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
protected CommandLineRunner init(final UserRepository userRepository , UserRepository2 userRepository2,UserRepository3 userRepository3) {
return null;
};
}
UserController.java
package com.javahelps.restservice.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties.Session;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.javahelps.restservice.entity.User;
import com.javahelps.restservice.repository.UserRepository;
import com.javahelps.restservice.repository.UserRepository3;
import javassist.tools.web.BadHttpRequest;
#RestController
#RequestMapping(path = "/productnames")
public class UserController {
#Autowired
private UserRepository repository;
private UserRepository3 repository3;
#GetMapping
public Iterable<User> findAll() {
return repository.findAll();
}
#GetMapping(path = "/{barcode}")
public User find(#PathVariable("barcode") String barcode) {
return repository.findOne(barcode);
}
#PostMapping(consumes = "application/json")
public User create(#RequestBody User user) {
return repository.save(user);
}
#DeleteMapping(path = "/{barcode}")
public void delete(#PathVariable("barcode") String barcode) {
repository.delete(barcode);
}
#DeleteMapping(path = "1/{id}")
public void delete(#PathVariable("id") Integer id) {
repository.delete(id);
}
#PutMapping(path = "/{barcode}")
public User update(#PathVariable("barcode") String barcode, #RequestBody User user) throws BadHttpRequest {
if (repository.exists(barcode)) {
user.setBarcode(barcode);
return repository.save(user);
} else {
throw new BadHttpRequest();
}
}
}
UserRepository.java
package com.javahelps.restservice.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RestResource;
import org.springframework.stereotype.Repository;
import com.javahelps.restservice.entity.User;
#RestResource(exported = false)
#Repository
public interface UserRepository extends JpaRepository<User,String> {
}
User.java
package com.javahelps.restservice.entity;
import java.sql.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="ProductNames")
public class User {
private int id;
#Id
private String barcode;
private String name;
private String category;
private int qty;
private Date dater;
private Date datel;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBarcode() {
return barcode;
}
public void setBarcode(String barcode) {
this.barcode = barcode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public Date getDater() {
return dater;
}
public void setDater(Date dater) {
this.dater = dater;
}
public Date getDatel() {
return datel;
}
public void setDatel(Date datel) {
this.datel = datel;
}
#Override
public String toString() {
return "User{" + "='" +", id='"+ id + '\'' +", name='"+ barcode + '\'' + ", name='" + name + '\'' + ", category='" + category + '\''
+ ", qty='" + qty + '\'' + ", dater='" + dater + '\''+", datel='" + datel + '\'' +'}';
}
}

For delete based on id, since your primary key is not int id you have to write the below custom code in your interface extending JpaRepository.
And in your rest controller you have to invoke it like repository.deleteById(id);
#Repository
public interface UserRepository extends JpaRepository<User,String> {
#Modifying
#Transactional
#Query(value="delete from User u where u.id= ?1")
void deleteById(int id);
}
Similarly you may have to write code for your update statement as well (for PUT case).
Hope this helps.

Related

JPA Repos- Is there a way to return all data without using ID?

I am trying to return a search bar of results based on a food's name on my front end. Therefore on the backend, I need to have a GetMapping that returns all data based on name. Basically, I want to find all food products by name. Is it possible to do this without using the Serial Key ID?
Here is my model:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="food")
public class Food {
#Id
#Column
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(name="category")
private String category;
#Column
private String name;
#Column
private String price;
#Column
private String image;
#Column
private String description;
public int getId() {
return id;
}
// public void setId(int id) {
// this.id = id;
// }
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Here is my Repo
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.winecoff.backend.models.Food;
#Repository
public interface FoodRepository extends JpaRepository<Food, Integer> {
List<Food> findByName(String name);
List<Food> findByCategory(String category);
}
Here is my Controller
package com.winecoff.backend.controllers;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.winecoff.backend.exceptions.ResourceNotFoundException;
import com.winecoff.backend.models.Food;
import com.winecoff.backend.repositories.FoodRepository;
#RestController
#CrossOrigin
#RequestMapping("/api/v1/")
public class FoodController {
#Autowired
private FoodRepository foodRepo;
// Read and return all food items
#GetMapping("allfood")
public List<Food> getAllFood(){
return foodRepo.findAll();
}
// This is where I am having trouble
#GetMapping("food/name")
public List<Food> findAllByFoodName(String name) {
return (List<Food>) foodRepo.findByName(name);
}
//Read and return all by category
#GetMapping("food/category/{category}")
public List<Food> findByCategory(#PathVariable String category){
return (List<Food>) foodRepo.findByCategory(category);
}
// Get food item by id
#GetMapping("food/{id}")
public ResponseEntity<Food> getFoodById(#PathVariable int id){
Food food = foodRepo.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Food not found."));
return ResponseEntity.ok(food);
}
// Delete by id
// Question: Wont this change the whole menu and not whats just in the cart?
#DeleteMapping("food/{id}")
public ResponseEntity<String> deleteFood(#PathVariable int id) {
foodRepo.findById(id);
// .orElseThrow(() -> new ResourceNotFoundException("Student not found."));
// Delete method from jpa
foodRepo.deleteById(id);
return new ResponseEntity<>("Food has been deleted", HttpStatus.OK);
}
// add food to api
#PostMapping("addfood")
public Food newFood(#RequestBody Food food) {
return foodRepo.save(food);
}
// update food obj keys, such as name to the api
#PutMapping("food/{id}")
public ResponseEntity<Food> updateFood(#PathVariable int id, #RequestBody Food newFoodInfo){
Food foundFood = foodRepo.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Food not found."));
foundFood.setCategory(newFoodInfo.getCategory());
foundFood.setName(newFoodInfo.getName());
foundFood.setPrice(newFoodInfo.getPrice());
// foundFood.setId(newFoodInfo.getId());
Food updatedFood = foodRepo.save(foundFood);
return ResponseEntity.ok(updatedFood);
}
}
yes you can do custom query in your repo:
try
#Query(value="your query")
List<Food> getFoodByFilter(#Param("filter") String filter);
this page can help you: https://www.baeldung.com/spring-data-jpa-query
You can use #Query annotation and write your own custom query.
#Query("SELECT e FROM food e WHERE e.name = :name")
List<Food> findByName(#Param("name") String name);
or create a custom repository class implements from the FoodRepository interface and create custom queries.
#PersistenceContext
private EntityManager entityManager;
#Override
public List<Food> findAllByFoodName(String name) {
String query = String.format("SELECT * FROM food WHERE name = '%s' ", name);
Query q = entityManager.createNativeQuery(query);
List<Food> result = q.getResultList();
return result;
}

Getting null value in db when using #embbeded in Spring boot Rest api? new to java help me out guys

Getting null values in database for the embedded Address entity. Using MySql database. The user entity is storing values fine but embedded Address entity is returning null value, can't figure out why it's not working. help me out guys.I am a beginner tried searching everywhere but no luck. Just a novice Api but it won't work the way i want it's really annoying.
Model class
package com.example.demo;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class User {
#Id
private int id;
private String name;
#Embedded
private Address address;
public User() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String toString() {
return "user [id=" + id + ", name=" + name + ",Address="+address+" ]";
}
public User(int id, String name, Address address) {
this.id = id;
this.name = name;
this.address = address;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
---------------------------------------------------------------------------------------------------------
**Model class**
package com.example.demo;
import javax.persistence.Embeddable;
#Embeddable
public class Address {
private String cityname;
private String streetname;
private String Housename;
public Address() {
}
public Address(String cityname, String streetname, String housename) {
super();
this.cityname = cityname;
this.streetname = streetname;
Housename = housename;
}
public String getStreetname() {
return streetname;
}
public void setStreetname(String streetname) {
this.streetname = streetname;
}
public String getHousename() {
return Housename;
}
public void setHousename(String housename) {
Housename = housename;
}
public String getCityname() {
return cityname;
}
public void setCityname(String cityname) {
this.cityname = cityname;
}
}
---------------------------------------------------------------------------------------------------------
**controller class**
package com.example.demo;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class Croller {
#Autowired
TestRepo repo;
#PostMapping("/add")
public String save(#RequestBody User mode) {
repo.save(mode);
return "details saved";
}
#GetMapping("/get")
public List<User> retrive(){
return repo.findAll();
}
#GetMapping("/search")
public List<User> searchname(#RequestParam("name")String name){
return repo.name(name);
}
#GetMapping("/byid/{id}")
public Optional <User> getone (#PathVariable int id){
return repo.findById(id);
}
#PutMapping("/update")
public String updateid(#RequestBody User mode ) {
repo.save(mode);
return " user updated sucessfully";
}
#DeleteMapping("/remove/{id}")
public String delete(#PathVariable int id) {
repo.deleteById(id);
return "deleted with the given id:"+ id;
}
}
---------------------------------------------------------------------------------------------------------
Repository
package com.example.demo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TestRepo extends JpaRepository <User, Integer> {
List <User> name(String name);
}
**Application.java**
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Demoapi2Application {
public static void main(String[] args) {
SpringApplication.run(Demoapi2Application.class, args);
}
}
Your request has to match the #RequestBody object for spring to map the keys appropriately
Try this request -
{
"id":19,
"name":"Alex",
"address":{
"cityname":"california",
"streetname":"ring road",
"Housename":"Housename"
}
}
Please make sure you give input as per your Model.

How to to do a List that contains just one attribute and not repeat in Spring Boot?

I want to make a List that contains just the name of the City, no more. The citiets doesn't have to repeat, I need all the names of the city but without repeated names.
The Entity looks like this:
import org.springframework.data.annotation.Id;
import java.util.Arrays;
public class Cities {
#Id
private String _id;
private String city;
private String[] loc;
private String pop;
private String state;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
String getLocation() {
return loc[0] + " " + loc[1];
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String[] getLoc() {
return loc;
}
public void setLoc(String[] loc) {
this.loc = loc;
}
public String getPop() {
return pop;
}
public void setPop(String pop) {
this.pop = pop;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
#Override
public String toString() {
return "Cities{" +
"_id='" + _id + '\'' +
", city='" + city + '\'' +
", loc=" + Arrays.toString(loc) +
", pop='" + pop + '\'' +
", state='" + state + '\'' +
'}';
}
}
I have my Repositoy like this:
import com.sbmongo.starbucks.Entity.Cities;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository("citiesRepository")
public interface CitiesRepository extends MongoRepository<Cities, String> {
public Cities findBy_id(ObjectId _id);
public List<Cities> findByCity(String city);
public List<Cities> findAllByCity();
}
And my Controller looks like this:
import com.sbmongo.starbucks.Constant.ViewConstant;
import com.sbmongo.starbucks.Entity.Cities;
import com.sbmongo.starbucks.Repository.CitiesRepository;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.servlet.ModelAndView;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
#Controller
#RequestMapping("/starbucks")
public class CitiesController {
#Autowired
#Qualifier("citiesRepository")
private CitiesRepository citiesRepository;
#GetMapping("/cities")
public ModelAndView listCities(){
ModelAndView mav = new ModelAndView(ViewConstant.CITIES);
mav.addObject("cities", citiesRepository.findAll());
return mav;
}
#GetMapping("/searchCity")
public ModelAndView searchCity(#RequestParam(name = "city", required = false)String city){
ModelAndView mav = new ModelAndView(ViewConstant.CITIES);
mav.addObject("cities", citiesRepository.findByCity(city.toUpperCase()));
System.out.println(citiesRepository.findByCity(city.toUpperCase()));
return mav;
}
#GetMapping("/sortAllCities")
public void sortAllCities(){
List<Cities> cities = citiesRepository.findAllByCity();
}
}
But when I try to do this i throws me a IndexOutOfBoundsException.
I just want to show in the list the names of the cities and don't repeat the names.
To fill a List of unique names use Set, then loop and fill the new object.
If you need the key replace the Set with Map.
Hope this sample help
List<Cities> citiesList = findAllByCity();
Set<Cities> uniqueCities = new HashSet<>();
citiesList.forEach(c ->{
uniqueCities.add(c);
});

JPA with Spring MVC doesn't insert into database using persist

I am using spring 4 and hibernate 4 to create some web services and when I try to retrieve data from the database. It work fine but the problem is when I try to insert data.
When I lunch the project as a java application every thing work fine. The problem is only when I lunch it on the server and I am using tomcat.
This is my entity:
package com.pfe.ecole.entity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import com.fasterxml.jackson.annotation.JsonIgnore;
#SuppressWarnings("serial")
#Entity
public class Specialite implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String specialite;
#ManyToMany(mappedBy="specialites")
#JsonIgnore
private List<Professeur> professeurs;
public List<Professeur> getProfesseurs() {
return professeurs;
}
public void setProfesseurs(List<Professeur> professeurs) {
this.professeurs = professeurs;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSpecialite() {
return specialite;
}
public void setSpecialite(String specialite) {
this.specialite = specialite;
}
public Specialite() {
// TODO Auto-generated constructor stub
}
public Specialite(int id, String specialite) {
super();
this.id = id;
this.specialite = specialite;
}
public Specialite(String specialite) {
super();
this.specialite = specialite;
}
}
package com.pfe.ecole.entity;
import java.io.Serializable;
import java.util.Set;
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;
#SuppressWarnings("serial")
#Entity
public class Professeur implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
#Column(unique=true, nullable=false)
private String cin;
#Column(unique=true, nullable=false)
private int tel;
#ManyToMany(targetEntity=Specialite.class, cascade = CascadeType.PERSIST)
private Set<Specialite> specialites;
private String nom;
private String prenom;
#Column(unique=true, nullable=false)
private String email;
private String adresse;
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public Set<Specialite> getSpecialites() {
return specialites;
}
public void setSpecialite(Set<Specialite> specialites) {
this.specialites = specialites;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCin() {
return cin;
}
public void setCin(String cin) {
this.cin = cin;
}
public int getTel() {
return tel;
}
public void setTel(int tel) {
this.tel = tel;
}
public Professeur() {
// TODO Auto-generated constructor stub
}
public Professeur(String cin, int tel, Set<Specialite> specialites, String nom, String prenom, String email,
String adresse) {
super();
this.cin = cin;
this.tel = tel;
this.specialites = specialites;
this.nom = nom;
this.prenom = prenom;
this.email = email;
this.adresse = adresse;
}
public Professeur(long id, String cin, int tel, Set<Specialite> specialites, String nom, String prenom,
String email, String adresse) {
super();
this.id = id;
this.cin = cin;
this.tel = tel;
this.specialites = specialites;
this.nom = nom;
this.prenom = prenom;
this.email = email;
this.adresse = adresse;
}
}
and this is my services
package com.pfe.ecole.services;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.pfe.ecole.entity.Agent;
import com.pfe.ecole.entity.Specialite;
#Service("specialiteImpl")
#Transactional
public class SpecialiteImpl implements ISpecialite{
#PersistenceContext
private EntityManager em;
#Override
public Specialite add(Specialite specialite) {
em.persist(new Agent());
return specialite;
}
#Override
public Specialite update(Specialite specialite) {
em.persist(specialite);
return specialite;
}
#SuppressWarnings("unchecked")
#Override
public List<Specialite> listAllSpecialite() {
return em.createQuery("select s from Specialite s").getResultList();
}
}
package com.pfe.ecole.services;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.pfe.ecole.entity.Professeur;
import com.pfe.ecole.entity.Specialite;
#Service("professeurImpl")
#Transactional
public class ProfesseurImpl implements IProfesseur{
#PersistenceContext
private EntityManager em;
#SuppressWarnings("unchecked")
#Override
public List<Professeur> listAll(int page, int items) {
List<Professeur> profList;
profList=em.createQuery("select p from Professeur p order by p.prenom").setFirstResult(page-1).setMaxResults(items).getResultList();
return profList;
}
#Override
public Professeur findByCin(int cin) {
Query req=em.createQuery("select p from Professeur p where p.cin=:cin").setParameter("cin", cin);
try{
return (Professeur) req.getSingleResult();
}
catch(NoResultException nrEx) {
return null;
}
}
#SuppressWarnings("unchecked")
#Override
public List<Professeur> findByNom(String nom) {
Query req = em.createQuery("select p from Professeur p where p.nom=:nom ").setParameter("nom", nom);
return req.getResultList();
}
#Override
public List<Professeur> listProfBySpec(Specialite spec) {
List<Professeur> profs = new ArrayList<Professeur>();
profs.addAll(spec.getProfesseurs());
return profs;
}
#Override
public Professeur add(Professeur professeur) {
em.persist(professeur);
return professeur;
}
#Override
public Professeur update(Professeur professeur) {
em.persist(professeur);
return professeur;
}
#Override
public int count() {
// TODO Auto-generated method stub
return (int) em.createQuery("select COUNT(p) from Professeur p").getFirstResult();
}
}
and this is the controller
package com.pfe.ecole.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import com.pfe.ecole.entity.Specialite;
import com.pfe.ecole.services.ISpecialite;
#Controller
#RestController
#EnableWebMvc
#CrossOrigin
public class SpecialiteCtrl {
#Autowired
ISpecialite metier;
#RequestMapping(value="/specialites",method=RequestMethod.GET)
#ResponseBody Map<String, List<Specialite>> get(){metier.add(new Specialite("ddd"));
Map<String, List<Specialite>> result = new HashMap<String,List<Specialite>>();
result.put("content", metier.listAllSpecialite());
return result;
}
}
package com.pfe.ecole.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import com.pfe.ecole.entity.Professeur;
import com.pfe.ecole.services.IProfesseur;
import com.pfe.ecole.services.Page;
#Controller
#RestController
#EnableWebMvc
#CrossOrigin
public class ProfCtrl {
#Autowired
IProfesseur metier;
#RequestMapping(value="/teacher",method=RequestMethod.POST)
#ResponseBody Professeur add(#RequestBody Professeur professeur) {
return metier.add(professeur);
}
#RequestMapping(value="/teachers/{page}/{items}",method=RequestMethod.GET)
#ResponseBody Page getByParm(#PathVariable("page") int page, #PathVariable("items") int items){
return getAll(page, items);
}
#RequestMapping(value="/teachers/{page}",method=RequestMethod.GET)
#ResponseBody Page getByParm(#PathVariable("page") int page){
return getAll(page, 10);
}
#RequestMapping(value="/teachers",method=RequestMethod.GET)
#ResponseBody Page getByParm(){
return getAll(1, 10);
}
private Page getAll(int page, int items){
return new Page(page,metier.count(),metier.listAll(page, items));
}
}
this is the test that works as java application
public static void main(String[] args) {
ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("root-context.xml");
ISpecialite m = (ISpecialite) context.getBean("specialiteImpl");
Specialite s= new Specialite("Web Dev");
m.add(s);
}
This is the error I am getting
javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call
adding this annotation to service solved the problem #EnableTransactionManagement

Getting Date as null when using java.sql.Date

I am trying to insert the date into database and I am using java.sql.Date but the problem when user is submitting the form I am getting Null value. As per some restriction I am only allowed to use java.sql.Date not util.Date.
Entity
import java.sql.Date;
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.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;
#Entity
#Table(name="Users")
public class Users {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="User_ID")
private int ID;
#Column(name="User_first_name")
#NotEmpty(message="Field cannot be left blank")
private String First_Name;
#Column(name="user_last_name")
private String Last_Name;
#Column(name="user_contact")
private int Contact;
#Column(name="user_email")
private String Email;
#Column(name="user_date_birth")
#DateTimeFormat(pattern="dd/MM/yyyy")
private Date DateOfBirth;
#Column(name="user_joining_date")
private Date DateOfJoining;
#Column(name="user_salary")
#NotNull
private int Salary;
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public String getFirst_Name() {
return First_Name;
}
public void setFirst_Name(String first_Name) {
First_Name = first_Name;
}
public String getLast_Name() {
return Last_Name;
}
public void setLast_Name(String last_Name) {
Last_Name = last_Name;
}
public int getContact() {
return Contact;
}
public void setContact(int contact) {
Contact = contact;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public Date getDateOfBirth() {
return DateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
DateOfBirth = dateOfBirth;
}
public Date getDateOfJoining() {
return DateOfJoining;
}
public void setDateOfJoining(Date dateOfJoining) {
DateOfJoining = dateOfJoining;
}
public int getSalary() {
return Salary;
}
public void setSalary(int salary) {
Salary = salary;
}
}
Controller
package com.example.crud;
import java.text.SimpleDateFormat;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.example.crud.entities.Users;
import com.example.crud.service.TaskService;
#Controller
public class HomeController {
#Autowired
private TaskService service;
private Logger logger = LoggerFactory.getLogger(HomeController.class);
#InitBinder
public void initBinder(WebDataBinder binder){
System.out.println("exe");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setLenient(true);
binder.registerCustomEditor(java.sql.Date.class,"DateOfBirth", new CustomDateEditor(sdf, true));
}
#RequestMapping(value="/Add", method=RequestMethod.GET)
public String index(Map<String, Object> model){
Users users = new Users();
model.put("users", users);
logger.debug("users");
return "home";
}
#RequestMapping(value="/Register", method=RequestMethod.POST)
public String Register(#ModelAttribute("users") Users users, BindingResult result, Model model){
System.out.println(users.getFirst_Name());
System.out.println(users.getDateOfBirth());
// service.Register(users);
return "home";
}
}
Register your own custom editor.
public class SqlDateEditor extends PropertyEditorSupport {
private DateFormat dateFormat;
public SqlDateEditor (final DateFormat dateFormat)
{
this.dateFormat = dateFormat;
}
#Override
public void setAsText(String text) {
try {
setValue(new java.sql.Date(this.dateformat.parse(text).getTime())
} catch (ParseException e) {
throw new IllegalArgumentException("Could not parse date: " + e.getMessage());
}
}
#Override
public String getAsText() {
java.sql.Date value = (java.sql.Date) getValue();
return (value != null ? this.dateFormat.format(value) : "");
}
}
At your controller:
#InitBinder
public void initBinder(final WebDataBinder binder) {
binder.registerCustomEditor(java.sql.Date.class, new SqlDateEditor(new SimpleDateFormat("dd/MM/yyyy")));
}

Categories

Resources