首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >DAO与弹簧

DAO与弹簧
EN

Stack Overflow用户
提问于 2017-08-18 14:50:13
回答 1查看 1.2K关注 0票数 1

我试着创造一个抽象的刀。我使用Spring + Hibernate。这是我的密码。

配置的主类:

代码语言:javascript
复制
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;
    }

}

休息控制器

代码语言:javascript
复制
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));
    }

}

服务层接口

代码语言:javascript
复制
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);
}

服务层实现

代码语言:javascript
复制
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);
    }
}

实体

代码语言:javascript
复制
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;
}

刀子。接口

代码语言:javascript
复制
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);

}

抽象道

代码语言:javascript
复制
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();
    }


}

刀子。实现

代码语言:javascript
复制
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变量中有null。在调试代码时,我发现了一件有趣的事情:在服务层方法中,deviceDao.getClazz()返回所需的clazz ( null)。但是在方法AbstractDao.findAll()中,clazz变量中有null。为什么?请帮帮忙。

抱歉,我的英语和配方。我是这个网站的新手,春天和英语

EN

回答 1

Stack Overflow用户

发布于 2017-08-18 15:54:20

你让事情变得太复杂了。因为您正在使用Spring,所以只需创建扩展CrudRepository并添加所需方法的泛型接口就可以了。

看看这里,https://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45759521

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档