I am learning Spring mvc with Hibernate. I have tried a tutorial where it shows with reverse engineering and hbm.xml. But I want to use annotated domain class for it. For which I am trying some but no luck.
I have taken a web project in Netbeans with Spring and Hibernate framework. When I submit the form it work fine and redirect to other page but data is not saved. How can I resolve this? Here are my attempts below.
My project structure:
My dispatcher-servlet.xml:
My application context:
My web.xml:
contextConfigLocation
/WEB-INF/applicationContext.xml
org.springframework.web.context.ContextLoaderListener
dispatcher
org.springframework.web.servlet.DispatcherServlet
2
dispatcher
*.html
30
redirect.jsp
My hibernate.cfg.xml:
org.hibernate.dialect.MySQLDialect
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/springhibernate?zeroDateTimeBehavior=convertToNull
root
50
true
org.hibernate.hql.ast.ASTQueryTranslatorFactory
My User controller:
@Controller
public class UserController {
private static SessionFactory factory;
@RequestMapping(value="/getForm", method = RequestMethod.GET)
public ModelAndView getDemoForm(){
ModelAndView model = new ModelAndView("demoForm");
return model;
}
@RequestMapping(value = "/submitDemoForm.html", method = RequestMethod.POST)
public ModelAndView submitAdmissionForm(@ModelAttribute("employee") EmployeeAnnotation employee) {
try {
factory = new AnnotationConfiguration().
configure().
//addPackage("com.xyz") //add package if used.
addAnnotatedClass(EmployeeAnnotation.class).
buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try {
tx = session.beginTransaction();
employeeID = (Integer) session.save(employee);
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
ModelAndView model = new ModelAndView("demoFormSuccess");
return model;
}
}
My EmployeeAnnotation Class (pojo):
import javax.persistence.*;
@Entity
@Table(name = "employee_annotation")
public class EmployeeAnnotation {
@Id @GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "salary")
private int salary;
public EmployeeAnnotation() {}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
}
My demoForm.jsp:
My demoFormSuccess.jsp:
ID is :: ${employee.id}
