2017-03-05 22 views
0

我正在編寫SpringMVC Hibernate JPA應用程序,使用通用CRUD而不使用接口,就像在EJB 3.1中完成一樣。 CRUD工作正常。不過,我還沒有看到任何關於Spring的在線教程沒有DAO和服務服務接口層。因此,如果我內嵌編寫Spring應用程序的最佳實踐,我很擔心。您的幫助將不勝感激。由於沒有DAO和Service Interface層的SpringMVC Hibernate JPA是最佳實踐嗎?

下面是我的代碼

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; 
    } 
} 

回答

0

更好地與彈簧數據的JPA而不是代碼庫中的編碼鍋爐板代碼繼續前進。

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

+0

非常感謝,我一直在等待這樣的技術,減少了很多時間浪費寫作CRUD DAO。我將在我的工作中實現Spring-data-JPA並回饋給您。再次感謝 –