Win a copy of TensorFlow 2.0 in Action this week in the Artificial Intelligence and Machine Learning forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

How would you immediately get the ID primary key generated from a POST request in Javascript?

 
Ranch Hand
Posts: 365
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm utilizing Java Spring Boot with Javascript.   This part of the application the school registers their school for the prom ticket application, and then they login with their ID number to start entering data and using the web application.  


What I want it to do after it posts, is to get the ID from MySQL of the entry that it had just entered, and a window box saying, "Successfully Registered!  Your school ID number is #"  the pound sign being the number.

However, if I just do a Get request, it may get all of them, and if I just search by the school name after the get all and then give back that number, what if two schools registered the same school name?  

Here is my function.



What do I do next to get that same entry and get the primary key of the school ID from it?  I put in null, which give it an auto increment because it is not null in MySQL.  

Would I do a get request, and if I did, how would I filter it to get just the request just sent without having to query by school name?   Is this even possible?  



I work for a hotel chain, and after we register a membership for someone, it gives back a message saying their membership number.  I want to do something like that.  
 
Saloon Keeper
Posts: 12432
269
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should edit the server-side of the application to return the ID with the rest of the response after it has created the new school.
 
Nathan Milota
Ranch Hand
Posts: 365
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:You should edit the server-side of the application to return the ID with the rest of the response after it has created the new school.



It is done through a rest controller and it's a POST method, so I'm not sure how to do that.  Is there an example somewhere?  

The MySQL has a function to get the last ID.  

I'm on my phone now, so I unfortunately don't have a copy of the post method on me.
 
Nathan Milota
Ranch Hand
Posts: 365
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In my post method which is normally a void method, I changed it to return an int, and when I returned the school's id, it gave a value of 0 in Java, so when it posts to the database, by the time I retrieve the ID of it, it is still 0 for some reason.
 
Nathan Milota
Ranch Hand
Posts: 365
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I added the @GeneratedValue(strategy = GenerationType.IDENTITY) and got the right value.  I'm still tackling how to send it over to the javascript function now.
 
Stephan van Hulst
Saloon Keeper
Posts: 12432
269
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You just return an object containing the ID and other info related to the registered school from your REST controller action:
 
Nathan Milota
Ranch Hand
Posts: 365
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot for the well prepared response.

I'm still new to Spring Boot, so a lot of it goes over my head right now.  

What I did was I changed the post method to an int instead of a void, and then returned the id of the school and put a pop up window saying what their school number is after they registered based on what the method returns.  


I'm curious though.  Why so many classes?  Just for cleaner code or encapsulation purposes?  

The tutorials and Spring Boot projects with controllers I've seen didn't have so many classes.  Just one Controller, Service, and Repository interface.  That along with the class of the type object itself as well.
 
Stephan van Hulst
Saloon Keeper
Posts: 12432
269
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From experience I can tell you that requests and responses often need to change to include more data than what you thought they needed in the first iteration of your application. Response wrappers decouple the response from the domain model, and leave you free to add more properties in the future without breaking your API.

Your JSON is also nicer to read. What is a more informative response after a registration:Or:
Note that the second example would require registerSchool() to return a RegisterSchoolResponse instead of a GetSchoolResponse.
 
Nathan Milota
Ranch Hand
Posts: 365
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Part of the problem I'm having with Spring Boot is that I cannot understand what Spring really is to begin with.  

Every tutorial, book, video, website that explains it has something different from a bean, xml files, configurations, etc.  None of it seems consistent.  
 
Stephan van Hulst
Saloon Keeper
Posts: 12432
269
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's because Spring is lots of things. It is a set of tools that solve common problems in web application development.

Imagine we didn't have Servlets. Every time you wanted to write a web service, you'd first have to write a web server that listens to an internet socket and parses and formats HTTP messages. You'd quickly get tired of this and write a library that you can use in all your web services.

Thankfully you don't have to, because Java EE contains the Servlet specification that says if you extend HttpServlet and package your application as a WAR, a compliant web application container will do the HTTP handling for you, and you just need to handle the HttpServletRequest.

As it turns out, even when servlets handle the details of HTTP for you, there are still a lot of repetitive task that you need to perform in every web application:

  • Load the application configuration
  • Route the request to the code that will handle it
  • Convert data in the request to objects from your model
  • Find out who the user is
  • Make sure the user is allowed to make the request
  • Initialize services that you need to fulfill the request
  • Create a view from the response data using a template

  • These tasks, and others I haven't mentioned, would drive you completely nuts if you had to write code to do them for every web application you wrote.

    Spring handles all this for you, so you can focus on what makes your web application different from other web applications. Because there is so much plumming to do, Spring is very large and complex, and beginners will often feel very overwhelmed. Thankfully, their user guide is very well written and with some practice you will be able to perform complex tasks very easily.

    I would say that the most important problem that Spring solves is dependency injection. It allows you to tell Spring what beans (services) your application will need, and how they are configured. Classes that need the service will have them injected with the @Autowired annotation.

    Note that Spring is not your only choice. Besides the Servlet specification, Java EE contains specifications for other components that handle the repetitive tasks that Spring also handles.

    For instance, instead of Spring REST Controllers, you can use JAX-RS. Instead of Spring dependency injection, you can use CDI. Instead of Spring Security, you can use Java EE Security API. And when Java EE 10 comes, you can probably use the MVC specification instead of Spring MVC. Personally I prefer the Java EE specs over Spring, but at this point it's mostly just a matter of what you're familiar with.
     
    Nathan Milota
    Ranch Hand
    Posts: 365
    2
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    So, if the repository is an interface, why do we never implement it?
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 12432
    269
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    What do you mean?
     
    Nathan Milota
    Ranch Hand
    Posts: 365
    2
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Stephan van Hulst wrote:What do you mean?



    You only instantiated the repository, but didn't implement it.  Why do we make the interface?
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 12432
    269
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Where did I instantiate it? And who says we don't implement the interface?
     
    Saloon Keeper
    Posts: 22671
    153
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Nathan Milota wrote:Part of the problem I'm having with Spring Boot is that I cannot understand what Spring really is to begin with.  

    Every tutorial, book, video, website that explains it has something different from a bean, xml files, configurations, etc.  None of it seems consistent.  



    Spring is a framework designed to construct and serve up JavaBeans. At its heart is a factory object (the BeanFactory) which is a resource that can be invoked to return a named JavaBean. Spring will create and initialize the bean if it does not exist, and that includes any secondary beans that are referenced by that bean's definition. Everything else is built on that foundation. Formally, Spring provides what is known as an Inversion of Control (IoC) system. IoC is about taking things defining their relationships so that an external mechanism (for example, Spring) can wire them together, rather like TinkerToys™. This can be contrasted with the Service Locator Design Pattern, where the beans have to find other beans themselves, and thus have to have locator code hard-coded into each bean that needs to connect. IoC can thus be more easily used with POJOs.

    The beans are defined via a master definition XML file and/or by placing annotations on the class definitions for the JavaBeans that you wish for Spring to manage. You can actually build very complex definitions using many different sources and data formats, but the XML and annotations are sufficient for most purposes.

    This mechanism is at the core of Spring, but successive layers have been built around it to provide convenience and standardization. For example, Spring Data provides data persistence services for a wide variety of storage mechanisms, including raw JDBC, JPA, noSQL storage such as MongoDB and graph databases like Neo4J. Spring Data provides interface consistency as well as automatically doing the "grunt" work like freeing up connections when a database exception occurs, doing automatic rollback on failure, and so forth.

    There are quite a few of these extensions. Spring Boot is the one that builds single-purpose web applications with built-in dedicated web server. Such constructs make it easy to create portable (OS-independent) GUI applications that can be deployed as a simple, single unit (as opposed to the messier traditional way that requires separate installation of a webapp server and configuration and deployment of the application itself).

    Multiple Spring modules can be used in a single application. For example, Spring Data - JPA in a Spring Boot application. I've got apps that have used 4 or 5 different modules in one app, in fact.

    For a good introduction to Spring, Manning Publications "Spring In Action" book is recommended.
     
    Nathan Milota
    Ranch Hand
    Posts: 365
    2
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I have the book "Spring In Action".  I'll have to start reading it again, it seems.  

    What I was mainly getting at is, Spring Boot seems to eliminate the need to use anything such as a xml file, bean factory, component scan, etc... So, is there still a point to learning it, and why?

    We don't learn frameworks in college or even touch the surface of them.  The local courses that have labs where you learn Spring and Spring Boot in person all cost thousands of dollars that I don't have, but what I would really need is something like in person, hands on training with it to understand it.  I'm hoping whatever company I am able to join eventually has some kind of training that clears up some of the gray areas.  
     
    Tim Holloway
    Saloon Keeper
    Posts: 22671
    153
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I don't count myself as an expert in Spring Boot, but I doubt very seriously that that it eliminates the BeanFactory. In fact, odds are that one of the first things that the Spring Boot Bootstrap class does is obtain a Tomcat server bean from the BeanFactory and initialize it, deploy the webapp into it, and launch Tomcat.

    A lot of the processes and configurations outlined in Spring In Action may have been assisted by code that's a standard part of Spring Boot, but I think that if you dig, you'll find that they are still there. And you'll be better off knowing that they're there when it comes time to do things that the standard Spring Boot setup cannot handle.
     
    Nathan Milota
    Ranch Hand
    Posts: 365
    2
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Say in my example, I have a Student class, and when a Student is given a Ticket, they have an object of the Ticket class.   Those are tightly coupled.  How do you use dependency injection there?
     
    Tim Holloway
    Saloon Keeper
    Posts: 22671
    153
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Nathan Milota wrote:Say in my example, I have a Student class, and when a Student is given a Ticket, they have an object of the Ticket class.   Those are tightly coupled.  How do you use dependency injection there?



    You don't. Dependency injection is part of the construction process. That "is given" is an indication of a post-construction action. Students and Tickets would, presumably, be JPA Entity Objects, which are constructed via the "new" operator, not obtained from a BeanFactory. BeanFactory mostly returns singleton objects, and Entities are rarely singletons.

    In your case, you might have a separate Ticket factory that constructs a Ticket for a particular school. Such a factory would initialize the Ticket's ID components, giving a unique ticket ID from a sequence constructor for each school ID passed to it. Although there are other ways to do that, including some rather gnarly techniques within JPA itself. You probably wouldn't be using the Spring BeanFactory, though. It's more geared towards producing stuff from fixed specifications. And, as I said, generally Singleton instances, not multiple parameterized Entity Instances.

    Note: "Dependency Injection" is not the same thing as "Injection". A Dependency Injection is an Injection done because Spring has been told that the object being requested references other object(s), which then have to be located/created and Injected into the object being created. Dependency Injection is only done at construction time. General Injections can occur at any time (allowing for possible multi-threading issues).
     
    Nathan Milota
    Ranch Hand
    Posts: 365
    2
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Is there an online web course or anything other than just someone's video channel on YouTube for learning Spring and Spring boot you'd recommend?  I personally just don't like "Spring in Action".   It's entire book is about building a taco application, and I think many of its tools might be out of date as the code as written in the book simply does not work and I don't find it to be a very good book for a beginner as it's very confusing.
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 12432
    269
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Have you tried Spring's own user manual, and their quickstart and tutorials?
     
    Nathan Milota
    Ranch Hand
    Posts: 365
    2
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I'm trying a Udemy course right now that is pretty extensive.

    I've been studying it for several days though and still cannot make the connection and that light bulb hasn't really gone off on what Spring really is yet and what the purpose of it, or what dependency injection or IOC really means.
     
    Tim Holloway
    Saloon Keeper
    Posts: 22671
    153
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Nathan Milota wrote:I'm trying a Udemy course right now that is pretty extensive.

    I've been studying it for several days though and still cannot make the connection and that light bulb hasn't really gone off on what Spring really is yet and what the purpose of it, or what dependency injection or IOC really means.



    Think of it like a TinkerToy™ set. You have bobbins with holes in them and you connect them with sticks to make things.

    IoC works like that. The "bobbins" are Java objects (usually POJOs) and the "sticks" are the connections between them.

    Say you have a "bobbin" that's a Person. And that person owns a Bicycle. But which bicycle? The world is full of bicycles. So your Person class has a member object of type Bicycle that represents that person's bicycle. Now you use the Person's setBicycle() method to inject a particular instance of Bicycle into that instance of Person. You're doing the work of the IoC framework here.

    The alternative would be for the Person to locate the bicycle themselves. That would require some sort of location mechanism and you'd have to code it all up inside the Person class. Which makes it less of a POJO, less generic, and thus less re-usable. That is the older way of doing things, which is why IoC is called Inverson of Control. Control comes from the outside in instead of the inside out. Or, as I like to say, "Good Things come to Those Who Wait".

    In practice, an IoC framework such as Spring has a Bean Factory to locate named beans, constructing them if necessary, and is provided with hints on how to wire them together such as via a Spring application configuration XML file and/or annotations such as @Autowired on the bean class definitions. And, incidentally, the beans so managed are comonly - though not always - singleton objects.

    It might seem overkill if you have onely one Person and one Bicycle to set up an elaborate factory and framework to link the two, but if Bicycle was an Interface instead of a concrete class, then you could implement it in class RealBicycle and class TestBicycle and switch back and forth just by changing the wiring rules without any code changes at all.
     
    Nathan Milota
    Ranch Hand
    Posts: 365
    2
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    From what I've seen studying DI, is that people are saying without it, you have tightly coupled classes, which you have to instantiate a new object.  With dependency injection, you have an interface instead, and you put that interface in the classes constructor, and declare it with the object, and therefore it is loosely coupled.  

    I guess none of the programs I've created had anything tightly coupled before, so I just haven't seen the need for dependency injection and loose coupling before.  

    Does anyone know of a good video or source that creates a web application and shows you the steps start to finish so that you get how it all works after you finish?
     
    Tim Holloway
    Saloon Keeper
    Posts: 22671
    153
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    No, you don't need Interfaces to do Dependency Injection. If you're not looking for plug-replaceable components, a simple class is all you need.

    But the "tight coupling" is exactly what I meant when I mentioned the old-school arrangement where one class had to know how to locate and bind to another.
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 12432
    269
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    A simple example. Here's the lookup pattern (booo!):

    Here's the same application, using dependency injection (yaaay!):

    As you can see, instead of making SomeComponent class responsible for knowing where it gets its dependencies, you make its clients (Application in this case) responsible for injecting its dependencies. This has three major benefits:

  • When creating an instance of the component, you can easily see how to configure it. You just have to look at its constructor parameters. You don't have to search through all classes to find static fields that hold configuration.
  • You can prevent other classes from messing with the component's configuration by giving it a separate instances of the dependency. There is no problem with rogue threads that modify the globally accessible configuration concurrently.
  • You can inject different implementations of the dependency without modifying the component code. This is especially useful for unit tests, where you want to inject mock services that don't do any business logic, but are instead used to validate service calls.

  • So, if you can do all this with plain old Java, what do you need the Spring IoC container for? Well, the Spring IoC container really is just what the Application class was in my previous examples. It keeps track of dependencies and their life times, and injects those dependencies into components that need them. You could just have well written your own main application class that kicks off a HTTP server and injects services into controllers and then routes requests to those controllers. But why write this infrastructure for every web application when you can just write it as a framework once? Spring is one such framework.
     
    Tim Holloway
    Saloon Keeper
    Posts: 22671
    153
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Actually, I take exception with Stephan's example. He's injecting the dependency at construction time. While some IoC frameworks such as Spring permit this, others do not. JSF, for example. The "ideal" POJO always has a no-argument constructor.  JPA, in fact requires that JPA Entity Beans have a no-element constructor.

    What's more important for classical IoC is that there be a post-construction injection method ("set" method).
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 12432
    269
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    It's true, some IoC frameworks require the components to be JavaBeans: Classes that provide at least a visible zero-parameter constructor, and have getters/setters that follow a specific naming scheme.

    I would not call this 'classic' IoC though, because IoC was a thing before JavaBeans were a thing. Regardless of what you want to call it, I do strongly recommend using constructor injection if the framework allows for it. Spring allows it through the @Autowired annotation and CDI applications allow it through the @Inject annotation.
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 12432
    269
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    For completeness, I'll also give an example of the application that uses the JavaBeans convention:
     
    Tim Holloway
    Saloon Keeper
    Posts: 22671
    153
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    That's not what @Autowired/@Inject is.

    In my "Spring In Action" book, parameterized construction is listed as a secondary means of injection. The primary focus was on POJOs with injector methods.

    @Autowired is a directive to the framework. When attached to a bean property, it declares to Spring that a default bean name (based on its classname) is to be located/constructed and injected by the BeanFactory into the target bean. But that's not done as part of the construction of that bean, it's done by the BeanFactory after it constructs the bean but before the BeanFactory returns the bean to its requester (which may in many instances itself be the BeanFactory).

    The @Autowired annotation is actually a default. If the Spring BeanFactory finds a superceding directive, such as might be obtained from a Spring applicationContext.xml file, then the @Autowired directive is ignored. Likewise, if applicationContext.xml directs that a bean have additional properties injected that do not have @Autowired annotations, the Bean factory will do so.
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 12432
    269
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Tim Holloway wrote:In my "Spring In Action" book, parameterized construction is listed as a secondary means of injection.


    I never said that @Autowired was initially written with this in mind. I said that Spring allows constructor injection by annotating the constructor with @Autowired, in which case you can omit a zero-parameter constructor. I also said that one should prefer this option if possible. What are constructors for, after all, if not for initializing the component?

    [edit]

    Spring allows constructor injection without the use of the @Autowired annotation if it is the only constructor, but you can use it if you have multiple constructors.
     
    Tim Holloway
    Saloon Keeper
    Posts: 22671
    153
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Actually, if I recall properly, the parameterized construction facility was presented in the Spring In Action book as a way to support legacy classes. As I said, they primarily promoted POJOs.

    In the IoC world, construction is usually limited to the internal properties of the bean at hand. And Spring is a bit of an outlier. As I said, JavaServer Faces doesn't have any means at all to present parameters to a constructor. So any bean designed to require parameters is ineligible for use as a JSF Managed Bean. Nor could you use such an object as a JPA Entity object. And there are probably other systems equally intolerant, although I mention the ones I'm most familiar with.

    In short, if you really want IoC and all of its benefits, it's best not to inject in the constructor.
     
    Bring out your dead! Or a tiny ad:
    the value of filler advertising in 2020
    https://coderanch.com/t/730886/filler-advertising
    reply
      Bookmark Topic Watch Topic
    • New Topic