春天的hibernate不会保存在myqsl数据库上

时间:2016-03-22 19:57:29

标签: java mysql database spring hibernate

我遇到了hibernate spring集成的问题。 没有任何错误,但是当hibernate必须在DB中保存它发送消息的信息

  

休眠:       插入       成           雇员           (年龄,姓名,工资)       值           (?,?,?)

我没有使用hibernate.cfg.xml fila配置,只是我的dispatcher-servlet.xml

我调试了很多次,我找不到问题...... 我在这里附上我的部分代码和控制台消息

控制台消息

  

2016年3月22日下午3:35:33 org.vacajose.controller.EmployeeController   createEmployee INFO:创建员工。数据:员工{id = 0,   name =' null',age = 0,salary = 0.0} mar 22,2016 3:35:48 PM   org.vacajose.controller.EmployeeController saveEmployee INFO:保存   员工。数据:员工{id = 0,姓名=' jose',年龄= 12,薪水= 123.0}   休眠:       插入       成           雇员           (年龄,姓名,工资)       值           (?,?,?)mar 22,2016 3:35:48 PM org.vacajose.controller.EmployeeController getAllEmployees INFO:   获得所有员工。休眠:       选择           employee0_.id为id1_0_,           employee0_.age为age2_0_,           employee0_.name为name3_0_,           employee0_.salary as salary4_0_           员工employee0 _

如你所见,它从表单中读取信息,但是当它必须进行插入查询时数据不存在...请不要知道这是什么问题。

MVC-调度-servlet.xml中

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!-- Specifying base package of the Components like Controller, Service,
DAO -->
<context:component-scan
base-package="org.vacajose" />

<!-- Getting Database properties -->
<context:property-placeholder location="classpath:application.properties" />

<mvc:annotation-driven />

<!-- Specifying the Resource location to load JS, CSS, Images etc -->
<mvc:resources mapping="/resources/**" location="/resources/" />

<!-- View Resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>

<!-- DataSource -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${database.driverClass}" />
<property name="jdbcUrl" value="${database.url}" />
<property name="user" value="${database.username}" />
<property name="password" value="${database.password}" />

<property name="acquireIncrement" value="${connection.acquireIncrement}" />
<property name="minPoolSize" value="${connection.minPoolSize}" />
<property name="maxPoolSize" value="${connection.maxPoolSize}" />
<property name="maxIdleTime" value="${connection.maxIdleTime}" />
</bean>

<!-- Hibernate SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.connection.autocommit">${hibernate.connection.autocommit}</prop>

</props>
</property>
<property name="packagesToScan" value="org.vacajose.entity"></property>
</bean>

<!-- Transaction -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />
</beans>

EmployeeControler.java

package org.vacajose.controller;

import java.util.List;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.vacajose.entity.Employee;
import org.vacajose.service.EmployeeService;

/**
 * @author Jose Luis
 * @version 1.0
 */
@Controller
public class EmployeeController {

    private static final Logger logger = Logger.getLogger(EmployeeController.class);

    public EmployeeController() {
        System.out.println("EmployeeController()");
    }

    @Autowired
    private EmployeeService employeeService;

    @RequestMapping("createEmployee")
    public ModelAndView createEmployee(@ModelAttribute Employee employee) {
        logger.info("Creating Employee. Data: " + employee);
        return new ModelAndView("employeeForm", "employee", employee);
    }

    @RequestMapping("editEmployee")
    public ModelAndView editEmployee(@RequestParam long id, @ModelAttribute Employee employee) {
        logger.info("Updating the Employee for the Id " + id);
        employee = employeeService.getEmployee(id);
        return new ModelAndView("employeeForm", "employeeObject", employee);
    }

    @RequestMapping("saveEmployee")
    public ModelAndView saveEmployee(@ModelAttribute Employee employee) {
        logger.info("Saving the Employee. Data : " + employee);
        if (employee.getId() == 0) { // if employee id is 0 then creating the
                                        // employee other updating the employee
            employeeService.createEmployee(employee);
        } else {
            employeeService.updateEmployee(employee);
        }
        return new ModelAndView("redirect:getAllEmployees");
    }

    @RequestMapping("deleteEmployee")
    public ModelAndView deleteEmployee(@RequestParam long id) {
        logger.info("Deleting the Employee. Id : " + id);
        employeeService.deleteEmployee(id);
        return new ModelAndView("redirect:getAllEmployees");
    }

    @RequestMapping("getAllEmployees")
    public ModelAndView getAllEmployees() {
        logger.info("Getting the all Employees.");
        List<Employee> employeeList = employeeService.getAllEmployees();
        return new ModelAndView("employeeList", "employeeList", employeeList);
    }

    @RequestMapping("searchEmployee")
    public ModelAndView searchEmployee(@RequestParam("searchName") String searchName) {
        logger.info("Searching the Employee. Employee Names: " + searchName);
        List<Employee> employeeList = employeeService.getAllEmployees(searchName);
        return new ModelAndView("employeeList", "employeeList", employeeList);
    }
}

EmployeeDAOImpl.java

package org.vacajose.dao;

import org.vacajose.dao.EmployeeDAO;
import org.vacajose.entity.Employee;
import org.vacajose.util.HibernateUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Jose Luis    
 * @version 1.0
 */

@Repository
public class EmployeeDAOImpl implements EmployeeDAO {

    public EmployeeDAOImpl() {
        System.out.println("EmployeeDAOImpl");
    }

    @Autowired
    private HibernateUtil hibernateUtil;

    @Override
    public long createEmployee(Employee employee) {
        return (Long) hibernateUtil.create(employee);
    }

    @Override
    public Employee updateEmployee(Employee employee) {
        return hibernateUtil.update(employee);
    }

    @Override
    public void deleteEmployee(long id) {
        Employee employee = new Employee();
        employee.setId(id);
        hibernateUtil.delete(employee);
    }

    @Override
    public List<Employee> getAllEmployees() {
        return hibernateUtil.fetchAll(Employee.class);
    }

    @Override
    public Employee getEmployee(long id) {
        return hibernateUtil.fetchById(id, Employee.class);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Employee> getAllEmployees(String employeeName) {
        String query = "SELECT e.* FROM Employees e WHERE e.name like '%" + employeeName + "%'";
        List<Object[]> employeeObjects = hibernateUtil.fetchAll(query);
        List<Employee> employees = new ArrayList<Employee>();
        for (Object[] employeeObject : employeeObjects) {
            Employee employee = new Employee();
            long id = ((BigInteger) employeeObject[0]).longValue();
            int age = (int) employeeObject[1];
            String name = (String) employeeObject[2];
            float salary = (float) employeeObject[3];
            employee.setId(id);
            employee.setName(name);
            employee.setAge(age);
            employee.setSalary(salary);
            employees.add(employee);
        }
        System.out.println(employees);
        return employees;
    }
} 

hibernateutil.java

package org.vacajose.util;

import java.io.Serializable;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * @author Jose Vaca
 * @version 1.0
 */
@Repository
public class HibernateUtil {

    @Autowired
    private SessionFactory sessionFactory;

    public <T> Serializable create(final T entity) {
        return sessionFactory.getCurrentSession().save(entity);
    }

    public <T> T update(final T entity) {
        sessionFactory.getCurrentSession().update(entity);
        return entity;
    }

    public <T> void delete(final T entity) {
        sessionFactory.getCurrentSession().delete(entity);
    }

    public <T> void delete(Serializable id, Class<T> entityClass) {
        T entity = fetchById(id, entityClass);
        delete(entity);
    }

    @SuppressWarnings("unchecked")
    public <T> List<T> fetchAll(Class<T> entityClass) {
        return sessionFactory.getCurrentSession().createQuery(" FROM " + entityClass.getName()).list();
    }

    @SuppressWarnings("rawtypes")
    public <T> List fetchAll(String query) {
        return sessionFactory.getCurrentSession().createSQLQuery(query).list();
    }

    @SuppressWarnings("unchecked")
    public <T> T fetchById(Serializable id, Class<T> entityClass) {
        return (T) sessionFactory.getCurrentSession().get(entityClass, id);
    }
}

如果您需要一些信息,请告诉我......

1 个答案:

答案 0 :(得分:0)

看起来事务未被提交,将@Transactional添加到每个控制器方法。