I'm developing a Spring MVC REST application. I made a few simple controller like this:
#Controller
#RequestMapping("/agents")
public class AgentsController {
#Autowired
AgentsRepository agentsRepository;
#RequestMapping(value="/{id}",method=RequestMethod.GET)
public #ResponseBody Agents getAgents(#PathVariable Long id){
Agents agents = agenteRepository.findOne(id);
return agent;
}
#RequestMapping(method=RequestMethod.GET)
public #ResponseBody List<Agents> getAllAgents(){
return agentsRepository.findAll();
}
}
The agent class is annotated in this way:
#XmlRootElement
#Entity
public class Agents implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long idAgents;
private String name;
private String surname;
Now the problem is the following, when I try to do a http get with (host+post/myapplication/agents/1) everything work and I get inside my browser the xml structure, instead when I do (host+post/myapplication/agents) I don't get all agent list in a xml structure, but I get the toString of the collection.
What am I doing wrong?
Related
I'm doing a spring boot experiment and using MySQL.
For example, if I have a list of users, but I want to get the specified names, how can I write the SQL query that only indicates this situation?
This is my model class :
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#Entity
#Table(name="users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public long id;
#Column(name="first_name")
public String name;
#Column (name="last_name")
public String last_name;
}
This is my JPA interface :
public interface CommentRepository extends JpaRepository<User , Long >{
// All C.R.U.D database methods
}
Finally, my controller area is as below :
#RestController
#RequestMapping(path="/api/v1/users")
public class CommentController {
#Autowired
CommentRepository repository ;
#GetMapping(path="/list")
public List<User> users() {
return repository.findAll();
}
}
Maybe you didn't understand my problem, I just want to write a customizable query of my own.
For example, I want to pull the data with the method I designed, while I normally pull the data by numbers with the find by id method.
You can either use methods that will be translated into queries or write your queries in the #Query annotation.
Please read the docs: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories
I'm attempting to get a basic spring application up and running from a tutorial with mysql but I'm running into issues with the GetMapping and PostMapping annotations, here is what I have so far:
I've manually added a user into my table with id=0, name="test" via mysql workbench and verified that the data is in fact there.
I was forced to do it via mysql workbench because attempting to post with curl results in no change
Attempting to call localhost/api/user/1 when there is no user with that ID gives me a 404, which is what is expected while calling it with localhost/api/user/0 gives me an http ok code 200, I'm just not actually receiving a populated JSON object.
Debugging the application on the getUser (using url localhost/api/user/0) shows a user in memory with id=0, name="test" however once the return ResponseBody.ok()... is completed the response I get via browser AND curl is still {}, an empty JSON object
User.Java
#Data
#Builder
#Entity
#Table(name = "user")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private String name;
}
UserRepository.java
#Repository
public interface UserRepository extends CrudRepository<User, Long> {}
UserController.java
#RestController
#RequestMapping("/api/user")
public class UserController {
#Autowired
private UserRepository userRepository;
#GetMapping
public List<User> getAllUsers(){
return (List<User>) userRepository.findAll();
}
#GetMapping("/{id}")
public ResponseEntity<User> getUser(#PathVariable(value="id") long id){
Optional<User> user = userRepository.findById(id);
if(user.isPresent()) {
return ResponseEntity.ok().body(user.get());
}else {
return ResponseEntity.notFound().build();
}
}
#PostMapping
public User saveUser(#Validated #RequestBody User user) {
return userRepository.save(user);
}
}
So to summarize I'm receiving an empty JSON object from my GetMapping AND PostMapping annotated calls, even while I have valid data in the table (or have submitted valid post data) when I should be receiving back a json object with {id:0, name:"test"}, does anyone know what might be happening?
Edit:
It appears as though lombok is not actually injecting getters and setters when I run my application, changing my user.java to
#Entity
#Table(name = "user")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return this.id;
}
}
and recalling localhost/api/user/0 returns the expected json object, Why isnt lombok injecting these functions into my code properly with the #Data annotation? (eclipse)
So this was happening because lombok was not injecting getters/setters and the ResponseEntity.ok.body(user) could not retrieve the values within the User class.
Apparently according to this stackoverflow answer when using eclipse lombok requires a plugin to properly inject the methods.
So this problem can be fixed by either manually defining the appropriate getters/setters needed or by installing the plugin for eclipse.
I'm working on a professional social network application using couchbase server 4.1 with spring data couchbase 2.2.4 in a spring boot application using java 1.8.
I want to replace the next stream which searches a LikeEntity with specific company in the database by a N1QL based query which searches a user with the same previous likeEntity unnested:
Here is the service containing the stream to replace by the query:
#Service
class CompanyServiceImpl implements CompanyService{
#Override
public void addCompanyToLike(UserEntity user, Company company){
int incrementValue=1;
LikeEntity existingLike=user.getLikeEntities()
.stream()
.filter(le->le.getCompany().getName().equals(company.getName()))
.findFirst();
//rest of process
}
}
Here is the different java beans you will need to look at:
UserEntity class:
#Document
#ViewIndexed(designDoc = "user")
class UserEntity implements Serializable{
#Field private String id;
#Reference
private List<LikeEntity> likeEntities=new ArrayList<LikeEntity>();
//Other attributes plus getters and setters:
}
LikeEntity class:
#Document
class LikeEntity implements serializable{
#Reference
private Company company;
#Reference
private Job job;
// other attributes plus getters and setters
}
As you see above, the LikeEntity class may contain any object liked by the user, it can be a company, a job or another object. Also the LikeEntity is stored only inside a user document as element of user's list of likes and not independately in the database.It's my choice of modelization because the LikeEntity won't by used in other java beans of my application
Company:
#Document
#ViewIndexed(designDoc = "company")
class Company implements Serializable{
#Field private String id;
#Field private String name;
//Other attributes plus getters and setters
}
N.B: I've tried the next query inside UserRepository but it didn't work:
UserRepository:
#Repository
#N1qlPrimaryIndexed
#N1qlSecondaryIndexed(indexName = "user")
public interface UserRepository extends CouchbaseRepository<UserEntity, String> {
#Query("SELECT b.*, likeEntity FROM #{#n1ql.bucket} AS b UNNEST b.likeEntities AS likeEntity WHERE b.id=$1 AND likeEntity.company.name=$2")
UserEntity findByLikedCompanyName(String idUser
, String companyName);
}
I'm looking for your answers, and thank you so much in advance.
I am using spring framework and hibernate as an ORM tool.
My parent class is like:
#Entity
public class Category {
#Id
#GeneratedValue
#NotNull
private int cid;
private String cname;
#OneToMany(cascade = CascadeType.ALL)
#LazyCollection(LazyCollectionOption.FALSE)
#JoinColumn(name = "cid")
List<Ad> ads;
//getter and setter, constructor
}
And my child class is like:
#Entity
public class Ad {
private int adid;
private String adName;
//getter and setter, constructor
}
My category controller is :
#Controller
public class CategoryController {
#Autowired
SessionFactory sessionFactory;
Session session;
#Transactional
#RequestMapping(value = "categories",method = RequestMethod.GET)
#ResponseBody
public List<Category> getAllCategory()throws SQLException{
session=sessionFactory.getCurrentSession();
return session.createCriteria(Category.class).list();
}
}
When i hit url localhost:8080/categories .I get json data like:
{"cid":"1",cname":"category","ads":[{"adid":"1","adName":"ad"}]}
Here I am getting datas of both parent and the related child table.But how can I get only datas of parent table.Here in this
example, I need data like:
{"cid":"1",cname":"category"}
How can I do this
I saw a nice article which describes exactly your problem.
Json Exclude Property
By configuring Entity using #JsonIgnore and #JsonProperty annotations you can achieve this.
You can try as below
Infinite Recursion with Jackson JSON and Hibernate JPA issue
Basically have to apply exclusion where you need to break the link
is there a way that I can take the DTO's from a REST api? I want to create my DTO's automaticaly from the JSON REST api. Is there some way?
You can try use a framework library like RESTEasy (Jboss Suite) or Jersey or Gson
Then you only need define a estructure same a you class for example, if your class is something like:
#Entity
#Table(name = "\"entityName\"")
public class Entity implements Serializable {
private static final long serialVersionUID = 3469107762875646075L;
#Id
private Integer id;
#Column
private String name;
public Entity() {
}
//getters and setters
The interface will receive an object of that type.
#POST
#Path("/create")
#Produces(MediaType.APPLICATION_JSON)
Response createEntity(Entity entityObject);
And JSON be this way, then the conversion is automatic.
{
"id":"99",
"name":"stackoverflow"
}
NOTE: The information received must be of the same type defined in your Class to perform this conversion.
After some years, this is what I wanted:
https://app.quicktype.io/