I have referred to ->
Spring MVC how to display data from database into a table
My aim is to try and understand what is the syntax and process to create queries, and whether I'm correct.
The following code tries to display all Order entities.
#AutoWired
private OrderService orderService;
#RequestMapping("/")
//public String orderPage(Model model) {
// model.addAttribute("orderList", SomeApp.getStore().getOrderList());
// return "form/orderPage"};
// this is the code I am trying to translate below
#ResponseBody
public List<order> orderList(Map<String, Object> model) {
List<order> orderList = OrderService.findALl();
//orderRepository.findAll <- where does this come in? is it needed at all
return orderList;
}
If the Service layer is not being used, in my Repo do I only state
List<Order> findAll();
Additional Info:
Service layer is not used in this project and instead business logic will be in Controller (partly why I'm confused as to what code goes where)
You need to #Autowire the OrderRepository so that you can call orderRepository.findAll() in your Controller as shown below. For that, you also need to define the OrderRepository and Order Entity classes.
Controller:
#Controller
public class Controller {
#AutoWired
private OrderRepository orderRepository;
#RequestMapping("/")
#ResponseBody
public List<order> orderList(Map<String, Object> model) {
List<order> orderList = OrderService.findALl();
orderRepository.findAll();
return orderList;
}
}
Repository:
#Repository
public interface OrderRepository extends JpaRepository<Order, Integer> {
public Order findAll();
}
Entity:
#Entity
public class Order {
//add your entity fields with getters and setters
}
You can refer here for spring-data-jpa basic example.
Related
Am learning about data sync from API to WPF app. Got a demo from https://github.com/Azure/azure-mobile-apps/tree/main/samples. But I got into a problem that all the data inside the tables are collected on the call but I need to select specific data using Id. Tried a query etc all came to nothing. Please guide me
Thank you
PatientsController.cs
[Route("tables/Patients")]
public class PatientsController : TableController<Patients>
{
public PatientsController(AppDbContext context)
: base(new EntityTableRepository<Patients>(context))
{
}
}
AppDbContext.cs
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<Patients> Patients => Set<Patients>();
}
Try to use the following code:
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<Patients> Patients {get;set;}
}
controller:
[Route("tables/Patients")]
public class PatientsController : TableController<Patients>
{
private readonly AppDbContext _context;
public PatientsController(AppDbContext context)
: base(new EntityTableRepository<Patients>(context))
{
_context=context;
}
public async Task<IActionResult> Index(int id){
var Patients=_context.Patients.FindAsync(id);
return View(Patients);
}
}
If you just need to get a record by Id, you use the URL https://mysite/tables/myTable/id - no search required - it will go directly to the entity you want.
If you need to limit what a user can see, you will need to implement an access control provider (which is an implementation of IAccessControlProvider). This provides three methods to limit what a user can see and do model updates for ensuring the write operations store the right thing. You can read more here: https://learn.microsoft.com/en-us/azure/developer/mobile-apps/azure-mobile-apps/howto/server/dotnet-core#configure-access-permissions
If it's something else, you'll need to be a little more specific. I hang out in the issues and discussions of the azure/azure-mobile-apps repo, so feel free to file a question there.
I am using spring boot along with react js and postgresql. I am trying to print the rows of table from postgresql to a react js page. I have used crud repository function findAll() in the controller method to get the List. My problem is that when I am printing the List in spring boot console, it prints the list but it's printing empty objects' list when that url is accessed.
User.java
#Entity
#Table(name="users")
public class User implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name="name")
private String name;
#Column(name="email")
private String email;
public User() {
}
public User(String name, String email) {
this.name = name;
this.email = email;
}
#Override
public String toString() {
return String.format("User[id=%d, name='%s', email='%s']",this.id,this.name,this.email);
}
}
UserRepository.java
public interface UserRepository extends CrudRepository<User, Long>{
}
WebController.java
public class WebController {
#Autowired
private UserRepository repository;
#GetMapping("home")
public String home() {
System.out.println("whaaat");
return "hi ssup";
}
#GetMapping("/save")
public String process() {
repository.save(new User("vidhi","vd#gmail.com"));
System.out.print("apple ");
return "Done";
}
#GetMapping("findall")
#ResponseBody
public Collection<User> findAll() {
System.out.println("cc");
List<User> users = (List<User>) repository.findAll();
System.out.println(users);
return users;
}
}
On printing users in boot: [User[id=33, name='i', email='vd#gmail.com'], User[id=34, name='v', email='d#gmail.com']
on localhost:8080/findall: [{},{}]
What's going on wrong here? I am very confused and trying to figure this out since a lot of time and it's eating my head.
Any help would be wonderful!
Thanks for your time.
You have to add getters and setters to the User class.
Change it to:
#GetMapping("findall", produces= MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public ResponseEntity<Collection<User>> findAll() {
System.out.println("cc");
List<User> users = (List<User>) repository.findAll();
System.out.println(users);
return ResponseEntity.ok(users);
}
change your repo to:
#Repository
public interface UserRepository extends JpaRepository<User, Long>{
}
I have mongodb related code in my java application and can I switch between two collections under same db in java code ?
#JsonIgnoreProperties(ignoreUnknown = true)
#Document(collection = "collectionA")
#QueryEntity
public class RepreCase {
I want to have a different collection here instead of this say collectionB #Document(collection = "collectionA") and comeback to the same collectionA, by switching between the two collections A & B under same DB
Can I do like this ? #Document(collection = "collectionA, collectionB")
Is it achievable & How ? Thanks in advance
This example should help
Define your entity class like
#Document(collection = "${EventDataRepository.getCollectionName()}")
public class EventData implements Serializable {
Define a custom repository interface with getter and setter methods for "collectionName"
public interface EventDataRepositoryCustom {
String getCollectionName();
void setCollectionName(String collectionName);
}
Provide implementation class for custom repository with "collectionName" implementation
public class EventDataRepositoryImpl implements EventDataRepositoryCustom{
private static String collectionName = "myCollection";
#Override
public String getCollectionName() {
return collectionName;
}
#Override
public void setCollectionName(String collectionName) {
this.collectionName = collectionName;
}
}
Add EventDataRepositoryImpl to the extends list of your repository interface in this it would look like
#Repository
public interface EventDataRepository extends MongoRepository<EventData, String>, EventDataRepositoryImpl {
}
Now in your Service class where you are using the MongoRepository set the collection name, it would look like
#Autowired
EventDataRepository repository ;
repository.setCollectionName("collectionName");
I need help with connecting my WebSocket to my DB in spring boot.
I know that the DB access happens in the controller but I don't know how.
#Controller
public class ChatController {
#MessageMapping("/chat.register")
#SendTo("/topic/public")
public ChatMessage register(#Payload ChatMessage chatMessage, SimpMessageHeaderAccessor headerAccessor) {
headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
return chatMessage;
}
#MessageMapping("/chat.send")
#SendTo("/topic/public")
public ChatMessage sendMessage(#Payload ChatMessage chatMessage) {
return chatMessage;
}
}
Where would I connect to the DB
Its not a good idea to add a repository to your controller. A better approach is to add a service layer between controller and database.
#Controller
public class ChatController {
#Autowired
private Chatservice chatservice;
#MessageMapping("/chat.register")
#SendTo("/topic/public")
public ChatMessage register(#Payload ChatMessage chatMessage, SimpMessageHeaderAccessor headerAccessor) {
headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
chatservice.saveChatMessage(chatMessage); // save this too?
return chatMessage;
}
#MessageMapping("/chat.send")
#SendTo("/topic/public")
public ChatMessage sendMessage(#Payload ChatMessage chatMessage) {
chatservice.saveChatMessage(chatMessage);
return chatMessage;
}
}
#Service
private class ChatService {
#Autowired
private ChatRepository repository;
public void saveChatMessage(ChatMessage chatMessage) {
// do more business stuff here e.g. Mapping to Entity ....
repository.save(chatMessage);
}
}
public interface ChatRepository extends CrudRepository<ChatMessage, Long> {
}
requirement is that i want request type scope in particular bean Omsdashboard.java .i have to submit the architecture of controller where i want every time request i want new object .so this can be achieve by request scope because controller is by default singleton that why i cant not handle this problem please explain it. thanks for giving your time.
beans class
Omsdashborad.java
#Component
public class OMSDashBoard implements Serializable{
controller class
I am using autowire but they give singleton object but i want another object when project is loaded both method call onload time first call below method then call first method.
#Autowired
private WebApplicationContext context;
private OMSDashBoard omsDashBoard;
public OMSDashBoard getOMSDashBoard() {
System.out.println("##2"+(OMSDashBoard) context.getBean("omsDashBoard"));
return (OMSDashBoard) context.getBean("omsDashBoard");
}
#Autowired(required = false)
public void setOmsDashBoard(#Qualifier("omsDashBoard") OMSDashBoard omsDashBoard) {
this.omsDashBoard = omsDashBoard;
#RequestMapping(value = "/stuck/order/{fromDate}/{toDate}/{requestType}", method = RequestMethod.POST)
public ResponseEntity<OMSDashBoard> getAllStcukOrdersByRequestType(#PathVariable("fromDate") String fromDate,
#PathVariable("toDate") String toDate, #PathVariable("requestType") String orderTypeCd) {
return new ResponseEntity<OMSDashBoard>(omsDashBoard, HttpStatus.OK);
}
#RequestMapping(value = "order/summary/{fromDate}/{toDate}", method = RequestMethod.POST)
public ResponseEntity<OMSDashBoard> getOrderSummaryDetails(#PathVariable("fromDate") String fromDate,
#PathVariable("toDate") String toDate) {
return new ResponseEntity<OMSDashBoard>(omsDashBoard, HttpStatus.OK);
}
step :
use scope(value="request") in omsdashboard.java
step-2
autowired
public AnnotationConfigWebApplicationContext context;
step-3
OMSDashBoard omsDashBoard = (OMSDashBoard) context.getBean(OMSDashBoard.class); in both method to get new object through bean.