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

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

Related

Error when trying to map foreing key in SpringBoot

I'm trying to create an API for saving a Person and its Address, like in this model:
And i'm getting this error when trying to save an address with a foreing key:
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error:
Cannot construct instance of `com.apitest.api.model.Pessoa` (although at least one Creator exists):
no int/Int-argument constructor/factory method to deserialize from Number value (1)]
I know it seems like a parser error, but it just happens when i do a request that contains the fk field, so:
This is a valid request:
{
"logradouro": "test",
"cep": "354",
"numero": "test",
"cidade": "test"
}
This one i get a 400 bad request:
{
"logradouro": "null",
"cep": "354",
"numero": "null",
"cidade": "null",
"pessoa": 1
}
Just by adding the fk field, like i said.
Models:
Person
package com.apitest.api.model;
import java.util.Date;
import java.util.List;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
#Entity
#Table(name = "pessoa")
public class Pessoa {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column(name = "nome")
private String nome;
#Column(name = "dataNascimento")
private Date dataNascimento;
public Pessoa(Integer id, String nome, Date dataNascimento) {
this.id = id;
this.nome = nome;
this.dataNascimento = dataNascimento;
}
public Pessoa(){
};
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Date getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(Date dataNascimento) {
this.dataNascimento = dataNascimento;
}
}
Address
package com.apitest.api.model;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
#Entity
#Table(name = "endereco")
public class Endereco {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id_endereco;
#Column(name = "logradouro")
private String logradouro;
#Column(name = "cep")
private String cep;
#Column(name = "numero")
private String numero;
#Column(name = "cidade")
private String cidade;
#ManyToOne
#JoinColumn(name = "id")
private Pessoa pessoa;
public Endereco(Integer id_endereco, String logradouro, String cep, String numero, String cidade, Pessoa pessoa) {
this.id_endereco = id_endereco;
this.logradouro = logradouro;
this.cep = cep;
this.numero = numero;
this.cidade = cidade;
this.pessoa = pessoa;
}
public Endereco(){
};
public String getLogradouro() {
return logradouro;
}
public void setLogradouro(String logradouro) {
this.logradouro = logradouro;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getCidade() {
return cidade;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
public Pessoa getPessoa() {
return pessoa;
}
public void setPessoa(Pessoa pessoa) {
this.pessoa = pessoa;
}
public Integer getId_endereco() {
return id_endereco;
}
public void setId_endereco(Integer id_endereco) {
this.id_endereco = id_endereco;
}
}
Controllers:
Person
package com.apitest.api.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.apitest.api.model.Pessoa;
import com.apitest.api.service.PessoaService;
#RestController
public class PessoaController {
#Autowired
private PessoaService pessoaService;
#PostMapping("/pessoas")
public ResponseEntity<Pessoa> createPessoa(#RequestBody Pessoa pessoa){
return ResponseEntity.ok().body(this.pessoaService.createPessoa(pessoa));
}
}
Address
package com.apitest.api.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.apitest.api.model.Endereco;
import com.apitest.api.service.EnderecoService;
#RestController
public class EnderecoController {
#Autowired
private EnderecoService enderecoService;
#PostMapping("/endereco")
public ResponseEntity<Endereco> createEndereco(#RequestBody Endereco endereco){
return ResponseEntity.ok().body(this.enderecoService.createEndereco(endereco));
}
}
Service:
Person
package com.apitest.api.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.apitest.api.model.Pessoa;
import com.apitest.api.repository.PessoaRepository;
#Service
#Transactional
public class PessoaServiceImpl implements PessoaService {
#Autowired
private PessoaRepository pessoaRepository;
#Override
public Pessoa createPessoa(Pessoa pessoa) {
return pessoaRepository.save(pessoa);
}
#Override
public Pessoa updatePessoa(Pessoa pessoa) {
Optional<Pessoa> pessoaDb = this.pessoaRepository.findById(pessoa.getId());
Pessoa pessoaUpdate = pessoaDb.get();
pessoaUpdate.setId(pessoa.getId());
pessoaUpdate.setNome(pessoa.getNome());
return pessoaUpdate;
}
#Override
public Pessoa getPessoaById(Pessoa pessoa) {
// TODO Auto-generated method stub
return null;
}
#Override
public List<Pessoa> getAllPessoa() {
// TODO Auto-generated method stub
return null;
}
#Override
public void deletePessoa(long pessoaId) {
// TODO Auto-generated method stub
}
}
Address
package com.apitest.api.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.apitest.api.model.Endereco;
import com.apitest.api.repository.EnderecoRepository;
import com.apitest.api.repository.PessoaRepository;
import org.springframework.transaction.annotation.Transactional;
#Service
#Transactional
public class EnderecoServiceImpl implements EnderecoService {
#Autowired
private EnderecoRepository enderecoRepository;
#Override
public Endereco createEndereco(Endereco endereco) {
return enderecoRepository.save(endereco);
}
}
I have already tried to use JsonCreator and JsonProperty annotations but did not worked for me...
Any help would be appreciated.
You're getting this error because you're sending the value of "1" for the object Pessoa. You need to pass the fields in the object, something like this should work.
{ "logradouro": "null", "cep": "354", "numero": "null", "cidade": "null", "pessoa": {"id": 1} }
Also, I'm not sure what "null" means here, but if you want those fields to be null, don't send them. The way this is written, you're going to end up with the word null everywhere.

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.

SpringBoot CRUD

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.

java - Spring - Injection of autowired dependencies failed

-
I am trying to create mapped cart entity.but shows 404 error associated with Injection of autowired dependencies failed
Check my source and help me ro solve it..
Mapping plan:
Customer-----one to one------>Cart--------onetomany--->Product
Customer
package com.model;
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.ManyToOne;
import javax.persistence.OneToOne;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
#Entity
public class Customer {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="Cid")
private int customerId;
#Column(name="password")
#NotEmpty(message="Name is mandatory")
private String password;
#Column(name="Email")
#NotEmpty(message="Name is mandatory")
private String email;
#NotEmpty(message="First Name is mandatory")
#Column(name="firstname")
private String firstName;
#NotEmpty(message="Last Name is mandatory")
#Column(name="lastname")
private String lastName;
#Column(name="Mobile")
#Size(min = 10)
#NotEmpty(message="Mobile is mandatory")
private String mobile;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="address_id")
private Address delAdderss;
private boolean enabled;
private String role;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="cart_id")
private Cart cart;
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public Address getDelAdderss() {
return delAdderss;
}
public void setDelAdderss(Address delAdderss) {
this.delAdderss = delAdderss;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
}
Cart
package com.model;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
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.OneToMany;
import javax.persistence.OneToOne;
#Entity
public class Cart {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int cart_id;
#Column
private double total;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="CID")
private Customer customer;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name="id")
private List<Product> product;
public int getCart_id() {
return cart_id;
}
public void setCart_id(int cart_id) {
this.cart_id = cart_id;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public List<Product> getProduct() {
return product;
}
public void setProduct(List<Product> product) {
this.product = product;
}
}
Product
package com.model;
import java.util.Date;
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.ManyToOne;
import javax.persistence.Transient;
import org.springframework.web.multipart.MultipartFile;
#Entity
public class Product {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column
private String product_Name;
#Column
private String descripction;
#Column
private int price;
#Column
private Date mfg_Date;
#Transient
private MultipartFile image;
#ManyToOne(cascade = CascadeType.ALL)
private List<Cart> cart;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProduct_Name() {
return product_Name;
}
public void setProduct_Name(String product_Name) {
this.product_Name = product_Name;
}
public String getDescripction() {
return descripction;
}
public void setDescripction(String descripction) {
this.descripction = descripction;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Date getMfg_Date() {
return mfg_Date;
}
public void setMfg_Date(Date mfg_Date) {
this.mfg_Date = mfg_Date;
}
public MultipartFile getImage() {
return image;
}
public void setImage(MultipartFile image) {
this.image = image;
}
public List<Cart> getCarts() {
return cart;
}
public void setCarts(List<Cart> carts) {
this.cart= carts;
}
}

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