2017-08-18 53 views
1

我試圖創建一個抽象道。我使用Spring + Hibernate。 這是我的代碼。
Main類與配置:DAO和Spring自動裝配Autowired

package ru.makaek.growbox.api; 

import org.hibernate.SessionFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.ComponentScan; 
import org.springframework.core.env.Environment; 
import org.springframework.jdbc.datasource.DriverManagerDataSource; 
import org.springframework.orm.hibernate5.HibernateTransactionManager; 
import org.springframework.orm.hibernate5.LocalSessionFactoryBean; 
import org.springframework.transaction.annotation.EnableTransactionManagement; 

import javax.sql.DataSource; 

@ComponentScan(value = "ru.makaek.growbox") 
@EnableAutoConfiguration(exclude = HibernateJpaAutoConfiguration.class) 
@EnableTransactionManagement 
@SpringBootApplication 
public class Application { 

    @Autowired 
    private Environment env; 

    public static void main(String[] args) { 
     SpringApplication.run(Application.class, args); 
    } 


    @Bean 
    public DataSource getDataSource() { 
     DriverManagerDataSource dataSource = new DriverManagerDataSource(); 
     dataSource.setDriverClassName(env.getRequiredProperty("datasource.driver")); 
     dataSource.setUrl(env.getRequiredProperty("datasource.url")); 
     dataSource.setUsername(env.getRequiredProperty("datasource.username")); 
     dataSource.setPassword(env.getRequiredProperty("datasource.password")); 
     return dataSource; 
    } 

    @Bean 
    public LocalSessionFactoryBean getSessionFactory() { 
     LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); 
     sessionFactory.setDataSource(getDataSource()); 
     sessionFactory.setPackagesToScan(new String[]{"ru.makaek.growbox"}); 
     return sessionFactory; 
    } 

    @Bean 
    public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) { 
     HibernateTransactionManager txManager = new HibernateTransactionManager(); 
     txManager.setSessionFactory(sessionFactory); 
     return txManager; 
    } 

} 

休息控制器

package ru.makaek.growbox.api.controller; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.web.bind.annotation.*; 
import ru.makaek.growbox.api.model.data.entities.Device; 
import ru.makaek.growbox.api.service.IStructureService; 

@RestController 
public class DeviceController extends AbstractController { 

    @Autowired 
    IStructureService structureService; 

    @RequestMapping(value = "/devices", method = RequestMethod.POST) 
    public Answer addDevice(@RequestBody Device device) { 
     structureService.addDevice(device); 
     return ok("Device has been added"); 
    } 

    @RequestMapping(value = "/devices", method = RequestMethod.GET) 
    public Answer getDevices() { 
     return ok(structureService.getDevices()); 
    } 

    @RequestMapping(value = "/devices/{deviceId}", method = RequestMethod.GET) 
    public Answer getDevice(@PathVariable Long deviceId) { 
     return ok(structureService.getDevice(deviceId)); 
    } 

} 

服務層。接口

package ru.makaek.growbox.api.service; 

import ru.makaek.growbox.api.model.data.entities.Device; 

import java.util.List; 

public interface IStructureService { 

    void addDevice(Device device); 

    List<Device> getDevices(); 

    Device getDevice(Long deviceId); 
} 

服務層。實施

package ru.makaek.growbox.api.service; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Service; 
import org.springframework.transaction.annotation.Transactional; 
import ru.makaek.growbox.api.model.data.dao.base.IDao; 
import ru.makaek.growbox.api.model.data.entities.Device; 

import java.util.List; 

@Service 
@Transactional 
public class StructureService implements IStructureService { 

    IDao<Device> deviceDao; 

    @Autowired 
    public void setDao(IDao<Device> dao) { 
     deviceDao = dao; 
     dao.setClazz(Device.class); 
    } 

    @Override 
    public void addDevice(Device device) { 
     deviceDao.create(device); 
    } 

    @Override 
    public List<Device> getDevices() { 
     return deviceDao.findAll(); 
    } 

    @Override 
    public Device getDevice(Long deviceId) { 
     return deviceDao.findOne(deviceId); 
    } 
} 

實體

package ru.makaek.growbox.api.model.data.entities; 

import lombok.Data; 

import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.GenerationType; 
import javax.persistence.Id; 

@Entity(name = "devices") 
@Data public class Device extends BaseEntity { 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Long id; 
    private String name; 
} 

DAO。接口

package ru.makaek.growbox.api.model.data.dao.base; 

import ru.makaek.growbox.api.model.data.entities.BaseEntity; 

import java.util.List; 

public interface IDao<T extends BaseEntity> { 

    T findOne(final long id); 

    void setClazz(Class<T> clazz); 

    List<T> findAll(); 

    void create(final T entity); 

    T update(final T entity); 

    void delete(final T entity); 

    void deleteById(final long entityId); 

} 

摘要DAO

package ru.makaek.growbox.api.model.data.dao.base; 

import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import ru.makaek.growbox.api.model.data.entities.BaseEntity; 
import ru.makaek.growbox.api.util.GBException; 

import java.util.List; 

public abstract class AbstractDao<T extends BaseEntity> implements IDao<T> { 

    private Class<T> clazz; 

    @Autowired 
    private SessionFactory sessionFactory; 

    public final void setClazz(Class<T> clazz) { 
     this.clazz = clazz; 
    } 

    public T findOne(long id) { 
     try { 
      return (T) getCurrentSession().get(clazz, id); 
     } catch (Exception e) { 
      throw new GBException.InternalError(e.getMessage()); 
     } 
    } 

    public List<T> findAll() { 
     try { 
      return getCurrentSession().createQuery("from " + clazz.getName()).list(); 
     } catch (Exception e) { 
      throw new GBException.InternalError(e.getMessage()); 
     } 
    } 

    public void create(T entity) { 
     try { 
      getCurrentSession().persist(entity); 
     } catch (Exception e) { 
      throw new GBException.InternalError(e.getMessage()); 
     } 
    } 

    public T update(T entity) { 
     try { 
      return (T) getCurrentSession().merge(entity); 
     } catch (Exception e) { 
      throw new GBException.InternalError(e.getMessage()); 
     } 
    } 

    public void delete(T entity) { 
     try { 
      getCurrentSession().delete(entity); 
     } catch (Exception e) { 
      throw new GBException.InternalError(e.getMessage()); 
     } 
    } 

    public void deleteById(long entityId) { 
     try { 
      T entity = findOne(entityId); 
      delete(entity); 
     } catch (Exception e) { 
      throw new GBException.InternalError(e.getMessage()); 
     } 
    } 

    protected final Session getCurrentSession() { 
     return sessionFactory.getCurrentSession(); 
    } 


} 

DAO。執行

package ru.makaek.growbox.api.model.data.dao; 

import org.springframework.stereotype.Repository; 
import ru.makaek.growbox.api.model.data.dao.base.AbstractDao; 
import ru.makaek.growbox.api.model.data.entities.Device; 

@Repository 
public class DeviceDao extends AbstractDao<Device> { 
} 

我有一個麻煩。當我打電話GET http://host:port/devices API方法我有AbstractDao.findAll()方法clazz中變量。當我調試,我發現一個有趣的事情代碼:在服務層的方法deviceDao.getClazz()返回的需要clazz中(NOT NULL)。但在方法AbstractDao.findAll()我有null in clazz變量。爲什麼?請幫忙。
對不起,我的英語和配方。我在這個新的網站,Spring和英語

回答

-1

你過於複雜的事情。因爲你使用Spring的引導,可以只創建一個擴展CrudRepository通用接口,並添加你需要的,是不是已經存在於那裏的方法。

看看這裏https://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html

+0

我想使用Hibernate。我是否正確理解sollution將使用spring-data而不是Hibernate? –

+0

Hibernate是一個JPA實現,而Spring數據JPA是JPA數據訪問抽象。 Spring Data爲GenericDao自定義實現提供了一個解決方案。它也可以通過方法名稱約定代表您生成JPA查詢。使用Spring Data,您可以使用Hibernate,Eclipse Link或任何其他JPA提供程序。 – toucheqt

+0

謝謝。您能否給我建議一些關於JPA的好書或文章? –

相關問題