返回介绍

4.7.2 Repository填充

发布于 2020-08-26 12:31:30 字数 4418 浏览 1070 评论 0 收藏 0

如果使用过Spring提供的JDBC模块,可能会对使用SQL脚本填充DataSource。Spring Data中也提供了相似的功能来填充repository,只不过不是使用SQL,而是使用XML或JSON来定义数据,

假设有一个data.json文件,内容如下:

Example 29. Data defined in JSON(使用JSON定义数据)

[ { "_class" : "com.acme.Person",
 "firstname" : "Dave",
  "lastname" : "Matthews" },
  { "_class" : "com.acme.Person",
 "firstname" : "Carter",
  "lastname" : "Beauford" } ]

为了把前面定义的数据填充到PersonRepository中可以使用repository命名空间提供的popilator元素。 Example 30. Declaring a Jackson repository populator(声明Jackson repository populator)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:repository="http://www.springframework.org/schema/data/repository"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/data/repository
    http://www.springframework.org/schema/data/repository/spring-repository.xsd">

  <repository:jackson2-populator locations="classpath:data.json" />

</beans>

上面的配置会让data.json文件可以在其他地方通过Jackson的Object Mapper读取和反序列化。

JSON object的类型可以通过解析json文件中的_class属性得到。Spring框架会根据反序列化的对象选择合适的repository来处理。

如果想要用XML来定义repositries填充的数据,需要使用unmarshaller-populator元素,可以利用Spring OXM提供的组件,想要详细了解请参考Spring参考文档:

Example 31. Declaring an unmarshalling repository populator (using JAXB)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:repository="http://www.springframework.org/schema/data/repository"
  xmlns:oxm="http://www.springframework.org/schema/oxm"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/data/repository
    http://www.springframework.org/schema/data/repository/spring-repository.xsd
    http://www.springframework.org/schema/oxm
    http://www.springframework.org/schema/oxm/spring-oxm.xsd">

  <repository:unmarshaller-populator locations="classpath:data.json"
    unmarshaller-ref="unmarshaller" />

  <oxm:jaxb2-marshaller contextPath="com.acme" />

</beans>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文