简体   繁体   中英

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

添加此批注到服务解决了@EnableTransactionManagement问题

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM