Spring-Data项目未接收到我的Get/Post请求,查询时未找到实体。

huangapple go评论68阅读模式
英文:

Spring-Data Project is not receiving my Get/Post No entity found for query

问题

I finished creating a simple Spring-boot project in which I can enter users and through the Get command it returns me the name (from a list of identical names) with the oldest entry date. Unfortunately, every time I ask for Get it returns this **ERROR**:

D:\>curl -G localhost:8080/demo/first -d name=Biagio
{"timestamp":"2020-10-05T08:52:34.741+00:00","status":500,"error":"Internal Server Error","message":"","path":"/demo/first"}

In the Spring-Boot terminal I have this **ERROR**:

Biagio
2020-10-05 10:52:34.722 ERROR 8860 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.EmptyResultDataAccessException: No entity found for query; nested exception is javax.persistence.NoResultException: No entity found for query] with root cause

Even when I try to POST / add I get a message that it has saved in the DB but hasn't actually saved anything

Below I add all interested parties:

**AccessingDataMysqlApplication.java**

package com.example.accessingdatamysql;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;


@SpringBootApplication
public class AccessingDataMysqlApplication {

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

}

**MainController.java**

package com.example.accessingdatamysql.rest;

import javax.persistence.NoResultException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.service.UserService;

@RestController
@RequestMapping("/demo")
public class MainController {

@Autowired
private UserService userService;

@Transactional
//@RequestMapping(value = "/add/", method = RequestMethod.POST)
@PostMapping(path="/demo/add")
public String addNewUser(@PathVariable("name") String name, @PathVariable("email") String email,
@PathVariable("surname") String surname) {

UserDto n = new UserDto();
n.setName(name);
n.setSurname(surname);
n.setEmail(email);
userService.create(n);
return "User Saved in DB";
}

@SuppressWarnings({ "rawtypes", "unchecked" })
//@RequestMapping(value = "/fetchUser/{name}", method = RequestMethod.GET)
@GetMapping("/demo/first")
public ResponseEntity<UserDto> fetchUser(@PathVariable("name") String name) {
System.out.println(name);

try {
UserDto namefound = userService.findFirstByName(name);
System.out.println("Name found");
ResponseEntity<UserDto> user = new ResponseEntity<UserDto>(namefound, HttpStatus.OK);
return user;
} catch(NoResultException ne) {
System.out.println("User not found");
return new ResponseEntity("User not found with name : " + name, HttpStatus.NOT_FOUND);
}

}
}


**UserService.java**

package com.example.accessingdatamysql.service;

import org.springframework.stereotype.Service;

import com.example.accessingdatamysql.model.UserDto;
@Service
public interface UserService {

UserDto findFirstByName(String name);

void create(UserDto user);

}

**UserServiceImpl.java**

package com.example.accessingdatamysql.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.model.UserEntity;
import com.example.accessingdatamysql.repo.UserRepository;
import com.example.accessingdatamysql.util.UserMapper;

@Service
public class UserServiceImpl implements UserService {

@Autowired
private UserRepository userRepository;

@Autowired
UserMapper mapper;

@Override
public UserDto findFirstByName(String name) {
	UserEntity entity = userRepository.findFirstByName(name);
	return mapper.toDtoMapper(entity);
}

@Override
public void create(UserDto user) {
	UserEntity entity = mapper.toEntityMapper(user);
	userRepository.create(entity);
}

}

**UserMapper.java**

package com.example.accessingdatamysql.util;

import org.mapstruct.Mapper;

import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.model.UserEntity;

@Mapper(componentModel = "spring")
public interface UserMapper {

public UserEntity toEntityMapper (UserDto user);	
public UserDto toDtoMapper (UserEntity userEntity);

}

**UserRepository.java**

package com.example.accessingdatamysql.repo;

import org.springframework.stereotype.Repository;

import com.example.accessingdatamysql.model.UserEntity;

@Repository
public interface UserRepository {
UserEntity findFirstByName(String name);
void create(UserEntity entity);

}

**UserRepositoryImpl.java**

package com.example.accessingdatamysql.service;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Component;

import com.example.accessingdatamysql.model.UserEntity;
import com.example.accessingdatamysql.repo.UserRepository;

@Component
public class UserRepositoryImpl implements UserRepository {

private final EntityManager em;

public UserRepositoryImpl(EntityManager entityManager) {
	this.em = entityManager;
}

@Override
public UserEntity findFirstByName(String name) {
	CriteriaBuilder builder = em.getCriteriaBuilder();
	CriteriaQuery&lt;UserEntity&gt; criteria = builder.createQuery(UserEntity.class);
	Root&lt;UserEntity&gt; root = criteria.from(UserEntity.class);
	criteria.select(root).where(builder.equal(root.get(&quot;name&quot;), name));
	criteria.orderBy(builder.asc(root.get(&quot;timestamp&quot;)));
	TypedQuery&lt;UserEntity&gt; query = em.createQuery(criteria).setMaxResults(1);
	return query.getSingleResult();

}

@Override

// per la creazione//
public void create(UserEntity entity) {
em.persist(entity);
}

}

**UserDto.java**

package com.example.accessingdatamysql.model;

import java.io.Serializable;
import java.sql.Timestamp;

public class UserDto implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = -7621330660870602403L;
/**
 * 
 */

private String name;

public String getName() {
英文:

I finished creating a simple Spring-boot project in which I can enter users and through the Get command it returns me the name (from a list of identical names) with the oldest entry date. Unfortunately, every time I ask for Get it returns this ERROR:

D:\&gt;curl -G localhost:8080/demo/first -d name=Biagio
{&quot;timestamp&quot;:&quot;2020-10-05T08:52:34.741+00:00&quot;,&quot;status&quot;:500,&quot;error&quot;:&quot;Internal Server Error&quot;,&quot;message&quot;:&quot;&quot;,&quot;path&quot;:&quot;/demo/first&quot;}

In the Spring-Boot terminal I have this ERROR:

Biagio
2020-10-05 10:52:34.722 ERROR 8860 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.EmptyResultDataAccessException: No entity found for query; nested exception is javax.persistence.NoResultException: No entity found for query] with root cause

Even when I try to POST / add I get a message that it has saved in the DB but hasn't actually saved anything

Below I add all interested parties:

AccessingDataMysqlApplication.java

package com.example.accessingdatamysql;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;


@SpringBootApplication
public class AccessingDataMysqlApplication {

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

}

MainController.java

package com.example.accessingdatamysql.rest;

import javax.persistence.NoResultException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.service.UserService;

@RestController
@RequestMapping(&quot;/demo&quot;)
public class MainController {

@Autowired
private UserService userService;

@Transactional
//@RequestMapping(value = &quot;/add/&quot;, method = RequestMethod.POST)
@PostMapping(path=&quot;/demo/add&quot;)
public String addNewUser(@PathVariable(&quot;name&quot;) String name, @PathVariable(&quot;email&quot;) String email,
@PathVariable(&quot;surname&quot;) String surname) {

UserDto n = new UserDto();
n.setName(name);
n.setSurname(surname);
n.setEmail(email);
userService.create(n);
return &quot;User Saved in DB&quot;;
}

@SuppressWarnings({ &quot;rawtypes&quot;, &quot;unchecked&quot; })
//@RequestMapping(value = &quot;/fetchUser/{name}&quot;, method = RequestMethod.GET)
@GetMapping(&quot;/demo/first&quot;)
public ResponseEntity&lt;UserDto&gt; fetchUser(@PathVariable(&quot;name&quot;) String name) {
System.out.println(name);

try {
UserDto namefound = userService.findFirstByName(name);
System.out.println(&quot;Name found&quot;);
ResponseEntity&lt;UserDto&gt; user = new ResponseEntity&lt;UserDto&gt;(namefound, HttpStatus.OK);
return user;
} catch(NoResultException ne) {
System.out.println(&quot;User not found&quot;);
return new ResponseEntity(&quot;User not found with name : &quot; + name, HttpStatus.NOT_FOUND);
}

}
}

UserService.java

package com.example.accessingdatamysql.service;

import org.springframework.stereotype.Service;

import com.example.accessingdatamysql.model.UserDto;
@Service
public interface UserService {

	UserDto findFirstByName(String name);
	
	void create(UserDto user);
    	
}

UserServiceImpl.java

package com.example.accessingdatamysql.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.model.UserEntity;
import com.example.accessingdatamysql.repo.UserRepository;
import com.example.accessingdatamysql.util.UserMapper;

@Service
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserRepository userRepository;

	@Autowired
	UserMapper mapper;

	@Override
	public UserDto findFirstByName(String name) {
		UserEntity entity = userRepository.findFirstByName(name);
		return mapper.toDtoMapper(entity);
	}

	@Override
	public void create(UserDto user) {
		UserEntity entity = mapper.toEntityMapper(user);
		userRepository.create(entity);
	}

}

UserMapper.java

package com.example.accessingdatamysql.util;

import org.mapstruct.Mapper;

import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.model.UserEntity;



@Mapper(componentModel = &quot;spring&quot;)
public interface UserMapper {	
	
	public UserEntity toEntityMapper (UserDto user);	
	public UserDto toDtoMapper (UserEntity userEntity);
	
}

UserRepository.java

package com.example.accessingdatamysql.repo;


import org.springframework.stereotype.Repository;

import com.example.accessingdatamysql.model.UserEntity;


@Repository
public interface UserRepository {
	UserEntity findFirstByName(String name);
	void create(UserEntity entity);
	
}

UserRepositoryImpl.java

package com.example.accessingdatamysql.service;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Component;

import com.example.accessingdatamysql.model.UserEntity;
import com.example.accessingdatamysql.repo.UserRepository;

@Component
public class UserRepositoryImpl implements UserRepository {

	private final EntityManager em;

	public UserRepositoryImpl(EntityManager entityManager) {
		this.em = entityManager;
	}

	@Override
	public UserEntity findFirstByName(String name) {
		CriteriaBuilder builder = em.getCriteriaBuilder();
		CriteriaQuery&lt;UserEntity&gt; criteria = builder.createQuery(UserEntity.class);
		Root&lt;UserEntity&gt; root = criteria.from(UserEntity.class);
		criteria.select(root).where(builder.equal(root.get(&quot;name&quot;), name));
		criteria.orderBy(builder.asc(root.get(&quot;timestamp&quot;)));
		TypedQuery&lt;UserEntity&gt; query = em.createQuery(criteria).setMaxResults(1);
		return query.getSingleResult();

	}

	@Override
//	per la creazione//
	public void create(UserEntity entity) {
		em.persist(entity);
	}

}

UserDto.java

package com.example.accessingdatamysql.model;

import java.io.Serializable;
import java.sql.Timestamp;

public class UserDto implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7621330660870602403L;
	/**
	 * 
	 */

	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Timestamp getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(Timestamp timestamp) {
		this.timestamp = timestamp;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getSurname() {
		return surname;
	}

	public void setSurname(String surname) {
		this.surname = surname;
	}

	private Timestamp timestamp;
	private String email;
	private String surname;

}

If you need also I could provide User.java and the pom file, but the pom has no problems as the dependencies are all correct.

答案1

得分: 1

你的create方法是无效的。因此,实际上你无法检索到一些数据。
你只调用了persist方法,但你还需要调用flush来将其实际写入数据库。代码片段可能如下所示:

@Transactional
@Override
public void create(UserEntity entity) {        
    if (!em.contains(entity)) {
        em.persist(entity);
        em.flush();
    }
}
英文:

Your create method is invalid. And because of this you cannot actually retrieve some data.
You only called persist method, but you also need to call flush to actually write this to DB. Code snippet could look like this:

@Transactional
@Override
public void create(UserEntity entity) {        
    if (!em.contains(entity)) {
        em.persist(entity);
        em.flush();
    }
}

答案2

得分: 0

好的,以下是翻译好的内容:

你的查询中没有结果,但可以使用getSingleResult()来强制获取一个结果。你可以使用Spring的CrudRepository,这会更加简单。

英文:

Well, you get no result in your query but force one with getSingleResult(). You can use a CrudRepository from Spring, that's a bit easier.

huangapple
  • 本文由 发表于 2020年10月5日 16:58:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/64205487.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定