I've got a little 'complex' question.
I'm using Hibernate/JPA to make transactions with a DB.
I'm not the DBA, and a client consumes my application, a RESTful web service. My problem is that the DB is altered (not very often, but it still changes). Also, the client does not always respect input for my application (length, type, etc.). When this happens Hibernate throws an exception. The exception is difficult to translate and read from the log, because it has nested exceptions and consists of a lot of text: like I said, very difficult to understand.
I want to know if it's possible to handle exceptions on entity level, throwing maybe a customized exception.
I thank your patience and help in advance.
EDIT:
Fianlly I managed to do what I wanted, not sure if it's done the right way.
App.java
package com.mc;
import org.hibernate.Session;
import com.mc.stock.Stock;
import com.mc.util.HibernateUtil;
import javax.persistence.EntityManager;
public class App {
public static void main(String[] args) {
Set<ConstraintViolation<Stock>> violations;
validator = Validation.buildDefaultValidatorFactory().getValidator();
Scanner scan = new Scanner(System.in);
EntityManager em = null;
System.out.println("Hibernate one to many (Annotation)");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Stock stock = new Stock();
String nextLine = scan.nextLine();
stock.setStockCode(nextLine.toString());
nextLine = scan.nextLine();
stock.setStockName(nextLine.toString());
violations = validator.validate(stock);
if (violations.size() > 0) {
StringBuilder excepcion = new StringBuilder();
for (ConstraintViolation<Stock> violation : violations) {
excepcion.append(violation.getMessageTemplate());
excepcion.append("\n");
}
System.out.println(excepcion.toString());
}
session.save(stock);
session.getTransaction().commit();
}
}
FieldMatch.java
package com.mc.constraints;
import com.mc.constraints.impl.FieldMatchValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
#Target({TYPE, ANNOTATION_TYPE})
#Retention(RUNTIME)
#Constraint(validatedBy = FieldMatchValidator.class)
#Documented
public #interface FieldMatch {
String message() default "{constraints.fieldmatch}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String first();
String second();
#Target({TYPE, ANNOTATION_TYPE})
#Retention(RUNTIME)
#Documented
#interface List {
FieldMatch[] value();
}
}
FieldMatchValidator.java
package com.mc.constraints.impl;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import com.mc.constraints.FieldMatch;
import org.apache.commons.beanutils.BeanUtils;
public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object> {
private String firstFieldName;
private String secondFieldName;
#Override
public void initialize(final FieldMatch constraintAnnotation) {
firstFieldName = constraintAnnotation.first();
secondFieldName = constraintAnnotation.second();
}
#Override
public boolean isValid(final Object value, final ConstraintValidatorContext context) {
try {
final Object firstObj = BeanUtils.getProperty(value, firstFieldName);
final Object secondObj = BeanUtils.getProperty(value, secondFieldName);
return firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
} catch (final Exception ignore) {
// ignore
}
return true;
}
}
Stock.java
package com.mc.stock;
import com.mc.constraints.FieldMatch;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
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.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.validator.constraints.Length;
#Entity
#Table(name = "STOCK")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Stock.findAll", query = "SELECT s FROM Stock s"),
#NamedQuery(name = "Stock.findByStockId", query = "SELECT s FROM Stock s WHERE s.stockId = :stockId"),
#NamedQuery(name = "Stock.findByStockCode", query = "SELECT s FROM Stock s WHERE s.stockCode = :stockCode"),
#NamedQuery(name = "Stock.findByStockName", query = "SELECT s FROM Stock s WHERE s.stockName = :stockName")})
#FieldMatch.List({
#FieldMatch(first = "stockCode", second = "stockName", message = "Code and Stock must have same value")
})
public class Stock implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_stock_id")
#SequenceGenerator(name = "seq_stock_id", sequenceName = "seq_stock_id", initialValue = 1, allocationSize = 1)
#Basic(optional = false)
#Column(name = "STOCK_ID", unique = true, nullable = false)
private Integer stockId;
#Column(name = "STOCK_CODE")
private String stockCode;
#Length(min = 1, max = 20, message = "{wrong stock name length}")
#Column(name = "STOCK_NAME")
private String stockName;
public Stock() {
}
public Stock(Integer stockId) {
this.stockId = stockId;
}
public Integer getStockId() {
return stockId;
}
public void setStockId(Integer stockId) {
this.stockId = stockId;
}
public String getStockCode() {
return stockCode;
}
public void setStockCode(String stockCode) {
this.stockCode = stockCode;
}
public String getStockName() {
return stockName;
}
public void setStockName(String stockName) {
this.stockName = stockName;
}
#Override
public int hashCode() {
int hash = 0;
hash += (stockId != null ? stockId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Stock)) {
return false;
}
Stock other = (Stock) object;
if ((this.stockId == null && other.stockId != null) || (this.stockId != null && !this.stockId.equals(other.stockId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.mc.stock.Stock[ stockId=" + stockId + " ]";
}
}
HibernateUtil.java
package com.mc.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
Oracle DB Structure
CREATE TABLE stock
(
STOCK_ID NUMBER(5) NOT NULL ,
STOCK_CODE VARCHAR2(10) NULL ,
STOCK_NAME VARCHAR2(20) NULL
);
ALTER TABLE stock
add CONSTRAINT PK_STOCK_ID PRIMARY KEY (STOCK_ID);
create sequence seq_stock_id
start with 1
increment by 1
nomaxvalue;
I'm inclined to do as much validation before you get the the DB level. Have a look at Hibernate Validator, http://www.hibernate.org/subprojects/validator.html which is the reference implementation of JSR-303.
Using standard annotations you can enforce constraints and get good error messages before you attempt to put the entities into your database.
I believe this will allow you to validate at the entity level as requested.
I am not sure what you mean about "entity level", but sure. Put a try/catch around the code that is invoking Hibernate. Catch Throwable and rethrow whatever you want. The trick is putting some reason that makes sense in the exception you are throwing.
Of course, one major point is that you should validate all input.
You can implement your own SQLExceptionConverter and handle it the way you want.
Use the property 'hibernate.jdbc.sql_exception_converter' to set your custom converter.
I am unable to find more documentation this, you need to dig into implementations by Hibernate to find more.
By the way, why can't you have a global filter, which catches every exception and decide which exception to re throw as it is or throw a new exception? You will be doing more or less same even if you implement your own SQLExceptionConverter.
according to my experience, you should catch the SQLException, and then u can get easily the SQL error code for specific database.
Eg: your database is mysql and u got error code 1062 . So you can know that error is Duplicated entry error. You can check the mysql error code
http://www.briandunning.com/error-codes/?source=MySQL
Related
I am building a SpringBoot API to learn the framework and I am facing two curious problems which probably are linked in some way.
First problem, when I try to test my code with my own Junit test class called EmployeeControllerTest, calling the method with http request returns the following error :
jakarta.servlet.ServletException: Request processing failed: java.util.NoSuchElementException: No value present
Second problem, when I perform those tests with Postman, the request /employees returning the list of employees works perfectly but the request /employee (with or without id added to the url), the API returns nothing.
In addition to this, calling the method from inside the code (in the run class) works great, I have every result I need.
Here are the code of every part involved. First the model class :
package com.openclassrooms.api.models;
import jakarta.persistence.*;
import lombok.Data;
#Data
#Entity
#Table(name = "employees")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
private String mail;
private String password;
}
The repository class :
package com.openclassrooms.api.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.openclassrooms.api.models.Employee;
#Repository
public interface EmployeeRepository extends CrudRepository<Employee, Long> {
}
The service class :
package com.openclassrooms.api.service;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.openclassrooms.api.models.Employee;
import com.openclassrooms.api.repository.EmployeeRepository;
#Service
public class EmployeeService {
#Autowired
private EmployeeRepository employeeRepository;
public Optional<Employee> getEmployee(final Long id) {
System.out.println("getEmployee ok");
return employeeRepository.findById(id);
}
public Iterable<Employee> getEmployees() {
System.out.println("getEmployees ok");
return employeeRepository.findAll();
}
public void deleteEmployee(final Long id) {
employeeRepository.deleteById(id);
}
public Employee saveEmployee(Employee employee) {
Employee savedEmployee = employeeRepository.save(employee);
return savedEmployee;
}
}
and the controller class :
package com.openclassrooms.api.controller;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.openclassrooms.api.models.Employee;
import com.openclassrooms.api.service.EmployeeService;
#RestController
public class EmployeeController {
#Autowired
private EmployeeService employeeService;
// Read - Get all employees
// #return - An Iterable object of Employee full filled
#GetMapping("/employees")
public Iterable<Employee> getEmployees() {
Iterable<Employee> list = employeeService.getEmployees();
System.out.println(list);
return list;
}
#GetMapping("/employee/{id}")
public Employee getEmployee(#PathVariable("id") final Long id) {
Optional<Employee> emp = employeeService.getEmployee(id);
if (emp.isEmpty()) {
Employee employe = emp.get();
System.out.println(employe.getFirstName());
return employe;
} else {
System.out.println("ABSENT");
return null;
}
}
#GetMapping("/employee")
public Employee getEmployee() {
Optional<Employee> emp = employeeService.getEmployee(1L);
if (emp.isEmpty()) {
Employee employe = emp.get();
System.out.println(employe.getFirstName());
return employe;
} else {
System.out.println("ABSENT");
return null;
}
}
}
Additionnaly, the main and test classes :
package com.openclassrooms.api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.openclassrooms.api.models.Employee;
import com.openclassrooms.api.service.EmployeeService;
#SpringBootApplication
public class ApiApplication implements CommandLineRunner {
#Autowired
private EmployeeService employeeService;
public static void main(String[] args) {
SpringApplication.run(ApiApplication.class, args);
}
public void run(String... args) throws Exception {
if (employeeService.getEmployee(1L).isPresent()) {
Employee emp1 = employeeService.getEmployee(1L).get();
System.out.println(emp1.getFirstName() + " " + emp1.getLastName());
} else {
System.out.println("Erreur, employé absent.");
}
System.out.println(employeeService.getEmployees());
}
}
package com.openclassrooms.api;
import static org.hamcrest.CoreMatchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import java.io.PrintStream;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureWebMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
//import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.ResultHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.openclassrooms.api.controller.EmployeeController;
import com.openclassrooms.api.models.Employee;
import com.openclassrooms.api.service.EmployeeService;
//#SpringBootTest
//#AutoConfigureWebMvc
#WebMvcTest(controllers = EmployeeController.class)
public class EmployeeControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private EmployeeService employeeService;
#Test
public void testGetEmployees() throws Exception {
Employee response = new Employee();
mockMvc.perform(get("/employee"))
.andExpect(status().isOk())
.andDo(print(System.out))
.andExpect(jsonPath("$.firstName").value("Laurent"));
//.andExpect(jsonPath("$[0].firstName", is("Laurent")));
}
}
Thanks in advance for any answer !
EDIT : the SQL script used when building the database :
DROP TABLE IF EXISTS employees;
CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(250) NOT NULL,
last_name VARCHAR(250) NOT NULL,
mail VARCHAR(250) NOT NULL,
password VARCHAR(250) NOT NULL
)
INSERT INTO employees (first_name, last_name, mail, password) VALUES
('Laurent', 'GINA', 'laurentgina#mail.com', 'laurent'),
('Sophie', 'FONCEK', 'sophiefoncek#mail.com', 'sophie'),
('Agathe', 'FEELING', 'agathefeeling#mail.com', 'agathe');
There seems to be a couple of issues with the code.
First, in the getEmployee method of the EmployeeController class, the if condition checks if the Optional returned by the employeeService is empty, but if it's empty, the code returns null, which is not the desired behavior. Instead, you should check if the Optional is present, and if it is, return the value, otherwise return an appropriate response indicating that the employee was not found.
#GetMapping("/employee/{id}")
public Employee getEmployee(#PathVariable("id") final Long id) {
Optional<Employee> emp = employeeService.getEmployee(id);
if (emp.isPresent()) {
Employee employe = emp.get();
System.out.println(employe.getFirstName());
return employe;
} else {
System.out.println("ABSENT");
// return an appropriate response indicating that the employee was not found
return null;
}
}
The same issue applies to the getEmployee method without a path variable.
#GetMapping("/employee")
public Employee getEmployee() {
Optional<Employee> emp = employeeService.getEmployee(1L);
if (emp.isPresent()) {
Employee employe = emp.get();
System.out.println(employe.getFirstName());
return employe;
} else {
System.out.println("ABSENT");
// return an appropriate response indicating that the employee was not found
return null;
}
}
Regarding the issue with the Junit test class, it's difficult to determine the problem without more information, such as the exact error message or a code snippet of the test class.
Overall, the code needs to be more robust in handling cases where the employee was not found, and the test class needs to be further investigated to determine the root cause of the issue.
i need to update tow columns inside my table (Job this table is joint with two other tables employees and job-history)one of them is the primary key, but i get error, if someone can help!
package com.touati.org.model;
import java.io.Serializable;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.List;
/**
* The persistent class for the jobs database table.
*
*/
#Entity
#Table(name="jobs")
#NamedQuery(name="Job.findAll", query="SELECT j FROM Job j")
public class Job implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="JOB_ID")
private String jobId;
#Column(name="JOB_TITLE")
private String jobTitle;
#Column(name="MAX_SALARY")
private BigDecimal maxSalary;
#Column(name="MIN_SALARY")
private BigDecimal minSalary;
//bi-directional many-to-one association to Employee
#OneToMany(mappedBy="job")
private List<Employee> employees;
//bi-directional many-to-one association to JobHistory
#OneToMany(mappedBy="job")
private List<JobHistory> jobHistories;
public Job() {
}
public String getJobId() {
return this.jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public String getJobTitle() {
return this.jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public BigDecimal getMaxSalary() {
return this.maxSalary;
}
public void setMaxSalary(BigDecimal maxSalary) {
this.maxSalary = maxSalary;
}
public BigDecimal getMinSalary() {
return this.minSalary;
}
public void setMinSalary(BigDecimal minSalary) {
this.minSalary = minSalary;
}
public List<Employee> getEmployees() {
return this.employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public Employee addEmployee(Employee employee) {
getEmployees().add(employee);
employee.setJob(this);
return employee;
}
public Employee removeEmployee(Employee employee) {
getEmployees().remove(employee);
employee.setJob(null);
return employee;
}
public List<JobHistory> getJobHistories() {
return this.jobHistories;
}
public void setJobHistories(List<JobHistory> jobHistories) {
this.jobHistories = jobHistories;
}
public JobHistory addJobHistory(JobHistory jobHistory) {
getJobHistories().add(jobHistory);
jobHistory.setJob(this);
return jobHistory;
}
public JobHistory removeJobHistory(JobHistory jobHistory) {
getJobHistories().remove(jobHistory);
jobHistory.setJob(null);
return jobHistory;
}
}
my controller: here when i try to look for all job in the data base it works fine, also if i try to update juste the title of the job it works fine to but in case that i try to set a new primary key for the job table it gives me error here my controller.
package com.touati.org.model;
import java.io.IOException;
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.PathVariable;
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.ResponseStatus;
#Controller // This means that this class is a Controller
#RequestMapping(path="/project") // This means URL's start with /demo (after Application path)
public class MainController {
#GetMapping(path="/job")
public #ResponseBody Iterable<Job> getAllJob() {
// This returns a JSON or XML with the users
return jobRepository.findAll();
}
#GetMapping(path="/job/{jobId}")
public #ResponseBody String getJob(#PathVariable String jobId) {
Job job = jobRepository.findOne(jobId);
try {
job.setJobTitle("manager");
job.setJobId("test1");
jobRepository.save(job);
}
catch (Exception ex) {
return "Error updating the job: " + ex.toString();
}
return "Job succesfully updated!";
}
i got this error,
Error updating the user: org.springframework.orm.jpa.JpaSystemException: identifier of an instance of com.touati.org.model.Job was altered from test to test1; nested exception is org.hibernate.HibernateException: identifier of an instance of com.touati.org.model.Job was altered from test to test1
Thank you for your help.
Altering the PK of an entity is not permitted - if you really have to do it, you should delete, and recreate it.
Reference (an older question) : JPA Hibernate - changing the primary key of an persisted object
I am trying to see how #Formula annotation works using a simple piece of code below.
I am able to print out values of description and bidAmount columns but the fields annotated with #Formula i.e. shortDescription and averageBidAmount return null.
Can anyone please help point out what is wrong with the code here?
I am using Hibernate 5.0, postgresql-9.3-1102-jdbc41 and TestNG on a Mac OSX.
import java.math.BigDecimal;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Persistence;
import javax.transaction.UserTransaction;
import org.testng.annotations.Test;
import com.my.hibernate.env.TransactionManagerTest;
public class DerivedPropertyDemo extends TransactionManagerTest {
#Test
public void storeLoadMessage() throws Exception {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("HelloWorldPU");
try {
{
UserTransaction tx = TM.getUserTransaction();
tx.begin();
EntityManager em = emf.createEntityManager();
DerivedProperty derivedProperty1 = new DerivedProperty();
derivedProperty1.description = "Description is freaking good!!!";
derivedProperty1.bidAmount = BigDecimal.valueOf(100D);
DerivedProperty derivedProperty2 = new DerivedProperty();
derivedProperty2.description = "Description is freaking bad!!!";
derivedProperty2.bidAmount = BigDecimal.valueOf(200D);
DerivedProperty derivedProperty3 = new DerivedProperty();
derivedProperty3.description = "Description is freaking neutral!!!";
derivedProperty3.bidAmount = BigDecimal.valueOf(300D);
em.persist(derivedProperty1);
em.persist(derivedProperty2);
em.persist(derivedProperty3);
tx.commit();
for (DerivedProperty dp : getDerivedProperty(em)) {
System.out.println("============================");
System.out.println(dp.description);
System.out.println(dp.bidAmount);
System.out.println(dp.getShortDescription());
System.out.println(dp.getAverageBidAmount());
System.out.println("#############################");
}
em.close();
}
} finally {
TM.rollback();
emf.close();
}
}
public List<DerivedProperty> getDerivedProperty(EntityManager em) {
List<DerivedProperty> resultList = em.createQuery("from " + DerivedProperty.class.getSimpleName()).getResultList();
return resultList;
}
}
My Entity class is:
#Entity
class DerivedProperty {
#Id
#GeneratedValue
protected Long id;
protected String description;
protected BigDecimal bidAmount;
#org.hibernate.annotations.Formula("substr(description, 1, 12)")
protected String shortDescription;
#org.hibernate.annotations.Formula("(select avg(b.bidAmount) from DerivedProperty b where b.bidAmount = 200)")
protected BigDecimal averageBidAmount;
public String getShortDescription() {
return shortDescription;
}
public BigDecimal getAverageBidAmount() {
return averageBidAmount;
}
}
EDIT
I am following the book Java Persistence with Hibernate 2nd Ed.
Thanks
Your DerivedProperty instances are returned from the persistence context (only their ids are used from the result set returned from the query). That's why formulas haven't been evaluated.
Persistence context is not cleared if you don't close the entity manager. Try adding em.clear() after you commit the first transaction to force clearing the persistence context.
I am using Java,Maven,Hibernate 3/JPA ,Eclipse to implement a PUT method for populating a Mysql db.
Here is my POJO
import static javax.persistence.GenerationType.IDENTITY;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name = "Person", catalog = "mydb", uniqueConstraints = {
#UniqueConstraint(columnNames = "Person"),})
public class Person implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String Name;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "name", unique = true, nullable = false, length = 30)
public String getName() {
return flowName;
}
public void setName(String Name) {
this.Name = Name;
}
}
Here is my annotations class.
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import com.google.gson.Gson;
import com.tracker.domain.Flow;
import com.tracker.persistence.HibernateUtil;
public class PersonService {
private Logger LOG = Logger.getLogger(TrackerService.class);
String JsonString = "{\"name\":\"John Doe\"}";
Gson gson = new Gson();
Person person = gson.fromJson(JsonString,Person.class);
#PUT
#Path("")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public void processandSaveJson(Person person) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
String Name = Person.getName();
person.setName(Name);
session.beginTransaction();
session.save(person);
session.getTransaction().commit();
}
}
Here is my Hibernate.Util.
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
Here is my SessionFactory Context Listener class
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.apache.log4j.Logger;
import org.hibernate.Session;
#WebListener
public class SessionFactoryListener implements ServletContextListener {
private Logger LOG = Logger.getLogger(SessionFactoryListener.class);
#Override
public void contextInitialized(ServletContextEvent arg0) {
if (LOG.isInfoEnabled()) {
LOG.info("\n\tInside contextInitialized()---\n");
}
Session session = HibernateUtil.getSessionFactory().openSession();
}
#Override
public void contextDestroyed(ServletContextEvent arg0) {
if (LOG.isInfoEnabled()) {
LOG.info("\n\tInside contextDestroyed()\n");
}
HibernateUtil.shutdown();
}
}
When I try to run this using Tomcat Server, i get the following error.
type Status report
message Method Not Allowed
description The specified HTTP method is not allowed for the requested resource.
I am very new to this. Kindly let me know what I am doing wrong. I trying to insert a
record into a mysql db using the above values. Kindly help me out.
Thanks,
Jack
as mentioned in the comments, you should supply your calling code along with the rest. but since you already mentioned that you're using a browser to make the request, it should be mentioned that most/no browsers support 'put' without using javadcript. what you are doing looks like a simple 'get'.
so the solution is to either use javascript in your form submission, or discard REST and have Urls that reflect the method (eg. /person/new/ and /person/{personId}
I've found a strange bug in my app. I've simplified it, and that is how it can be reproduced:
(I used DbUnit to create the tables and HSQLDB as a database, but that doesn't actually matter)
package test;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import org.dbunit.DatabaseUnitException;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.operation.DatabaseOperation;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.orm.hibernate3.HibernateTemplate;
public class DatabaseBugReproduction {
#Entity(name = "A")
#Table(name = "a")
public static class A {
private int id;
private Set <B> bs;
#Id
public int getId() {
return id;
}
#ManyToMany
#JoinTable(
name = "ab",
joinColumns = #JoinColumn(name = "a_id"),
inverseJoinColumns = #JoinColumn(name = "b_id")
)
public Set <B> getBs() {
return bs;
}
void setId(int id) {
this.id = id;
}
void setBs(Set <B> engines) {
this.bs = engines;
}
}
#Entity(name = "B")
#Table(name = "b")
public static class B {
private int id;
#Id
public int getId() {
return id;
}
void setId(int id) {
this.id = id;
}
}
private static SessionFactory getSessionFactory() throws SQLException, IOException, DatabaseUnitException {
String driverClass = "org.hsqldb.jdbc.JDBCDriver";
String jdbcUrl = "jdbc:hsqldb:mem:seoservertooltest";
String dbUsername = "test";
String dbPassword = "test";
String dbDialect = "org.hibernate.dialect.HSQLDialect";
Configuration config = new Configuration()//
.setProperty("hibernate.connection.driver_class", driverClass)//
.setProperty("hibernate.connection.url", jdbcUrl)//
.setProperty("hibernate.connection.username", dbUsername)//
.setProperty("hibernate.connection.password", dbPassword)//
.setProperty("hibernate.dialect", dbDialect)//
.setProperty("hibernate.hbm2ddl.auto", "create-drop")//
.setProperty("hibernate.current_session_context_class", "thread")//
.setProperty("hibernate.cache.use_query_cache", "true")//
.setProperty("hibernate.cache.use_second_level_cache", "true")//
.setProperty("hibernate.cache.region.factory_class", "net.sf.ehcache.hibernate.EhCacheRegionFactory")//
.setProperty("hibernate.cache.region_prefix", "")//
// .setProperty("hibernate.show_sql", "true")//
// .setProperty("hibernate.format_sql", "true")//
.addAnnotatedClass(A.class) //
.addAnnotatedClass(B.class) //
;
SessionFactory result = config.buildSessionFactory();
try (Connection con = DriverManager.getConnection(jdbcUrl, dbUsername, dbPassword)) {
con.createStatement().executeUpdate("SET DATABASE REFERENTIAL INTEGRITY FALSE;");
String xml = "<?xml version='1.0' encoding='UTF-8'?>"//
+ "<dataset>"//
+ "<a id='1'/>"//
+ "<b id='1'/>"//
+ "<ab a_id='1' b_id='1' />"//
+ "</dataset>";
final IDatabaseConnection dbCon = new DatabaseConnection(con);
try {
final FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
final IDataSet dataSet = builder.build(new StringReader(xml));
DatabaseOperation.CLEAN_INSERT.execute(dbCon, dataSet);
} finally {
dbCon.close();
}
}
return result;
}
public static void main(String[] args) throws Exception {
HibernateTemplate hibTemplate = new HibernateTemplate(getSessionFactory());
hibTemplate.setCacheQueries(true);
System.out.println(hibTemplate.find("select a.bs from A a"));
System.out.println(hibTemplate.find("select a.bs from A a"));
}
}
Output is:
[test.DatabaseBugReproduction$B#2942ce]
[null]
It looks like the cache is somehow misconfigured. Where is a mistake and how can I fix it?
Used:
JDK 1.7.0_01 both x32 and x64
Hibernate 3.6.7
Ehcache 2.5.0
Spring 3.1.0
Database: works at least with HSQLDB, H2 and MySQL
After some debugging, I've found that there seems to be a problem with the Query Cache and collection queries. The method that dissembles collections to store in the cache always returns null.
In fact, after googling it up, it turns out that this problems is due to a bug in Hibernate. See the issue description for more information.
While this problem isn't fixed (it seems like it won't) you could re-write your query so you don't need a collection query:
public static void main(String[] args) throws Exception {
HibernateTemplate hibTemplate = new HibernateTemplate(getSessionFactory());
hibTemplate.setCacheQueries(true);
//System.out.println(hibTemplate.find("select a.bs from A a"));
//System.out.println(hibTemplate.find("select a.bs from A a"));
System.out.println(hibTemplate.find("select bs from A a inner join a.bs as bs"));
System.out.println(hibTemplate.find("select bs from A a inner join a.bs as bs"));
}
I've tested it and it works fine.