- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试创建一个抽象的 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/
我有组件需要更新客户和客户地址的数据库(通过 JDBC)。从 CustomerDAO 调用 CustomerAddressDAO 是否合适?或者创建一个单独的“CustomerDataManager”
任何人都可以解释MS Access 2007中DAO.Recordset,DAO.Recordsets和DAO.Recordset2之间的区别吗?基本上使用记录集。...举一个例子,使它更清晰。我从“
所以我正在编写一个个人项目来学习 Web 编程,并且我遇到了 DAO 模式。我构建了一些类(模型),并且像几乎所有程序一样,它们是嵌套的(例如:类 Payment 具有对 Author 实例的引用)。
我有一个基本问题。 我一直在创建关注点分离的 DAO。每个 DAO 都专注于上下文中的 BusinessObject。我的问题是如何在另一个 DAO 中使用一个 DAO 方法。我认为这是错误的,但没有
有没有办法使用 Android Room Persistence Library 将 DAO 作为依赖项添加到其他 DAO 中,也许是使用 Dagger2?我试图避免在使用事务对多个表执行操作的 DA
通常,我会尝试以一种完全依赖于自身的方式来构建我的 DAO 类。它们可以与多个表交互,但前提是数据与基础对象相关。例如,假设我有一个约会对象,约会 DAO 从约会表中提取数据。如果约会表是一个服务 i
在学校学习过 Java 后,我对 DAO 模式( Data access object )非常熟悉。然而在工作中我使用.NET。在 .NET 中,经常讨论 DAL( Data Access Layer
我一直在尝试按照以下步骤创建一个通用的 DAO: http://www.ibm.com/developerworks/java/library/j-genericdao/index.html 不过,我
Java EE 中的最佳实践是什么? 在服务(或管理器)类中创建 DAO 类的实例 SalesDAO salesDao = new SalesDAOImpl(); salesDao.findCusto
这有道理吗? 假设我需要从 DB 中获取一个对象,该对象与另一个对象有关系(由 DB 中的外键表示,并由我的域对象中的组合表示)。如果在我的第一个 DAO 中,我为对象 1 获取数据,然后为对象 2
我目前正在为应用程序创建数据访问层。此应用程序最初将连接到 Oracle 数据库,但稍后也会连接到 DB2 数据库。 为了连接到数据库,我将使用 JDBC。在这个时候我正在考虑我的选择。在我看来,我有
我正在 JSF 中设计一些数据“块” 我从每个块的 Java bean 中获取我的数据。 我的问题是我的块从多个表中获取数据。 例如: 描述 的块客户的个人资料 由组成: 客户名称(在表 客户 中)
将 DAO 类与应用程序代码中实际实例化的 DAO 类分开有什么好处,即为什么不在这样的场景中直接实例化 DAO 类: Class CreateIocContainer{ p s v main
我正在为我的 DataNucleus JDO DAO 创建通用 DAO。通用 DAO 将执行获取、更新、删除、创建操作和一些其他通用操作,因此这些实现可以在更具体的 DAO 中进行扩展。 是否有可能以
这可能是一件非常微不足道的事情,但我是一些面向对象模式的新手。 简而言之,在另一个 DAO 中使用一个 DAO 中的方法是一种不好的做法吗?我试图在 DAO 中创建一个实体,但发现仅使用该 DAO 很
我参与了一个 Java 项目,该项目从不同的支付代理获取支付信息,对其进行处理并将其存储到我们的计费系统(数据库)中。 由于我们有不同的代理,因此支付协议(protocol)也不同,因此我们有时有相似
考虑以下 Room DAO @Dao public abstract class JobDao { @Insert public abstract long insert( Job v
我有一个“容器”类,其字段包含在多个数据库表中,我使用 DAO 模式来访问数据。 问题是,我应该为这个“容器”类创建一个 DAO,还是每个表有一个 DAO 并合并它们的数据更好? 最佳答案 您应该根据
我们正在通过 @Service 和 @Component 注释使用 Spring @Autowired 改造一个新的面向服务的架构。 我一直在和我的同事争论不让每个 DAO 都有接口(interfac
我有通用的 DAO: @NoRepositoryBean interface ICrudDao extends Repository { void delete(T deleted);
我是一名优秀的程序员,十分优秀!