I am trying to make a simple Spring/Hibernate/MySQL CRUD but it is not working :/ I got:
HTTP Status 500 - Internal Server Error
Type Exception Report
Message: Request processing failed; nested exception is
java.lang.IllegalArgumentException:
org.hibernate.hql.internal.ast.QuerySyntaxException: employees is not
mapped [from employees order by last_name]
Description: The server encountered an unexpected condition that
prevented it from fulfilling the request.
Here's my code:
Employee.java
package com.employeemanager.entity;
import java.util.Set;
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="employees")
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Column(name="email")
private String email;
#Column(name="username")
private String username;
#Column(name="password")
private String password;
public Employee(){
}
public Employee(String firstName){
}
public Employee(String firstName,Set<Project> projects){
this.firstName=firstName;
this.projects=projects;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
EmployeeDAO.java
package com.employeemanager.dao;
import java.util.List;
import com.employeemanager.entity.Employee;
public interface EmployeeDAO {
public List<Employee> getEmployees();
public void saveEmployee(Employee theEmployee);
public Employee getEmployee(int theId);
public void deleteEmployee(int theId);
}
EmployeeDAOImpl.java
package com.employeemanager.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.employeemanager.entity.Employee;
#Repository
public class EmployeeDAOImpl implements EmployeeDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
public List<Employee> getEmployees() {
Session currentSession=sessionFactory.getCurrentSession();
List<Employee> employeeList=
currentSession.createQuery("from employees order by
last_name").getResultList();
return employeeList;
}
#Override
public void saveEmployee(Employee theEmployee) {
Session currentSession=sessionFactory.getCurrentSession();
currentSession.saveOrUpdate(theEmployee);
}
#Override
public Employee getEmployee(int theId) {
Session currentSession=sessionFactory.getCurrentSession();
Employee theEmployee=currentSession.get(Employee.class, theId);
return theEmployee;
}
#Override
public void deleteEmployee(int theId) {
Session currentSession=sessionFactory.getCurrentSession();
Employee employee=((Employee)
currentSession.load(Employee.class,theId));
if(null!=employee){
this.sessionFactory.getCurrentSession().delete(employee);
}
}
}
EmployeeService.java
package com.employeemanager.service;
import java.util.List;
import com.employeemanager.entity.Employee;
public interface EmployeeService {
public List<Employee> getEmployees();
public void saveEmployee(Employee theEmployee);
public Employee getEmployee(int theId);
public void deleteEmployee(int theId);
}
EmployeeServiceImpl.java
package com.employeemanager.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.employeemanager.entity.Employee;
import com.employeemanager.dao.EmployeeDAO;
#Service
public class EmployeeServiceImpl implements EmployeeService {
#Autowired
private EmployeeDAO employeeDAO;
#Override
#Transactional
public List<Employee> getEmployees() {
return employeeDAO.getEmployees();
}
#Override
#Transactional
public void saveEmployee(Employee theEmployee) {
employeeDAO.saveEmployee(theEmployee);
}
#Override
#Transactional
public Employee getEmployee(int theId) {
return employeeDAO.getEmployee(theId);
}
#Override
#Transactional
public void deleteEmployee(int theId) {
employeeDAO.deleteEmployee(theId);
}
}
EmployeeController.java
package com.employeemanager.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.employeemanager.entity.Employee;
import com.employeemanager.entity.Project;
import com.employeemanager.service.EmployeeService;
import com.employeemanager.service.ProjectService;
#Controller
#RequestMapping("/employee")
public class EmployeeController {
#Autowired
private EmployeeService employeeService;
#Autowired
private ProjectService projectService;
#GetMapping("/list")
public String listEmployees(Model theModel){
List<Employee> theEmployees=employeeService.getEmployees();
theModel.addAttribute("employees",theEmployees);
return"employees-list";
}
#GetMapping("/addEmployeeForm")
public String addEmployeeForm(Model theModel){
Employee theEmployee=new Employee();
List<Project> theProjects=projectService.getProjects();
theModel.addAttribute("projects",theProjects);
theModel.addAttribute("employee",theEmployee);
return"employee-form";
}
#PostMapping("/saveEmployee")
public String saveEmployee(#ModelAttribute("employee") Employee theEmployee)
{
employeeService.saveEmployee(theEmployee);
return "redirect:/employee/list";
}
#GetMapping("/updateEmployeeForm")
public String updateEmployeeForm(#RequestParam("employeeId") int theId,
Model theModel){
Employee theEmployee=employeeService.getEmployee(theId);
theModel.addAttribute("employee",theEmployee);
return"employee-form";
}
#GetMapping("/deleteEmployee")
public String deleteEmployee(#RequestParam("employeeId") int theId){
employeeService.deleteEmployee(theId);
return"redirect:/employee/list";
}
}
Do you have any ideas how to resolve this problem?
Thank you for all your help :)
Change your HQL from this:
from employees order by last_name
To this:
from Employee e order by e.lastName
In HQL you should use namings the same as your mapped class.
If you are using HQL, then java Entity names should be used instead of real table names:
#Repository
public class EmployeeDAOImpl implements EmployeeDAO {
#Override
public List<Employee> getEmployees() {
Session currentSession = sessionFactory.getCurrentSession();
return currentSession.createQuery("from Employee order by last_name").getResultList();
}
}
I think that there is an error in EmployeeDAOImpl.java. Change "employees" to "Employee" and "last_name" to "lastName" (names should be the same as in the mapped class(Employee.java))
Just change:
#Override
public List<Employee> getEmployees() {
Session currentSession=sessionFactory.getCurrentSession();
List<Employee> employeeList=
currentSession.createQuery("from employees order by
last_name").getResultList();
return employeeList;
}
to:
#Override
public List<Employee> getEmployees() {
Session currentSession=sessionFactory.getCurrentSession();
List<Employee> employeeList=
currentSession.createQuery("from Employee order by
lastName").getResultList();
return employeeList;
}
and tell us if it worked :)
Related
I'm trying to sort of login with JPA and hibernate. The truth is that I'm new to working with hibernate and I don't know what I'm doing wrong.
I have two entity classes (User and Credential), and I have already mapped them in the persistence.xml file
<!-- Define Persistence Unit -->
<persistence-unit name="HibernateSchedule" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>ues.edu.sv.entity.User</class>
<class>ues.edu.sv.entity.Credential</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/diary?useSSL=false&useTimezone=true&serverTimezon=UTC&allowPublicKeyRetrieval=true"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="localhost"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
</persistence-unit>
These are the entity classes:
package ues.edu.sv.entity;
import java.io.Serializable;
import javax.persistence.*;
#Entity
#NamedQueries({
#NamedQuery(name="User.listAllUsers", query="SELECT u FROM User u")
})
#Table(name = "\"user\"")
public class User implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "id_user")
private int idUser;
private String name;
#Column(name = "lastname")
private String lastName;
private String email;
public User(){}
public User(int idUser){
this.idUser = idUser;
}
public User(String name, String lastName, String email){
this.name = name;
this.lastName = lastName;
this.email = email;
}
public User(int idUser, String name, String lastName, String email){
this.idUser = idUser;
this.name = name;
this.lastName = lastName;
this.email = email;
}
public int getIdUser() {
return idUser;
}
public void setIdUser(int idUser) {
this.idUser = idUser;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "User{" + "idUser=" + idUser + ", name=" + name + ", lastName=" + lastName + ", email=" + email + '}';
}
}
This is the Credential class
package ues.edu.sv.entity;
import java.io.Serializable;
import javax.persistence.*;
#Entity
#NamedQueries({
#NamedQuery(name = "Credential.getAllCredentials", query = "SELECT c FROM Credential
c")
})
#Table(name = "credential")
public class Credential implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "id_credential")
private int idCredential;
#Column(name = "username")
private String userName;
private String password;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "id_user", referencedColumnName = "id_user")
private User user;
public Credential(){}
public Credential(int idCredential){
this.idCredential = idCredential;
}
public Credential(String userName, String password){
this.userName = userName;
this.password = password;
}
public Credential(String userName, String password, User user){
this.userName = userName;
this.password = password;
this.user = user;
}
public Credential(int idCredential,String userName, String password){
this.idCredential = idCredential;
this.userName = userName;
this.password = password;
}
public int getIdCredential() {
return idCredential;
}
public void setIdCredential(int idCredential) {
this.idCredential = idCredential;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#Override
public String toString() {
return "Credential{" + "idCredential=" + idCredential + ", userName=" + userName + ", password=" + password + ", user=" + user + '}';
}
}
I am using a three layer pattern to retrieve the information, so I have a package "ues.edu.sv.dao" where I have two interfaces and two classes that implement them and are defined as ejb
package ues.edu.sv.dao;
import java.util.List;
import ues.edu.sv.entity.User;
public interface UserDao {
public List<User> listAllUsers();
public User getUserById(User user);
public void createNewUser(User user);
public void updateUser(User user);
public void deleteUser(User user);
}
package ues.edu.sv.dao;
import java.util.List;
import ues.edu.sv.entity.Credential;
public interface CredentialDao {
public List<Credential> getAllCredentials();
public Credential getCredentialById(Credential credential);
public Credential getCredentialByUserName(Credential credential);
public void createNewCredential(Credential credential);
public void updateCredential(Credential credential);
public void deleteCredential(Credential credential);
}
And here are the classes that implement their corresponding interface
package ues.edu.sv.dao;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.*;
import ues.edu.sv.entity.User;
#Stateless
public class UserDaoImpl implements UserDao {
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("HibernateSchedule");
EntityManager em = emf.createEntityManager();
#Override
public List<User> listAllUsers() {
return em.createNamedQuery("User.listAllUsers").getResultList();
}
#Override
public User getUserById(User user) {
return em.find(User.class, user.getIdUser());
}
#Override
public void createNewUser(User user) {
em.persist(user);
}
#Override
public void updateUser(User user) {
em.merge(user);
}
#Override
public void deleteUser(User user) {
em.remove(em.merge(user));
}
}
package ues.edu.sv.dao;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import ues.edu.sv.entity.Credential;
#Stateless
public class CredentialDaoImpl implements CredentialDao {
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("HibernateSchedule");
EntityManager em = emf.createEntityManager();
#Override
public List<Credential> getAllCredentials() {
return em.createNamedQuery("Credential.getAllCredentials").getResultList();
}
#Override
public Credential getCredentialById(Credential credential) {
return em.find(Credential.class, credential.getIdCredential());
}
#Override
public Credential getCredentialByUserName(Credential credential) {
return em.find(Credential.class, credential.getUserName());
}
#Override
public void createNewCredential(Credential credential) {
em.persist(credential);
}
#Override
public void updateCredential(Credential credential) {
em.merge(credential);
}
#Override
public void deleteCredential(Credential credential) {
em.remove(em.merge(credential));
}
}
My understanding is that since I am working in a java enterprise context, there is no need to open a transaction when persisting an object in the database. I am using glassfish by the way.
now to complete the three-layer pattern, I have another package called "ues.edu.sv.service" that injects the above interfaces via CDI
package ues.edu.sv.service;
import java.util.List;
import javax.ejb.Local;
import ues.edu.sv.entity.Credential;
#Local
public interface CredentialService {
public List<Credential> getAllCredentials();
public Credential getCredentialById(Credential credential);
public Credential getCredentialByUserName(Credential credential);
public void createNewCredential(Credential credential);
public void updateCredential(Credential credential);
public void deleteCredential(Credential credential);
}
package ues.edu.sv.service;
import java.util.List;
import javax.ejb.Local;
import ues.edu.sv.entity.User;
#Local
public interface UserService {
public List<User> listAllUsers();
public User getUserById(User user);
public void createNewUser(User user);
public void updateUser(User user);
public void deleteUser(User user);
}
and implementation classes
package ues.edu.sv.service;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.inject.Inject;
import ues.edu.sv.dao.CredentialDao;
import ues.edu.sv.entity.Credential;
#Stateless
public class CredentialServiceImpl implements CredentialService{
#Inject
CredentialDao credentialDao;
#Resource
SessionContext context;
#Override
public List<Credential> getAllCredentials() {
return credentialDao.getAllCredentials();
}
#Override
public Credential getCredentialById(Credential credential) {
return credentialDao.getCredentialById(credential);
}
#Override
public Credential getCredentialByUserName(Credential credential) {
return credentialDao.getCredentialByUserName(credential);
}
#Override
public void createNewCredential(Credential credential) {
credentialDao.createNewCredential(credential);
}
#Override
public void updateCredential(Credential credential) {
try{
credentialDao.updateCredential(credential);
}catch(Exception ex){
ex.printStackTrace(System.out);
context.setRollbackOnly();
}
}
#Override
public void deleteCredential(Credential credential) {
credentialDao.deleteCredential(credential);
}
}
package ues.edu.sv.service;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.inject.Inject;
import ues.edu.sv.dao.UserDao;
import ues.edu.sv.entity.User;
#Stateless
public class UserServiceImpl implements UserService{
#Inject
UserDao userDao;
#Resource
SessionContext context;
#Override
public List<User> listAllUsers() {
return userDao.listAllUsers();
}
#Override
public User getUserById(User user) {
return userDao.getUserById(user);
}
#Override
public void createNewUser(User user) {
userDao.createNewUser(user);
}
#Override
public void updateUser(User user) {
try{
userDao.updateUser(user);
}catch(Exception ex){
ex.printStackTrace(System.out);
context.setRollbackOnly();
}
}
#Override
public void deleteUser(User user) {
userDao.deleteUser(user);
}
}
And finally I have an ejb that connects to the jsf page called "Register.xhtml" and is responsible for retrieving the information that the user enters in the text fields to finally persist the information in the database, I have programmed the relationships so cascading user object can be persisted
package ues.edu.sv.beans;
import java.io.IOException;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import ues.edu.sv.crypto.Cypher;
import ues.edu.sv.entity.Credential;
import ues.edu.sv.entity.User;
import ues.edu.sv.service.CredentialService;
import ues.edu.sv.service.UserService;
#Named
#RequestScoped
public class RegisterBean {
#Inject
CredentialService credentialService;
#Inject
UserService userService;
private String name;
private String lastName;
private String email;
private String userName;
private String password;
public RegisterBean() {
}
public void toRegister() {
User user = new User(name, lastName, email);
String encriptedPassword = Cypher.encryptPassword(password);
Credential credential = new Credential(userName, encriptedPassword, user);
credentialService.createNewCredential(credential);
try {
FacesContext.getCurrentInstance().getExternalContext().redirect("Login.xhtml");
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
And apparently everything is fine, the console does not show me any error, but it does nothing in the database, it does not insert the content into the database :(
This is what appears in the console when everything has been executed...
]|#]
HHH000204: Processing PersistenceUnitInfo [name: HibernateSchedule]|#]
HHH000412: Hibernate Core {6.0.0.Alpha4}|#]
HCANN000001: Hibernate Commons Annotations {5.1.0.Final}|#]
HHH10001002: Using Hibernate built-in connection pool (not for production use!)|#]
HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL
[jdbc:mysql://localhost:3306/diary?
useSSL=false&useTimezone=true&serverTimezon=UTC&allowPublicKeyRetrieval=true]|#]
HHH10001001: Connection properties: {user=root, password=****}|#]
HHH10001003: Autocommit mode: false|#]
HHH000115: Hibernate connection pool size: 20 (min=1)|#]
HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect|#]
HHH10005002: No explicit CDI BeanManager reference was passed to Hibernate, but CDI
is available on the Hibernate ClassLoader.|#]
HHH000490: Using JtaPlatform implementation:
[org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]|#]
That is all that appears. Someone who can help me please
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.
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
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")));
}
code for employee.java
package Data;
import java.io.Serializable;
import java.util.*;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
#Entity
public class Employee implements Serializable {
private int empid;
private String empName;
private String empEmailAddress;
private boolean isActive;
private String empAddress;
private String empphone;
#OneToMany
private List<Department> deptobj;= new ArrayList<Department>();
private String emprole;
private Integer salary;
public void setdeptobj(List<Department> deptobj) {
this.deptobj; = deptobj;
}
public List<Department> getdeptobj() {
return deptobj;;
}
public void setempEmailAddress(String empEmailAddress) {
this.empEmailAddress = empEmailAddress;
}
public String getempEmailAddress() {
return empEmailAddress;
}
public boolean getisActive() {
return isActive;
}
public void setisActive(boolean isActive) {
this.isActive = isActive;
}
public String getempAddress() {
return empAddress;
}
public void setempAddress(String empAddress) {
this.empAddress = empAddress;
}
public String getempphone() {
return empphone;
}
public void setempphone(String empphone) {
this.empphone = empphone;
}
public String getemprole() {
return emprole;
}
public void setemprole(String emprole) {
this.emprole = emprole;
}
public int getsalary() {
return salary;
}
public void setsalary(int salary) {
this.salary = salary;
}
#Id
public int getEmpid() {
return empid;
}
public void setEmpid(int empid) {
this.empid = empid;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
}
code for Department.java
package Data;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
#Entity
public class Department {
private String dept;
#ManyToOne
private Employee employee;
#Id
private int deptid;
public String getdept() {
return dept;
}
public void setdept(String dept) {
this.dept = dept;
}
public int getdeptid() {
return deptid;
}
public void setdeptid(int deptid) {
this.deptid = deptid;
}
private Employee getemployee(){
return employee;
}
private void setemployee(Employee employee){
this.employee = employee;
}
}
code for middle layer
package service;
import Data.*;
import static com.mchange.v2.log.MLog.config;
import java.io.Serializable;
import java.util.List;
import javax.imageio.spi.ServiceRegistry;
import javax.persistence.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
public class ServiceLayer {
SessionFactory sessionFactory = new AnnotationConfiguration().configure("hibernate.cfg.xml").buildSessionFactory();
Session session = sessionFactory.openSession() ;
public void add(Employee emp){
session.beginTransaction();
System.out.println("hello");
session.save(emp);
System.out.println("hello");
session.getTransaction().commit();
}
public void delete(int empid){
session.beginTransaction();
Employee emp = (Employee) session.get(Employee.class, empid);
session.delete(emp);
session.getTransaction().commit();
}
public void update(Employee emp){
session.beginTransaction();
session.update(emp);
session.getTransaction().commit();
}
public void read(){
session.beginTransaction();
String hql = "select * from Employee;";
session.createSQLQuery(hql);
session.getTransaction().commit();
}
public Department check(String dept){
session.beginTransaction();
SQLQuery q = session.createSQLQuery("from Department d where d.dept=:deptname");
q.setParameter("deptname", dept);
Department d = (Department) q.uniqueResult();
session.getTransaction().commit();
return d;
}
public Department getDept(Department list){
session.beginTransaction();
Department deptobj= (Department) session.get(Department.class, (Serializable) list.getdeptid());
session.getTransaction().commit();
return deptobj;
}
public void addDept(Department dep){
session.beginTransaction();
session.save(dep);
session.getTransaction().commit();
}
}
code for mainservice layer
package mainService;
import Data.*;
import static java.sql.Types.NULL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import service.ServiceLayer;
public class Logic {
private int empid;
private String empName;
ServiceLayer sl = new ServiceLayer();
private String empPassword;
private String empEmailAddress;
private boolean isPermanent;
private Calendar empJoinDate;
public void add(String empName,String empEmailAddress,String empAddress,String empphone,String dept,String emprole,Integer salary,boolean active){
Employee emp = new Employee();
emp.setEmpName(empName);
emp.setempAddress(empAddress);
emp.setempEmailAddress(empEmailAddress);
emp.setempphone(empphone);
emp.setemprole(emprole);
emp.setsalary(salary);
emp.setisActive(active);
Department dep = null;
Department list = sl.check(dept);
if(list.getdeptid()==NULL){
dep = addDept(dept);
}
else{
dep = sl.getDept(list);
}
emp.getdeptobj().add((Department) dep);
sl.add(emp);
}
private Department addDept(String dept) {
Department dep = new Department();
dep.setdept(dept);
sl.addDept(dep);
Department list = sl.check(dept);
dep = (Department) sl.getDept(list);
return dep;
}
}
Service layer gets the values from form created in swing then it passes the data to ServiceLayer.java file which creates session and sets the value to create a record and then save that record THE problem is I want to check if department already exists, then link with that for that search will be based on department name given by user if department does not exixt then first create new department and then link with employee.
I am not able to get where the problem is because I haven't used hibernate before... so please help me. And on running the file I am getting the ERROR of
Exception in thread "AWT-EventQueue-0" org.hibernate.MappingException:
Could not determine type for: java.util.List, for columns:
[org.hibernate.mapping.Column(deptobj)])
Either you put JPA annotations on getters, consistently, or you put them on fields, consistently. Mixing both in a single class makes Hibernate ignore all the ones that aren't placed on the same location as the #Id annotation.
Also, your mapping is weird: a department has a single employee, which also belongs to other departments? Is this a mapping for a single-person company doing everything? You probably want the association in the other direction: a department has many employees, and each employee belongs to one department.