gpt4 book ai didi

java - DAO 和 Spring Autowired

转载 作者:行者123 更新时间:2023-12-01 06:05:29 26 4
gpt4 key购买 nike

我尝试创建一个抽象的 Dao。我使用 Spring + Hibernate。这是我的代码。
具有配置的主类:

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

}

休息 Controller

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 变量中有 null。当我调试代码时,我发现了一件有趣的事情:在服务层方法 deviceDao.getClazz() 中返回了所需的 clazz (不为空)。但在方法 AbstractDao.findAll() 中,我的 clazz 变量中有 null 。为什么?请帮忙。
抱歉我的英语和表述。我是这个网站的新人,Spring 和英语

最佳答案

你把事情搞得太复杂了。因为您使用的是 Spring Boot,所以可以只创建扩展 CrudRepository 的通用接口(interface)并添加您需要的但尚未存在于其中的方法。

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

关于java - DAO 和 Spring Autowired,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45759521/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com