2017-03-05 8 views
0

私はSpringMVC Hibernate JPAアプリケーションを、EJB 3.1で行われているのとまったく同じようにInterfaceを使わずに汎用CRUDを使ってコーディングしています。 CRUDは正常に動作します。しかし、私はDAOとサービスのサービスインターフェイスレイヤーなしでSpringのオンラインチュートリアルを見たことはありません。したがって、私がSpringアプリケーションを作成するためのベストプラクティスに沿っているのであれば、私は心配しています。あなたの助けに感謝します。以下のおかげSpringMVC DAOとサービスインターフェイスレイヤーを持たない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

私のコードです

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を私の仕事に導入し、あなたにお返しします。もう一度ありがとう –

関連する問題