gpt4 book ai didi

Java Spring 初始化一次 hibernate 存储库

转载 作者:行者123 更新时间:2023-11-30 06:16:41 25 4
gpt4 key购买 nike

我关注了官方spring tutorial我声明我的对象如下:

存储库:

@Repository
public interface PropertyRepository extends CrudRepository<Property, Long> {
}

属性对象:

@Entity
@Table(catalog = "configdb", name = "properties", uniqueConstraints = {@UniqueConstraint(columnNames = {"property_id"})})
public class Property implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "property_id")
private Long propertyId;
@Column(name = "property_key", length = 50)
private String propertyKey;

应用:

@SpringBootApplication
@ComponentScan({"org.demo*"})

@EnableAutoConfiguration
public class Application {

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

}

还有一个非常短的 Controller :

@Controller
@RequestMapping(path = "/demo")
public class PropertyController {
@Autowired
private PropertyDao propDao;
public PropertyController(PropertyRepository repo) {
propDao = PropertyDao.setRepository(repo);
}
@GetMapping(path = "/map")
public @ResponseBody
HashMap<String,String> get() {
return propDao.getPropertiesMap();
}

PropertyDao 在构造函数中设置其 Repository,然后将 Property 转换为 HashMap。

我从日志中看到,每次在 Controller 上执行请求时,都会调用 Hibernate 并执行对 mysql 的查询,就像在每次请求时创建 PropertyController 一样。

但是这个 Property 对象仅包含缩写配置,并且在每个请求时调用数据库是一个巨大的开销。

你有什么解决办法吗?

编辑:添加PropertyDao

@Component
public class PropertyDao {
public PropertyDao setRepository(PropertyRepository repository) {...}
public HashMap<String, String> getPropertiesMap(){...}
}

最佳答案

创建一个服务(服务是单例的,它们仅创建一次)并将逻辑移至那里。然后从 Controller 调用服务方法。

类似这样的事情:

@Service
@Transactional
public class MyService {

@Autowired
private PropertyDao propDao;

public MyService(PropertyRepository repo) {
propDao = PropertyDao.setRepository(repo);
}


HashMap<String,String> getPropertiesMap() {
return propDao.getPropertiesMap();
}
}

在你的 Controller 中:

@Controller
@RequestMapping(path = "/demo")
public class PropertyController {
@Autowired
private MyService myService;

public PropertyController(MyService myService) {
this.myService = myService;
}

@GetMapping(path = "/map")
public @ResponseBody
HashMap<String,String> get() {
return myService.getPropertiesMap();
}
}

关于Java Spring 初始化一次 hibernate 存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49053165/

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