我遵循了官方的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
@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在构造函数中设置其存储库,然后将Property转换为HashMap。
从日志中可以看到,每次我在控制器上执行请求时,都会调用Hibernate并执行对mysql的查询,就像是否在每个请求中都创建了PropertyController一样。
但是,此Property对象仅包含初始配置,并且在每次请求时调用db都是巨大的开销。
你有什么解决办法吗?
编辑:添加了PropertyDao
@Component
public class PropertyDao {
public PropertyDao setRepository(PropertyRepository repository) {...}
public HashMap<String, String> getPropertiesMap(){...}
}
最佳答案
创建一个服务(服务是单例的,它们仅创建一次)并在其中移动逻辑。然后从控制器调用服务方法。
像这样:
@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
@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 - Java Spring一次初始化 hibernate 库,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49053165/