@Component
@Entity
@Table(name="menu")
@Configurable
public class Menu implements Serializable{
....
@OneToMany(mappedBy="menu", fetch=FetchType.EAGER)
private Set<VoceMenu> voceMenuList;
public Set<VoceMenu> getVoceMenuList() {
return voceMenuList;
}
public void setVoceMenuList(Set<VoceMenu> voceMenuList) {
this.voceMenuList = voceMenuList;
}
.....
}
Run Code Online (Sandbox Code Playgroud)
我打印一个表单来编辑菜单,以及它的相对VoceMenu对象,这样:
<form:form action="editMenu" method="post" commandName="menu">
Menu id<form:input path="id" maxlength="11"/><br/>
......
<c:forEach items="${menu.voceMenuList}" varStatus="counter">
<form:input path="voceMenuList[${counter.index}].id" maxlength="11"/>
.....
</c:forEach>
<input type="submit">
</form:form>
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试保存对象菜单时,我收到此错误:
bean类[com.springgestioneerrori.model.Menu]的属性'voceMenuList [0]'无效:无法从大小为0的集合获取索引为0的元素,使用属性路径'voceMenuList [0]'访问
根据当前 Spring Data Rest 手册的第 12.1 节,我想使用 RepositoryEntityLinks 类在我的代码中的各个位置获取资源的链接
12.1. 编程链接 有时您需要在您自己的自定义构建的 Spring MVC 控制器中添加指向导出资源的链接。可用的链接分为三个基本级别:
...
3 使用 Spring Data REST 的 RepositoryEntityLinks 实现。
http://docs.spring.io/spring-data/rest/docs/current/reference/html/#_programmatic_links
我注意到文档明确提到“...你自己定制的 Spring MVC 控制器”,而且它似乎是唯一可用的地方。我想在 Spring Security AuthenticationSuccessHandler 中使用配置的实例,但是应用程序无法启动并显示错误:
找不到 [org.springframework.data.rest.webmvc.support.RepositoryEntityLinks] 类型的合格 bean
我已经能够按预期成功地将它注入到控制器中。
我可以在 Spring MVC 控制器之外使用 RepositoryEntityLinks 类吗?
public class RestAuthenticationSuccessHandler implements AuthenticationSuccessHandler
{
@Autowired
private RepositoryEntityLinks entityLinks;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException
{
//do something with entityLinks
}
}
Run Code Online (Sandbox Code Playgroud) 在 Spring Data Rest 项目中处理延迟加载代理时,使用 Jackson 的Hibernate4Module来处理序列化问题。
一般来说,它解决了 Jackson 尝试序列化未初始化代理的问题,但一个副作用是 JSON 输出不同:
直接获取:api/cases/5400
{
"id": 5400,
"practiceReference": "DWPYI9"
}
Run Code Online (Sandbox Code Playgroud)
通过延迟加载的 @ManyToOne 获取:api/submissions/11901/parentCase
{
"content": {
"id": 5400,
"practiceReference": "DWPYI9"
}
}
Run Code Online (Sandbox Code Playgroud)
通过非延迟加载的 @ManyToOne 获取:api/submissions/11901/parentCase
{
"id": 5400,
"practiceReference": "DWPYI9"
}
Run Code Online (Sandbox Code Playgroud)
从上面可以看出,序列化惰性@ManyToOne关联时 JSON 表示有所不同:实体包装在content节点中。
如果关联是非惰性的,则无论路径如何,都会写入相同的表示形式。
这是否有原因,并且可以以某种方式阻止附加的“内容”节点吗?
2017 年 2 月更新:
我在这里找到了相同的(已删除的)问题:
/sf/ask/2323618811/ different-resulting-jsons-when-serializing-lazy-objects-and-simple-objects
这是从这个 github 问题中引用的。另外,这里报告了,所以似乎是一个已知问题:
我有两张桌子:
用户:
- user_id(主要)
- ip(唯一)
- ETC ..
服务到IP
- id(主要)
- 服务ID
- ip
- ETC ..
课堂上用户:
@OneToMany()
@JoinColumn(name = "ip", insertable = false, nullable = false, updatable = false)
public List<QPlanService> getPlanServices() {
return planServices;
}
Run Code Online (Sandbox Code Playgroud)
使用 MySQL 查询日志,我们得到类似的信息:
SELECT *
FROM services_users planservic0_
LEFT OUTER JOIN services qservice1_
ON planservic0_.service_id = qservice1_.id
WHERE planservic0_.ip = 777
Run Code Online (Sandbox Code Playgroud)
在 WHERE 条件下,使用“user_id”字段(默认字段是主键 - users.id)(user_id=777)。
如何指定我需要从用户实体获取“ip”字段的值,而不是“user_id”?
我将不胜感激任何帮助!
我尝试使用两种模型从REST API(宠物和媒体)获取数据。我试图通过FetchType.EAGER批注获取宠物与媒体之间的oneToMany关系,但是在编写MediaRepository时没有出现数据。如果我没有实现该文件,则媒体关系和数据会在响应中返回。
实施MediaRepository.java后,GET / pets返回:
{
"id": 72,
"name": "Spot",
"description": "Annoying as hell",
"media": [], <-- why is this here only if I don't implement MediaRepository?
...
}
Run Code Online (Sandbox Code Playgroud)
如果未实现MediaRepository.java,则GET / pets将返回:
{
"id": 72,
"name": "Spot",
"description": "Annoying as hell",
... (No media array in response)
}
Run Code Online (Sandbox Code Playgroud)
宠物
@Entity
public class Pet implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name="name")
private String name;
@Column(name="description")
private String description;
@OneToMany(cascade=CascadeType.ALL, mappedBy="pet", …Run Code Online (Sandbox Code Playgroud) 我想自己登录表格.当我更改登录页面时,我无法打开它.Google Chrome告诉我,此页面的重定向过多......
我的代码:
@RequestMapping(value="/login", method = RequestMethod.GET)
public ModelAndView loginPage() {
ModelAndView modelAndView = new ModelAndView("login");
return modelAndView;
}
@RequestMapping(value="/loginError", method = RequestMethod.GET)
public ModelAndView loginErrorPage() {
ModelAndView modelAndView = new ModelAndView("login");
modelAndView.addObject("error", "true");
modelAndView.addObject("msg", "invalid login credentials");
return modelAndView;
}
Run Code Online (Sandbox Code Playgroud)
设置:
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("user").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.antMatchers("/**").access("hasRole('ROLE_USER')")
.and().formLogin().loginPage("/login").defaultSuccessUrl("/index").failureUrl("/loginError");
}
Run Code Online (Sandbox Code Playgroud)
和登录表格:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD …Run Code Online (Sandbox Code Playgroud) 我有一个基于Spring引导的应用程序,使用HSQL数据库上的JPA存储库.
问题是,当应用程序运行时,我创建了一个实体,并且它正确地保存到数据库(可以在数据库管理器中看到).但是从eclipse关闭应用程序后,所有数据都被删除了;
保存是这样执行的
@Service
public class NotificationService {
@Autowired
private NotificationRepository notificationRepository;
public void notifyRefreshArticles(){
Notification notification = new Notification();
notification.setCreatedAt(LocalDateTime.now());
notification.setNotificationSeverity(NotificationSeverity.NORMAL);
notification.setNotificationType(NotificationType.REFRESH_ARTICLES);
notificationRepository.save(notification);
}
}
Run Code Online (Sandbox Code Playgroud)
我很确定它的配置问题,但春天启动基本上只有配置,我有这个配置文件.
spring.datasource.driver-class-name=org.hsqldb.jdbc.JDBCDriver
spring.datasource.url=jdbc:hsqldb:hsql://localhost/rr_app_database
spring.datasource.username=XXXXXX
spring.datasource.password=XXXXXX
spring.datasource.show-sql=true
Run Code Online (Sandbox Code Playgroud) Spring Data Rest存储库指出可以将自定义链接添加到实体,如下所示:
http://docs.spring.io/spring-data/rest/docs/current/reference/html/#_the_resourceprocessor_interface
示例给出:
@Bean
public ResourceProcessor<Resource<Person>> personProcessor() {
return new ResourceProcessor<Resource<Person>>() {
@Override
public Resource<Person> process(Resource<Person> resource) {
resource.add(new Link("http://localhost:8080/people", "added-link"));
return resource;
}
};
}
Run Code Online (Sandbox Code Playgroud)
显然硬编码很糟糕,那么如何编写可以动态获取应用程序中其他资源路径的组件呢?
显而易见的解决方案似乎是注入RepositoryRestConfiguration的实例,但是注入配置中此区域中的所有查找都返回null,即使存储库已公开并且正在为此资源工作.
其他数据,如投影定义,带有ID的类等,按预期在注入的RepositoryRestConfiguration中出现.那么为什么我会为这些查找获取null?
@Component
public class CaseResourceProcessor implements ResourceProcessor<Resource<Case>>
{
@Autowired
private RepositoryRestConfiguration configuration;
@Override
public Resource<Case> process(Resource<Case> resource)
{
//null
configuration.getResourceMappingForDomainType(Submission.class).getPath();
//null
configuration.getResourceMappingForRepository(SubmissionRepository.class).getPath();
resource.add(new Link("...."));
return resource;
}
}
Run Code Online (Sandbox Code Playgroud)
这个领域的大部分代码都被弃用了,但是不清楚究竟应该使用什么代码(尽管我希望不推荐的代码能够起作用).
从本质上讲,我如何以编程方式发现特定实体或存储库的URL.
我有要运行的本机查询:
String sqlSelect =
"select r.id_roster as id, " +
"count(roster_cat.id_category), " +
" sum(case when roster_cat.id_category IN ( :categoryIds) then 1 else 0 end) as counter " +
"from roster r " +
"inner join roster_sa_categories roster_cat " +
"on r.id_roster = roster_cat.id_roster " +
"where r.day = :dayToLookFor " +
"and r.id_shop = :idShop " +
"group by r.id_roster " +
"having count(roster_cat.id_category) = :nrCategories " +
"and count(roster_cat.id_category) = counter" ;
Query selectRostersQuery = entityManager.createNativeQuery(sqlSelect);
selectRostersQuery.setParameter("categoryIds", Arrays.asList(categoryIds)); …Run Code Online (Sandbox Code Playgroud) 给定如下代码:
def do_stuff():
session = boto3.session.Session()
client = session.client(service_name="secretsmanager", region_name=region_name)
client.get_secret_value(SecretId=sendgrid_api_key_arn)
Run Code Online (Sandbox Code Playgroud)
我如何模拟
client.get_secret_value("some-value")返回一些值
我如何模拟它以抛出异常
@patch("boto3.session")
def test_get_sendgrid_api_key_secret_when_client_error(mock_session):
session = mock_session.Session();
client = session.client()
client.get_secret_value().return_value =
{"SecretString": "my-secret"} <- this is wrapped in a MagicMock which is useless.
Run Code Online (Sandbox Code Playgroud) java ×8
spring ×5
hibernate ×4
jpa ×3
jsp ×2
boto3 ×1
jackson ×1
joincolumn ×1
jstl ×1
pytest ×1
pytest-mock ×1
python ×1
spring-boot ×1
spring-data ×1
spring-form ×1