没有DAO和Service Interface的SpringMVC Hibernate JPA是最佳实践吗?

时间:2017-03-05 06:02:08

标签: java spring hibernate spring-mvc spring-data-jpa

我正在使用通用CRUD编写SpringMVC Hibernate JPA应用程序而不使用接口,就像在EJB 3.1中完成一样。 CRUD工作正常。但是,在没有DAO和服务服务接口层的情况下,我还没有看到任何关于Spring的在线教程。因此,我担心如果我是编写Spring应用程序的最佳实践。我们将不胜感激。感谢

以下是我的代码

Employee.java

package com.websystique.springmvc.model;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author Nandom
 */
@Entity
public class Employee implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Column(name = "name")
    private String name;
    @Column(name = "joining_date")
    private String joiningDate;
    @Column(name = "salary")
    private String salary;
    @Column(name = "ssn")
    private String ssn;

    public Employee() {
    }

    public Employee(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getJoiningDate() {
        return joiningDate;
    }

    public void setJoiningDate(String joiningDate) {
        this.joiningDate = joiningDate;
    }

    public String getSalary() {
        return salary;
    }

    public void setSalary(String salary) {
        this.salary = salary;
    }

    public String getSsn() {
        return ssn;
    }

    public void setSsn(String ssn) {
        this.ssn = ssn;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.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 Employee)) {
            return false;
        }
        Employee other = (Employee) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "entity.Employee[ id=" + id + " ]";
    }

}

CrudService.java

package com.websystique.springmvc.crud;

import java.util.List;
import javax.persistence.EntityManager;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Nandom
 * @param <T>
 */
public abstract class CrudService<T> {

private final Class<T> entityClass;

public CrudService(Class<T> entityClass) {
    this.entityClass = entityClass;
}

protected abstract EntityManager getEntityManager();

@Transactional
public void create(T entity) {
    getEntityManager().persist(entity);
}

@Transactional
public void edit(T entity) {
    getEntityManager().merge(entity);
}

@Transactional
public void remove(T entity) {
    getEntityManager().remove(getEntityManager().merge(entity));
}

@Transactional
public T find(Object id) {
    return getEntityManager().find(entityClass, id);
}

public List<T> findAll() {
    javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
    cq.select(cq.from(entityClass));
    return getEntityManager().createQuery(cq).getResultList();
}

public List<T> findRange(int[] range) {
    javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
    cq.select(cq.from(entityClass));
    javax.persistence.Query q = getEntityManager().createQuery(cq);
    q.setMaxResults(range[1] - range[0] + 1);
    q.setFirstResult(range[0]);
    return q.getResultList();
}

public int count() {
    javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
    javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
    cq.select(getEntityManager().getCriteriaBuilder().count(rt));
    javax.persistence.Query q = getEntityManager().createQuery(cq);
    return ((Long) q.getSingleResult()).intValue();
}

}

EmployeeService.java

package com.websystique.springmvc.crud;


import com.websystique.springmvc.model.Employee;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Nandom
 */
@Repository
public class EmployeeService extends CrudService<Employee> {

    @PersistenceContext
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public EmployeeService() {
        super(Employee.class);
    }

}

AppController.java

package com.websystique.springmvc.controller;

import com.websystique.springmvc.crud.EmployeeService;
import com.websystique.springmvc.model.Employee;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/")
public class AppController {

    @Autowired
    EmployeeService service;

    @RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET)
    public String listEmployees(ModelMap model) {

        List<Employee> employees = service.findAll();
        model.addAttribute("employees", employees);
        return "allemployees";
    }

    @RequestMapping(value = { "/new" }, method = RequestMethod.GET)
    public String newEmployee(ModelMap model) {
        Employee employee = new Employee();
        model.addAttribute("employee", employee);
        return "registration";
    }


    @RequestMapping(value = { "/new" }, method = RequestMethod.POST)
    public String saveEmployee(Employee employee, BindingResult result,
            ModelMap model) {

        if (result.hasErrors()) {
            return "registration";
        }

        service.create(employee);

        model.addAttribute("success", "Employee " + employee.getName()
                + " registered successfully");
        return "success";
    }

//  @RequestMapping(value = { "/delete-{ssn}-employee" }, method = RequestMethod.GET)
//  public String deleteEmployee(@PathVariable Integer ssn) {
//                Employee e = service.find(Integer.valueOf(ssn));
//      service.remove(e);
//      return "redirect:/list";
//  }

}

HibernateConfiguration

package com.websystique.springmvc.configuration;

import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@ComponentScan({"com.websystique.springmvc.configuration"})
//@PropertySource(value = {"classpath:application.properties"})
public class HibernateConfiguration {


    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan(new String[]{"com.websystique.springmvc.model"});
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additonalPropertes());
        return em;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/springemployeejpahibernate");
        dataSource.setUsername("root");
        dataSource.setPassword("nandom");
        return dataSource;
    }

    @Bean
    public PlatformTransactionManager transactonManager(EntityManagerFactory emf) {
        JpaTransactionManager transactonManager = new JpaTransactionManager();
        transactonManager.setEntityManagerFactory(emf);
        return transactonManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptonTranslaton() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    Properties additonalPropertes() {
        Properties propertes = new Properties();
        Properties properties = new Properties();
        properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        properties.put("hibernate.show_sql", "true");
        properties.put("hibernate.format_sql", "true");
        properties.put("hibernate.hbm2ddl.auto", "update");
        return propertes;
    }
}

1 个答案:

答案 0 :(得分:0)

最好继续使用Spring-data-JPA,而不是编写代码库中的样板代码。

Spring-data-JPA提供了所有必需的功能。